quantumapi 0.22.0__tar.gz → 0.23.0__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.
- {quantumapi-0.22.0/quantumapi.egg-info → quantumapi-0.23.0}/PKG-INFO +28 -1
- {quantumapi-0.22.0 → quantumapi-0.23.0}/README.md +27 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/pyproject.toml +1 -1
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/__init__.py +6 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/async_client.py +2 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/base.py +21 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/keys.py +142 -1
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/sync_client.py +1 -0
- quantumapi-0.23.0/quantumapi/client/transit.py +192 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/errors/__init__.py +6 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/errors/exceptions.py +38 -4
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/health.py +6 -2
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/keys.py +51 -11
- quantumapi-0.23.0/quantumapi/models/transit.py +196 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0/quantumapi.egg-info}/PKG-INFO +28 -1
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi.egg-info/SOURCES.txt +5 -1
- quantumapi-0.23.0/tests/test_data_keys.py +121 -0
- quantumapi-0.23.0/tests/test_transit.py +209 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/LICENSE +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/__init__.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/applications.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/audit.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/encryption.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/end_users.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/health.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/qrng.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/resource_groups.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/roles.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/client/secrets.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/__init__.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/applications.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/audit.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/encryption.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/end_users.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/qrng.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/resource_groups.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/roles.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/models/secrets.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi/py.typed +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi.egg-info/dependency_links.txt +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi.egg-info/requires.txt +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/quantumapi.egg-info/top_level.txt +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/setup.cfg +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/tests/test_audit.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/tests/test_end_users.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/tests/test_exceptions.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/tests/test_models.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/tests/test_parity.py +0 -0
- {quantumapi-0.22.0 → quantumapi-0.23.0}/tests/test_qrng.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: quantumapi
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.23.0
|
|
4
4
|
Summary: Official Python SDK for QuantumAPI - Quantum-safe encryption and identity platform
|
|
5
5
|
Author-email: QuantumAPI Team <developers@quantumapi.eu>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -375,6 +375,33 @@ rate_limit = await client.health.rate_limit()
|
|
|
375
375
|
print(f"Remaining: {rate_limit.remaining}/{rate_limit.limit}")
|
|
376
376
|
```
|
|
377
377
|
|
|
378
|
+
### Transit (encryption as a service)
|
|
379
|
+
|
|
380
|
+
`client.transit` encrypts, decrypts, rewraps, signs and MACs with named keys. Raw `bytes` are
|
|
381
|
+
base64-encoded for you; a `str` is sent as-is (the API wire format is base64).
|
|
382
|
+
|
|
383
|
+
```python
|
|
384
|
+
key = await client.transit.create_key("orders") # POST /api/v1/keys
|
|
385
|
+
enc = await client.transit.encrypt("orders", b"4111 1111 1111") # vault:v1:...
|
|
386
|
+
dec = await client.transit.decrypt("orders", enc.ciphertext)
|
|
387
|
+
assert dec.plaintext_bytes == b"4111 1111 1111"
|
|
388
|
+
|
|
389
|
+
await client.transit.rotate_key(key.id) # new version
|
|
390
|
+
new = await client.transit.rewrap("orders", enc.ciphertext) # moves to the latest version
|
|
391
|
+
|
|
392
|
+
dk = await client.transit.generate_data_key("orders", key_bytes=32) # envelope encryption
|
|
393
|
+
mac = await client.transit.hmac("orders", b"payload", algorithm="sha256")
|
|
394
|
+
sig = await client.transit.sign("signing-key", b"payload")
|
|
395
|
+
await client.transit.set_min_decryption_version("orders", 2) # older versions then raise KeyVersionBelowMinimumError
|
|
396
|
+
history = await client.keys.list_versions(key.id) # versions[] with state and dates
|
|
397
|
+
rows = await client.keys.list(all_versions=True) # per-version rows (default: one row per key)
|
|
398
|
+
ok = (await client.transit.verify("signing-key", b"payload", sig.signature)).valid
|
|
399
|
+
batch = await client.transit.batch_encrypt("orders", [b"a", b"b"]) # up to 100 items
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
Errors: `KeyRevokedError` (403 `key_revoked`) and `InsufficientScopeError` (403 `insufficient_scope`),
|
|
403
|
+
both subclasses of `PermissionError`.
|
|
404
|
+
|
|
378
405
|
## Error Handling
|
|
379
406
|
|
|
380
407
|
The SDK provides typed exceptions for all error scenarios:
|
|
@@ -334,6 +334,33 @@ rate_limit = await client.health.rate_limit()
|
|
|
334
334
|
print(f"Remaining: {rate_limit.remaining}/{rate_limit.limit}")
|
|
335
335
|
```
|
|
336
336
|
|
|
337
|
+
### Transit (encryption as a service)
|
|
338
|
+
|
|
339
|
+
`client.transit` encrypts, decrypts, rewraps, signs and MACs with named keys. Raw `bytes` are
|
|
340
|
+
base64-encoded for you; a `str` is sent as-is (the API wire format is base64).
|
|
341
|
+
|
|
342
|
+
```python
|
|
343
|
+
key = await client.transit.create_key("orders") # POST /api/v1/keys
|
|
344
|
+
enc = await client.transit.encrypt("orders", b"4111 1111 1111") # vault:v1:...
|
|
345
|
+
dec = await client.transit.decrypt("orders", enc.ciphertext)
|
|
346
|
+
assert dec.plaintext_bytes == b"4111 1111 1111"
|
|
347
|
+
|
|
348
|
+
await client.transit.rotate_key(key.id) # new version
|
|
349
|
+
new = await client.transit.rewrap("orders", enc.ciphertext) # moves to the latest version
|
|
350
|
+
|
|
351
|
+
dk = await client.transit.generate_data_key("orders", key_bytes=32) # envelope encryption
|
|
352
|
+
mac = await client.transit.hmac("orders", b"payload", algorithm="sha256")
|
|
353
|
+
sig = await client.transit.sign("signing-key", b"payload")
|
|
354
|
+
await client.transit.set_min_decryption_version("orders", 2) # older versions then raise KeyVersionBelowMinimumError
|
|
355
|
+
history = await client.keys.list_versions(key.id) # versions[] with state and dates
|
|
356
|
+
rows = await client.keys.list(all_versions=True) # per-version rows (default: one row per key)
|
|
357
|
+
ok = (await client.transit.verify("signing-key", b"payload", sig.signature)).valid
|
|
358
|
+
batch = await client.transit.batch_encrypt("orders", [b"a", b"b"]) # up to 100 items
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Errors: `KeyRevokedError` (403 `key_revoked`) and `InsufficientScopeError` (403 `insufficient_scope`),
|
|
362
|
+
both subclasses of `PermissionError`.
|
|
363
|
+
|
|
337
364
|
## Error Handling
|
|
338
365
|
|
|
339
366
|
The SDK provides typed exceptions for all error scenarios:
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "quantumapi"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.23.0"
|
|
8
8
|
description = "Official Python SDK for QuantumAPI - Quantum-safe encryption and identity platform"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -18,6 +18,9 @@ from quantumapi.client.sync_client import QuantumAPISyncClient
|
|
|
18
18
|
from quantumapi.errors.exceptions import (
|
|
19
19
|
AuthenticationError,
|
|
20
20
|
ConflictError,
|
|
21
|
+
InsufficientScopeError,
|
|
22
|
+
KeyRevokedError,
|
|
23
|
+
KeyVersionBelowMinimumError,
|
|
21
24
|
NetworkError,
|
|
22
25
|
NotFoundError,
|
|
23
26
|
PermissionError,
|
|
@@ -37,6 +40,9 @@ __all__ = [
|
|
|
37
40
|
"QuantumAPIError",
|
|
38
41
|
"AuthenticationError",
|
|
39
42
|
"PermissionError",
|
|
43
|
+
"KeyRevokedError",
|
|
44
|
+
"KeyVersionBelowMinimumError",
|
|
45
|
+
"InsufficientScopeError",
|
|
40
46
|
"NotFoundError",
|
|
41
47
|
"ConflictError",
|
|
42
48
|
"RateLimitError",
|
|
@@ -14,6 +14,7 @@ from quantumapi.client.qrng import QrngClient
|
|
|
14
14
|
from quantumapi.client.resource_groups import ResourceGroupsClient
|
|
15
15
|
from quantumapi.client.roles import RolesClient
|
|
16
16
|
from quantumapi.client.secrets import SecretsClient
|
|
17
|
+
from quantumapi.client.transit import TransitClient
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
class QuantumAPIClient:
|
|
@@ -91,6 +92,7 @@ class QuantumAPIClient:
|
|
|
91
92
|
self.roles = RolesClient(self._base_client)
|
|
92
93
|
self.health = HealthClient(self._base_client)
|
|
93
94
|
self.qrng = QrngClient(self._base_client)
|
|
95
|
+
self.transit = TransitClient(self._base_client)
|
|
94
96
|
|
|
95
97
|
async def close(self) -> None:
|
|
96
98
|
"""
|
|
@@ -10,6 +10,9 @@ from httpx import Response
|
|
|
10
10
|
from quantumapi.errors import (
|
|
11
11
|
AuthenticationError,
|
|
12
12
|
ConflictError,
|
|
13
|
+
InsufficientScopeError,
|
|
14
|
+
KeyVersionBelowMinimumError,
|
|
15
|
+
KeyRevokedError,
|
|
13
16
|
NetworkError,
|
|
14
17
|
NotFoundError,
|
|
15
18
|
PermissionError,
|
|
@@ -129,6 +132,24 @@ class BaseClient:
|
|
|
129
132
|
status_code=401,
|
|
130
133
|
)
|
|
131
134
|
elif response.status_code == 403:
|
|
135
|
+
if error_code == "key_revoked":
|
|
136
|
+
raise KeyRevokedError(
|
|
137
|
+
message=error_message,
|
|
138
|
+
error_code=error_code,
|
|
139
|
+
details=error_details,
|
|
140
|
+
)
|
|
141
|
+
if error_code == "key_version_below_minimum":
|
|
142
|
+
raise KeyVersionBelowMinimumError(
|
|
143
|
+
message=error_message,
|
|
144
|
+
error_code=error_code,
|
|
145
|
+
details=error_details,
|
|
146
|
+
)
|
|
147
|
+
if error_code == "insufficient_scope":
|
|
148
|
+
raise InsufficientScopeError(
|
|
149
|
+
message=error_message,
|
|
150
|
+
error_code=error_code,
|
|
151
|
+
details=error_details,
|
|
152
|
+
)
|
|
132
153
|
raise PermissionError(
|
|
133
154
|
message=error_message,
|
|
134
155
|
error_code=error_code,
|
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
from datetime import datetime, timezone
|
|
4
4
|
from typing import List, Optional
|
|
5
|
+
from urllib.parse import quote
|
|
5
6
|
from uuid import UUID
|
|
6
7
|
|
|
7
8
|
from quantumapi.client.base import BaseClient
|
|
9
|
+
from quantumapi.models.transit import KeyVersionsResponse, TransitKeyConfigResponse
|
|
8
10
|
from quantumapi.models.keys import (
|
|
11
|
+
GenerateDataKeyResponse,
|
|
9
12
|
GenerateKeyRequest,
|
|
10
13
|
ImportKeyRequest,
|
|
11
14
|
KeyHealthReport,
|
|
@@ -14,6 +17,7 @@ from quantumapi.models.keys import (
|
|
|
14
17
|
KeyType,
|
|
15
18
|
PublicKeyResponse,
|
|
16
19
|
RotateKeyRequest,
|
|
20
|
+
UnwrapKeyResponse,
|
|
17
21
|
UpdateKeyRequest,
|
|
18
22
|
)
|
|
19
23
|
|
|
@@ -72,7 +76,21 @@ class KeysClient:
|
|
|
72
76
|
set_as_default=set_as_default,
|
|
73
77
|
labels=labels,
|
|
74
78
|
)
|
|
75
|
-
|
|
79
|
+
# The API names the purpose ``keyType`` (camelCase body); ``purpose`` is kept for older servers.
|
|
80
|
+
body = {
|
|
81
|
+
"name": request.name,
|
|
82
|
+
"keyType": request.key_type.value,
|
|
83
|
+
"purpose": request.key_type.value,
|
|
84
|
+
"algorithm": request.algorithm,
|
|
85
|
+
"setAsDefault": request.set_as_default,
|
|
86
|
+
}
|
|
87
|
+
if description is not None:
|
|
88
|
+
body["description"] = description
|
|
89
|
+
if expires_at is not None:
|
|
90
|
+
body["expiresAt"] = request.expires_at.isoformat()
|
|
91
|
+
if labels is not None:
|
|
92
|
+
body["labels"] = labels
|
|
93
|
+
response = await self._client.post("/api/v1/keys", json_data=body)
|
|
76
94
|
return KeyResponse(**response)
|
|
77
95
|
|
|
78
96
|
async def import_key(
|
|
@@ -136,6 +154,7 @@ class KeysClient:
|
|
|
136
154
|
status: Optional[str] = None,
|
|
137
155
|
page: int = 1,
|
|
138
156
|
page_size: int = 50,
|
|
157
|
+
all_versions: bool = False,
|
|
139
158
|
) -> KeyListResponse:
|
|
140
159
|
"""
|
|
141
160
|
List cryptographic keys.
|
|
@@ -145,6 +164,7 @@ class KeysClient:
|
|
|
145
164
|
status: Filter by status (active, inactive, scheduled_deletion)
|
|
146
165
|
page: Page number
|
|
147
166
|
page_size: Number of items per page
|
|
167
|
+
all_versions: Return one row per key version instead of one row per key
|
|
148
168
|
|
|
149
169
|
Returns:
|
|
150
170
|
List of keys with pagination info
|
|
@@ -159,10 +179,28 @@ class KeysClient:
|
|
|
159
179
|
params["keyType"] = key_type.value
|
|
160
180
|
if status:
|
|
161
181
|
params["status"] = status
|
|
182
|
+
if all_versions:
|
|
183
|
+
params["allVersions"] = "true"
|
|
162
184
|
|
|
163
185
|
response = await self._client.get("/api/v1/keys", params=params)
|
|
164
186
|
return KeyListResponse(**response)
|
|
165
187
|
|
|
188
|
+
async def list_versions(self, key_id: UUID) -> KeyVersionsResponse:
|
|
189
|
+
"""List the version history of a key (``GET /api/v1/keys/{id}/versions``)."""
|
|
190
|
+
return KeyVersionsResponse(**await self._client.get(f"/api/v1/keys/{key_id}/versions"))
|
|
191
|
+
|
|
192
|
+
async def set_min_decryption_version(
|
|
193
|
+
self, key_id: UUID, min_decryption_version: int
|
|
194
|
+
) -> TransitKeyConfigResponse:
|
|
195
|
+
"""Set the minimum decryption version (``PUT /api/v1/keys/{id}/min-decryption-version``).
|
|
196
|
+
|
|
197
|
+
Raises ``ValidationError`` (400 ``invalid_min_decryption_version``) when out of range."""
|
|
198
|
+
response = await self._client.put(
|
|
199
|
+
f"/api/v1/keys/{key_id}/min-decryption-version",
|
|
200
|
+
json_data={"minDecryptionVersion": min_decryption_version},
|
|
201
|
+
)
|
|
202
|
+
return TransitKeyConfigResponse(**response)
|
|
203
|
+
|
|
166
204
|
async def get(self, key_id: UUID) -> KeyResponse:
|
|
167
205
|
"""
|
|
168
206
|
Get key details by ID.
|
|
@@ -329,6 +367,109 @@ class KeysClient:
|
|
|
329
367
|
)
|
|
330
368
|
return PublicKeyResponse(**response)
|
|
331
369
|
|
|
370
|
+
@staticmethod
|
|
371
|
+
def _data_key_body(
|
|
372
|
+
key_bytes: Optional[int], algorithm: Optional[str], context: Optional[str]
|
|
373
|
+
) -> dict:
|
|
374
|
+
body: dict = {}
|
|
375
|
+
if algorithm is not None:
|
|
376
|
+
body["algorithm"] = algorithm
|
|
377
|
+
if key_bytes is not None:
|
|
378
|
+
body["keyBytes"] = key_bytes
|
|
379
|
+
if context is not None:
|
|
380
|
+
body["context"] = context
|
|
381
|
+
return body
|
|
382
|
+
|
|
383
|
+
async def generate_data_key(
|
|
384
|
+
self,
|
|
385
|
+
key_id: UUID,
|
|
386
|
+
key_bytes: Optional[int] = None,
|
|
387
|
+
algorithm: Optional[str] = None,
|
|
388
|
+
context: Optional[str] = None,
|
|
389
|
+
) -> GenerateDataKeyResponse:
|
|
390
|
+
"""
|
|
391
|
+
Generate a data key for envelope encryption
|
|
392
|
+
(``POST /api/v1/keys/{key_id}/generate-data-key``).
|
|
393
|
+
|
|
394
|
+
Args:
|
|
395
|
+
key_id: Master key that wraps the data key
|
|
396
|
+
key_bytes: Data key length: 16, 24 or 32 (server default 32)
|
|
397
|
+
algorithm: Data key algorithm label (server default AES-256-GCM)
|
|
398
|
+
context: Optional base64 encryption context (AAD); pass it again on unwrap
|
|
399
|
+
|
|
400
|
+
Returns:
|
|
401
|
+
Plaintext and encrypted data key
|
|
402
|
+
"""
|
|
403
|
+
response = await self._client.post(
|
|
404
|
+
f"/api/v1/keys/{key_id}/generate-data-key",
|
|
405
|
+
json_data=self._data_key_body(key_bytes, algorithm, context),
|
|
406
|
+
)
|
|
407
|
+
return GenerateDataKeyResponse(**response)
|
|
408
|
+
|
|
409
|
+
async def generate_data_key_without_plaintext(
|
|
410
|
+
self,
|
|
411
|
+
key_id: UUID,
|
|
412
|
+
key_bytes: Optional[int] = None,
|
|
413
|
+
algorithm: Optional[str] = None,
|
|
414
|
+
context: Optional[str] = None,
|
|
415
|
+
) -> GenerateDataKeyResponse:
|
|
416
|
+
"""Like :meth:`generate_data_key` but ``plaintext_key`` is None
|
|
417
|
+
(``POST /api/v1/keys/{key_id}/generate-data-key-without-plaintext``)."""
|
|
418
|
+
response = await self._client.post(
|
|
419
|
+
f"/api/v1/keys/{key_id}/generate-data-key-without-plaintext",
|
|
420
|
+
json_data=self._data_key_body(key_bytes, algorithm, context),
|
|
421
|
+
)
|
|
422
|
+
return GenerateDataKeyResponse(**response)
|
|
423
|
+
|
|
424
|
+
async def generate_transit_data_key(
|
|
425
|
+
self,
|
|
426
|
+
key_name: str,
|
|
427
|
+
key_bytes: Optional[int] = None,
|
|
428
|
+
algorithm: Optional[str] = None,
|
|
429
|
+
context: Optional[str] = None,
|
|
430
|
+
) -> GenerateDataKeyResponse:
|
|
431
|
+
"""Generate a data key with a named Transit key
|
|
432
|
+
(``POST /api/v1/transit/datakey/{key_name}``)."""
|
|
433
|
+
response = await self._client.post(
|
|
434
|
+
f"/api/v1/transit/datakey/{quote(key_name, safe='')}",
|
|
435
|
+
json_data=self._data_key_body(key_bytes, algorithm, context),
|
|
436
|
+
)
|
|
437
|
+
return GenerateDataKeyResponse(**response)
|
|
438
|
+
|
|
439
|
+
async def generate_transit_data_key_without_plaintext(
|
|
440
|
+
self,
|
|
441
|
+
key_name: str,
|
|
442
|
+
key_bytes: Optional[int] = None,
|
|
443
|
+
algorithm: Optional[str] = None,
|
|
444
|
+
context: Optional[str] = None,
|
|
445
|
+
) -> GenerateDataKeyResponse:
|
|
446
|
+
"""Transit data key without plaintext
|
|
447
|
+
(``POST /api/v1/transit/datakey/{key_name}/without-plaintext``)."""
|
|
448
|
+
response = await self._client.post(
|
|
449
|
+
f"/api/v1/transit/datakey/{quote(key_name, safe='')}/without-plaintext",
|
|
450
|
+
json_data=self._data_key_body(key_bytes, algorithm, context),
|
|
451
|
+
)
|
|
452
|
+
return GenerateDataKeyResponse(**response)
|
|
453
|
+
|
|
454
|
+
async def unwrap(
|
|
455
|
+
self,
|
|
456
|
+
key_id: UUID,
|
|
457
|
+
wrapped_key: str,
|
|
458
|
+
context: Optional[str] = None,
|
|
459
|
+
) -> UnwrapKeyResponse:
|
|
460
|
+
"""
|
|
461
|
+
Unwrap a wrapped key, or the ``encrypted_key`` of a data key, with the master key
|
|
462
|
+
(``POST /api/v1/keys/{key_id}/unwrap``).
|
|
463
|
+
|
|
464
|
+
Raises:
|
|
465
|
+
KeyRevokedError: HTTP 403 ``key_revoked`` when the master key was revoked
|
|
466
|
+
"""
|
|
467
|
+
body = {"wrappedKey": wrapped_key}
|
|
468
|
+
if context is not None:
|
|
469
|
+
body["context"] = context
|
|
470
|
+
response = await self._client.post(f"/api/v1/keys/{key_id}/unwrap", json_data=body)
|
|
471
|
+
return UnwrapKeyResponse(**response)
|
|
472
|
+
|
|
332
473
|
async def check(self, key_id: UUID) -> KeyHealthReport:
|
|
333
474
|
"""
|
|
334
475
|
Check the health of a key.
|
|
@@ -108,6 +108,7 @@ class QuantumAPISyncClient:
|
|
|
108
108
|
self.roles = _SyncProxy(self._async_client.roles)
|
|
109
109
|
self.health = _SyncProxy(self._async_client.health)
|
|
110
110
|
self.qrng = _SyncProxy(self._async_client.qrng)
|
|
111
|
+
self.transit = _SyncProxy(self._async_client.transit)
|
|
111
112
|
|
|
112
113
|
def close(self) -> None:
|
|
113
114
|
"""Close HTTP client connections."""
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Transit client for QuantumAPI SDK (``/api/v1/transit``).
|
|
2
|
+
|
|
3
|
+
Errors: ``PermissionError`` (403), ``InsufficientScopeError`` (403 ``insufficient_scope``),
|
|
4
|
+
``KeyRevokedError`` (403 ``key_revoked``),
|
|
5
|
+
``KeyVersionBelowMinimumError`` (403 ``key_version_below_minimum`` on decrypt, rewrap, verify,
|
|
6
|
+
batch decrypt), ``NotFoundError``, ``ValidationError``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
from typing import Any, Dict, List, Optional, Union
|
|
11
|
+
from urllib.parse import quote
|
|
12
|
+
from uuid import UUID
|
|
13
|
+
|
|
14
|
+
from quantumapi.client.base import BaseClient
|
|
15
|
+
from quantumapi.models.transit import (
|
|
16
|
+
TransitKeyConfigResponse,
|
|
17
|
+
TransitBatchDecryptResponse,
|
|
18
|
+
TransitBatchEncryptResponse,
|
|
19
|
+
TransitDataKeyResponse,
|
|
20
|
+
TransitDecryptResponse,
|
|
21
|
+
TransitEncryptResponse,
|
|
22
|
+
TransitHmacResponse,
|
|
23
|
+
TransitKey,
|
|
24
|
+
TransitRewrapResponse,
|
|
25
|
+
TransitRotateKeyResponse,
|
|
26
|
+
TransitSignResponse,
|
|
27
|
+
TransitVerifyResponse,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
Bytesish = Union[str, bytes]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _b64(data: Bytesish) -> str:
|
|
34
|
+
"""Raw bytes are base64-encoded; a str is assumed to be base64 already (the API wire format)."""
|
|
35
|
+
if isinstance(data, (bytes, bytearray)):
|
|
36
|
+
return base64.b64encode(bytes(data)).decode("ascii")
|
|
37
|
+
return data
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _plaintext(value: Bytesish) -> str:
|
|
41
|
+
return _b64(value) if isinstance(value, (bytes, bytearray)) else value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TransitClient:
|
|
45
|
+
"""Encryption-as-a-service on named keys: encrypt, decrypt, rewrap, data keys, HMAC, sign/verify."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, base_client: BaseClient) -> None:
|
|
48
|
+
self._client = base_client
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def _path(op: str, key_name: str, suffix: str = "") -> str:
|
|
52
|
+
return f"/api/v1/transit/{op}/{quote(key_name, safe='')}{suffix}"
|
|
53
|
+
|
|
54
|
+
async def encrypt(
|
|
55
|
+
self, key_name: str, plaintext: Bytesish, encoding: Optional[str] = None
|
|
56
|
+
) -> TransitEncryptResponse:
|
|
57
|
+
"""Encrypt with the latest version of a named key.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
key_name: Transit key name
|
|
61
|
+
plaintext: Raw ``bytes`` (sent as base64), or a ``str``: base64 by default, or UTF-8
|
|
62
|
+
text when ``encoding="utf8"``
|
|
63
|
+
encoding: ``"base64"`` (server default) or ``"utf8"``; only sent when given
|
|
64
|
+
|
|
65
|
+
Example:
|
|
66
|
+
>>> out = await client.transit.encrypt("orders", b"4111 1111")
|
|
67
|
+
>>> out.ciphertext # vault:v1:...
|
|
68
|
+
"""
|
|
69
|
+
body: Dict[str, Any] = {"plaintext": _plaintext(plaintext)}
|
|
70
|
+
if encoding is not None:
|
|
71
|
+
body["encoding"] = encoding
|
|
72
|
+
return TransitEncryptResponse(**await self._client.post(self._path("encrypt", key_name), json_data=body))
|
|
73
|
+
|
|
74
|
+
async def decrypt(self, key_name: str, ciphertext: str) -> TransitDecryptResponse:
|
|
75
|
+
"""Decrypt a ``vault:v{n}:...`` ciphertext. ``result.plaintext`` is base64;
|
|
76
|
+
``result.plaintext_bytes`` is the raw bytes."""
|
|
77
|
+
return TransitDecryptResponse(
|
|
78
|
+
**await self._client.post(self._path("decrypt", key_name), json_data={"ciphertext": ciphertext})
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
async def rewrap(self, key_name: str, ciphertext: str) -> TransitRewrapResponse:
|
|
82
|
+
"""Re-encrypt a ciphertext under the latest key version without exposing the plaintext."""
|
|
83
|
+
return TransitRewrapResponse(
|
|
84
|
+
**await self._client.post(self._path("rewrap", key_name), json_data={"ciphertext": ciphertext})
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
async def generate_data_key(
|
|
88
|
+
self,
|
|
89
|
+
key_name: str,
|
|
90
|
+
key_bytes: Optional[int] = None,
|
|
91
|
+
algorithm: Optional[str] = None,
|
|
92
|
+
context: Optional[str] = None,
|
|
93
|
+
include_plaintext: bool = True,
|
|
94
|
+
) -> TransitDataKeyResponse:
|
|
95
|
+
"""Generate a data key for envelope encryption
|
|
96
|
+
(``/transit/datakey/{name}`` or ``.../without-plaintext`` when ``include_plaintext=False``)."""
|
|
97
|
+
body: Dict[str, Any] = {}
|
|
98
|
+
if algorithm is not None:
|
|
99
|
+
body["algorithm"] = algorithm
|
|
100
|
+
if key_bytes is not None:
|
|
101
|
+
body["keyBytes"] = key_bytes
|
|
102
|
+
if context is not None:
|
|
103
|
+
body["context"] = context
|
|
104
|
+
suffix = "" if include_plaintext else "/without-plaintext"
|
|
105
|
+
return TransitDataKeyResponse(
|
|
106
|
+
**await self._client.post(self._path("datakey", key_name, suffix), json_data=body)
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
async def hmac(self, key_name: str, data: Bytesish, algorithm: Optional[str] = None) -> TransitHmacResponse:
|
|
110
|
+
"""HMAC of ``data`` (sha256 default; sha384, sha512)."""
|
|
111
|
+
body: Dict[str, Any] = {"data": _b64(data)}
|
|
112
|
+
if algorithm is not None:
|
|
113
|
+
body["algorithm"] = algorithm
|
|
114
|
+
return TransitHmacResponse(**await self._client.post(self._path("hmac", key_name), json_data=body))
|
|
115
|
+
|
|
116
|
+
async def sign(self, key_name: str, data: Bytesish, algorithm: Optional[str] = None) -> TransitSignResponse:
|
|
117
|
+
"""Sign ``data`` with a signing key (ML-DSA or classical)."""
|
|
118
|
+
body: Dict[str, Any] = {"data": _b64(data)}
|
|
119
|
+
if algorithm is not None:
|
|
120
|
+
body["algorithm"] = algorithm
|
|
121
|
+
return TransitSignResponse(**await self._client.post(self._path("sign", key_name), json_data=body))
|
|
122
|
+
|
|
123
|
+
async def verify(self, key_name: str, data: Bytesish, signature: str) -> TransitVerifyResponse:
|
|
124
|
+
"""Verify a signature produced by :meth:`sign`."""
|
|
125
|
+
return TransitVerifyResponse(
|
|
126
|
+
**await self._client.post(
|
|
127
|
+
self._path("verify", key_name), json_data={"data": _b64(data), "signature": signature}
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
async def batch_encrypt(
|
|
132
|
+
self, key_name: str, items: List[Bytesish], encoding: Optional[str] = None
|
|
133
|
+
) -> TransitBatchEncryptResponse:
|
|
134
|
+
"""Encrypt up to 100 items; failed items carry ``error`` instead of ``ciphertext``."""
|
|
135
|
+
payload = []
|
|
136
|
+
for item in items:
|
|
137
|
+
entry: Dict[str, Any] = {"plaintext": _plaintext(item)}
|
|
138
|
+
if encoding is not None:
|
|
139
|
+
entry["encoding"] = encoding
|
|
140
|
+
payload.append(entry)
|
|
141
|
+
return TransitBatchEncryptResponse(
|
|
142
|
+
**await self._client.post(self._path("batch/encrypt", key_name), json_data={"items": payload})
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
async def batch_decrypt(self, key_name: str, ciphertexts: List[str]) -> TransitBatchDecryptResponse:
|
|
146
|
+
"""Decrypt up to 100 ciphertexts (items may use different key versions)."""
|
|
147
|
+
return TransitBatchDecryptResponse(
|
|
148
|
+
**await self._client.post(
|
|
149
|
+
self._path("batch/decrypt", key_name),
|
|
150
|
+
json_data={"items": [{"ciphertext": c} for c in ciphertexts]},
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# -- Key lifecycle (named Transit keys live in the Keys API) -----------------------------
|
|
155
|
+
|
|
156
|
+
async def create_key(
|
|
157
|
+
self,
|
|
158
|
+
name: str,
|
|
159
|
+
key_type: str = "encryption",
|
|
160
|
+
algorithm: str = "ML-KEM-768",
|
|
161
|
+
description: Optional[str] = None,
|
|
162
|
+
labels: Optional[List[str]] = None,
|
|
163
|
+
) -> TransitKey:
|
|
164
|
+
"""Create a named key (``POST /api/v1/keys``; body uses the API's ``keyType`` field)."""
|
|
165
|
+
body: Dict[str, Any] = {"name": name, "keyType": key_type, "algorithm": algorithm}
|
|
166
|
+
if description is not None:
|
|
167
|
+
body["description"] = description
|
|
168
|
+
if labels is not None:
|
|
169
|
+
body["labels"] = labels
|
|
170
|
+
return TransitKey(**await self._client.post("/api/v1/keys", json_data=body))
|
|
171
|
+
|
|
172
|
+
async def get_key(self, key_id: UUID) -> TransitKey:
|
|
173
|
+
"""Read key metadata (``GET /api/v1/keys/{id}``)."""
|
|
174
|
+
return TransitKey(**await self._client.get(f"/api/v1/keys/{key_id}"))
|
|
175
|
+
|
|
176
|
+
async def set_min_decryption_version(
|
|
177
|
+
self, key_name: str, min_decryption_version: int
|
|
178
|
+
) -> TransitKeyConfigResponse:
|
|
179
|
+
"""Set the minimum decryption version (``POST /api/v1/transit/keys/{name}/config``).
|
|
180
|
+
|
|
181
|
+
Older versions then fail with ``KeyVersionBelowMinimumError``; rewrap first. Raises
|
|
182
|
+
``ValidationError`` (400 ``invalid_min_decryption_version``) when out of range."""
|
|
183
|
+
response = await self._client.post(
|
|
184
|
+
f"/api/v1/transit/keys/{quote(key_name, safe='')}/config",
|
|
185
|
+
json_data={"minDecryptionVersion": min_decryption_version},
|
|
186
|
+
)
|
|
187
|
+
return TransitKeyConfigResponse(**response)
|
|
188
|
+
|
|
189
|
+
async def rotate_key(self, key_id: UUID) -> TransitRotateKeyResponse:
|
|
190
|
+
"""Rotate a key to a new version (``POST /api/v1/keys/{id}/rotate``). Older ciphertexts
|
|
191
|
+
stay decryptable; call :meth:`rewrap` to move them to the new version."""
|
|
192
|
+
return TransitRotateKeyResponse(**await self._client.post(f"/api/v1/keys/{key_id}/rotate"))
|
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
from quantumapi.errors.exceptions import (
|
|
4
4
|
AuthenticationError,
|
|
5
5
|
ConflictError,
|
|
6
|
+
InsufficientScopeError,
|
|
6
7
|
InvalidRequestError,
|
|
8
|
+
KeyRevokedError,
|
|
9
|
+
KeyVersionBelowMinimumError,
|
|
7
10
|
NetworkError,
|
|
8
11
|
NotFoundError,
|
|
9
12
|
PermissionError,
|
|
@@ -18,6 +21,9 @@ __all__ = [
|
|
|
18
21
|
"QuantumAPIError",
|
|
19
22
|
"AuthenticationError",
|
|
20
23
|
"PermissionError",
|
|
24
|
+
"KeyRevokedError",
|
|
25
|
+
"KeyVersionBelowMinimumError",
|
|
26
|
+
"InsufficientScopeError",
|
|
21
27
|
"NotFoundError",
|
|
22
28
|
"ConflictError",
|
|
23
29
|
"ValidationError",
|
|
@@ -40,7 +40,8 @@ class AuthenticationError(QuantumAPIError):
|
|
|
40
40
|
|
|
41
41
|
def __init__(self, message: str = "Authentication failed", **kwargs: Any) -> None:
|
|
42
42
|
"""Initialize AuthenticationError."""
|
|
43
|
-
|
|
43
|
+
kwargs.setdefault("status_code", 401)
|
|
44
|
+
super().__init__(message, **kwargs)
|
|
44
45
|
|
|
45
46
|
|
|
46
47
|
class PermissionError(QuantumAPIError):
|
|
@@ -48,7 +49,38 @@ class PermissionError(QuantumAPIError):
|
|
|
48
49
|
|
|
49
50
|
def __init__(self, message: str = "Permission denied", **kwargs: Any) -> None:
|
|
50
51
|
"""Initialize PermissionError."""
|
|
51
|
-
|
|
52
|
+
kwargs.setdefault("status_code", 403)
|
|
53
|
+
super().__init__(message, **kwargs)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class KeyRevokedError(PermissionError):
|
|
57
|
+
"""Raised on HTTP 403 ``key_revoked``: the key used for the operation was revoked."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, message: str = "Key has been revoked", **kwargs: Any) -> None:
|
|
60
|
+
"""Initialize KeyRevokedError."""
|
|
61
|
+
kwargs.setdefault("error_code", "key_revoked")
|
|
62
|
+
super().__init__(message, **kwargs)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class KeyVersionBelowMinimumError(PermissionError):
|
|
66
|
+
"""Raised on HTTP 403 ``key_version_below_minimum``: the ciphertext or signature was produced by
|
|
67
|
+
a key version older than the key's minimum decryption version (rewrap or re-sign it)."""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self, message: str = "Key version is below the minimum decryption version", **kwargs: Any
|
|
71
|
+
) -> None:
|
|
72
|
+
"""Initialize KeyVersionBelowMinimumError."""
|
|
73
|
+
kwargs.setdefault("error_code", "key_version_below_minimum")
|
|
74
|
+
super().__init__(message, **kwargs)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class InsufficientScopeError(PermissionError):
|
|
78
|
+
"""Raised on HTTP 403 ``insufficient_scope``: the API key lacks the scope the route needs."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, message: str = "API key lacks the required scope", **kwargs: Any) -> None:
|
|
81
|
+
"""Initialize InsufficientScopeError."""
|
|
82
|
+
kwargs.setdefault("error_code", "insufficient_scope")
|
|
83
|
+
super().__init__(message, **kwargs)
|
|
52
84
|
|
|
53
85
|
|
|
54
86
|
class NotFoundError(QuantumAPIError):
|
|
@@ -56,7 +88,8 @@ class NotFoundError(QuantumAPIError):
|
|
|
56
88
|
|
|
57
89
|
def __init__(self, message: str = "Resource not found", **kwargs: Any) -> None:
|
|
58
90
|
"""Initialize NotFoundError."""
|
|
59
|
-
|
|
91
|
+
kwargs.setdefault("status_code", 404)
|
|
92
|
+
super().__init__(message, **kwargs)
|
|
60
93
|
|
|
61
94
|
|
|
62
95
|
class ConflictError(QuantumAPIError):
|
|
@@ -73,7 +106,8 @@ class ValidationError(QuantumAPIError):
|
|
|
73
106
|
|
|
74
107
|
def __init__(self, message: str = "Validation failed", **kwargs: Any) -> None:
|
|
75
108
|
"""Initialize ValidationError."""
|
|
76
|
-
|
|
109
|
+
kwargs.setdefault("status_code", 400)
|
|
110
|
+
super().__init__(message, **kwargs)
|
|
77
111
|
|
|
78
112
|
|
|
79
113
|
class RateLimitError(QuantumAPIError):
|
|
@@ -8,9 +8,13 @@ from pydantic import BaseModel, Field
|
|
|
8
8
|
class HealthResponse(BaseModel):
|
|
9
9
|
"""Response model for API health check."""
|
|
10
10
|
|
|
11
|
-
status: str = Field(..., description="API status (
|
|
11
|
+
status: str = Field(..., description="API status as reported by /health (e.g. Healthy)")
|
|
12
12
|
version: str = Field(..., description="API version")
|
|
13
|
-
timestamp: str = Field(
|
|
13
|
+
timestamp: Optional[str] = Field(default=None, description="Current timestamp (not sent by the platform)")
|
|
14
|
+
git_sha: Optional[str] = Field(default=None, alias="gitSha", description="Deployed git commit")
|
|
15
|
+
service: Optional[str] = Field(default=None, description="Service name")
|
|
16
|
+
|
|
17
|
+
model_config = {"populate_by_name": True}
|
|
14
18
|
|
|
15
19
|
|
|
16
20
|
class VersionResponse(BaseModel):
|