quantumapi 0.22.1__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.
Files changed (49) hide show
  1. {quantumapi-0.22.1/quantumapi.egg-info → quantumapi-0.23.0}/PKG-INFO +28 -1
  2. {quantumapi-0.22.1 → quantumapi-0.23.0}/README.md +27 -0
  3. {quantumapi-0.22.1 → quantumapi-0.23.0}/pyproject.toml +1 -1
  4. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/__init__.py +4 -0
  5. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/async_client.py +2 -0
  6. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/base.py +14 -0
  7. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/keys.py +36 -1
  8. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/sync_client.py +1 -0
  9. quantumapi-0.23.0/quantumapi/client/transit.py +192 -0
  10. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/errors/__init__.py +4 -0
  11. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/errors/exceptions.py +21 -0
  12. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/health.py +6 -2
  13. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/keys.py +23 -11
  14. quantumapi-0.23.0/quantumapi/models/transit.py +196 -0
  15. {quantumapi-0.22.1 → quantumapi-0.23.0/quantumapi.egg-info}/PKG-INFO +28 -1
  16. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi.egg-info/SOURCES.txt +4 -1
  17. quantumapi-0.23.0/tests/test_transit.py +209 -0
  18. {quantumapi-0.22.1 → quantumapi-0.23.0}/LICENSE +0 -0
  19. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/__init__.py +0 -0
  20. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/applications.py +0 -0
  21. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/audit.py +0 -0
  22. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/encryption.py +0 -0
  23. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/end_users.py +0 -0
  24. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/health.py +0 -0
  25. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/qrng.py +0 -0
  26. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/resource_groups.py +0 -0
  27. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/roles.py +0 -0
  28. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/client/secrets.py +0 -0
  29. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/__init__.py +0 -0
  30. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/applications.py +0 -0
  31. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/audit.py +0 -0
  32. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/encryption.py +0 -0
  33. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/end_users.py +0 -0
  34. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/qrng.py +0 -0
  35. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/resource_groups.py +0 -0
  36. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/roles.py +0 -0
  37. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/models/secrets.py +0 -0
  38. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi/py.typed +0 -0
  39. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi.egg-info/dependency_links.txt +0 -0
  40. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi.egg-info/requires.txt +0 -0
  41. {quantumapi-0.22.1 → quantumapi-0.23.0}/quantumapi.egg-info/top_level.txt +0 -0
  42. {quantumapi-0.22.1 → quantumapi-0.23.0}/setup.cfg +0 -0
  43. {quantumapi-0.22.1 → quantumapi-0.23.0}/tests/test_audit.py +0 -0
  44. {quantumapi-0.22.1 → quantumapi-0.23.0}/tests/test_data_keys.py +0 -0
  45. {quantumapi-0.22.1 → quantumapi-0.23.0}/tests/test_end_users.py +0 -0
  46. {quantumapi-0.22.1 → quantumapi-0.23.0}/tests/test_exceptions.py +0 -0
  47. {quantumapi-0.22.1 → quantumapi-0.23.0}/tests/test_models.py +0 -0
  48. {quantumapi-0.22.1 → quantumapi-0.23.0}/tests/test_parity.py +0 -0
  49. {quantumapi-0.22.1 → 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.22.1
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.22.1"
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,7 +18,9 @@ from quantumapi.client.sync_client import QuantumAPISyncClient
18
18
  from quantumapi.errors.exceptions import (
19
19
  AuthenticationError,
20
20
  ConflictError,
21
+ InsufficientScopeError,
21
22
  KeyRevokedError,
23
+ KeyVersionBelowMinimumError,
22
24
  NetworkError,
23
25
  NotFoundError,
24
26
  PermissionError,
@@ -39,6 +41,8 @@ __all__ = [
39
41
  "AuthenticationError",
40
42
  "PermissionError",
41
43
  "KeyRevokedError",
44
+ "KeyVersionBelowMinimumError",
45
+ "InsufficientScopeError",
42
46
  "NotFoundError",
43
47
  "ConflictError",
44
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,8 @@ from httpx import Response
10
10
  from quantumapi.errors import (
11
11
  AuthenticationError,
12
12
  ConflictError,
13
+ InsufficientScopeError,
14
+ KeyVersionBelowMinimumError,
13
15
  KeyRevokedError,
14
16
  NetworkError,
15
17
  NotFoundError,
@@ -136,6 +138,18 @@ class BaseClient:
136
138
  error_code=error_code,
137
139
  details=error_details,
138
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
+ )
139
153
  raise PermissionError(
140
154
  message=error_message,
141
155
  error_code=error_code,
@@ -6,6 +6,7 @@ from urllib.parse import quote
6
6
  from uuid import UUID
7
7
 
8
8
  from quantumapi.client.base import BaseClient
9
+ from quantumapi.models.transit import KeyVersionsResponse, TransitKeyConfigResponse
9
10
  from quantumapi.models.keys import (
10
11
  GenerateDataKeyResponse,
11
12
  GenerateKeyRequest,
@@ -75,7 +76,21 @@ class KeysClient:
75
76
  set_as_default=set_as_default,
76
77
  labels=labels,
77
78
  )
78
- response = await self._client.post("/api/v1/keys", json_data=request.model_dump(exclude_none=True))
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)
79
94
  return KeyResponse(**response)
80
95
 
81
96
  async def import_key(
@@ -139,6 +154,7 @@ class KeysClient:
139
154
  status: Optional[str] = None,
140
155
  page: int = 1,
141
156
  page_size: int = 50,
157
+ all_versions: bool = False,
142
158
  ) -> KeyListResponse:
143
159
  """
144
160
  List cryptographic keys.
@@ -148,6 +164,7 @@ class KeysClient:
148
164
  status: Filter by status (active, inactive, scheduled_deletion)
149
165
  page: Page number
150
166
  page_size: Number of items per page
167
+ all_versions: Return one row per key version instead of one row per key
151
168
 
152
169
  Returns:
153
170
  List of keys with pagination info
@@ -162,10 +179,28 @@ class KeysClient:
162
179
  params["keyType"] = key_type.value
163
180
  if status:
164
181
  params["status"] = status
182
+ if all_versions:
183
+ params["allVersions"] = "true"
165
184
 
166
185
  response = await self._client.get("/api/v1/keys", params=params)
167
186
  return KeyListResponse(**response)
168
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
+
169
204
  async def get(self, key_id: UUID) -> KeyResponse:
170
205
  """
171
206
  Get key details by ID.
@@ -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,8 +3,10 @@
3
3
  from quantumapi.errors.exceptions import (
4
4
  AuthenticationError,
5
5
  ConflictError,
6
+ InsufficientScopeError,
6
7
  InvalidRequestError,
7
8
  KeyRevokedError,
9
+ KeyVersionBelowMinimumError,
8
10
  NetworkError,
9
11
  NotFoundError,
10
12
  PermissionError,
@@ -20,6 +22,8 @@ __all__ = [
20
22
  "AuthenticationError",
21
23
  "PermissionError",
22
24
  "KeyRevokedError",
25
+ "KeyVersionBelowMinimumError",
26
+ "InsufficientScopeError",
23
27
  "NotFoundError",
24
28
  "ConflictError",
25
29
  "ValidationError",
@@ -62,6 +62,27 @@ class KeyRevokedError(PermissionError):
62
62
  super().__init__(message, **kwargs)
63
63
 
64
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)
84
+
85
+
65
86
  class NotFoundError(QuantumAPIError):
66
87
  """Raised when a resource is not found (404)."""
67
88
 
@@ -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 (healthy, degraded, unhealthy)")
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(..., description="Current timestamp")
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):
@@ -42,22 +42,32 @@ class GenerateKeyRequest(BaseModel):
42
42
 
43
43
 
44
44
  class KeyResponse(BaseModel):
45
- """Response model containing key metadata."""
45
+ """Response model containing key metadata (accepts the API's camelCase and snake_case)."""
46
46
 
47
47
  id: UUID = Field(..., description="Unique identifier of the key")
48
48
  name: str = Field(..., description="Name of the key")
49
49
  description: Optional[str] = Field(default=None, description="Description of the key")
50
- key_type: KeyType = Field(..., description="Type of key")
50
+ key_type: KeyType = Field(..., alias="keyType", description="Type of key")
51
51
  algorithm: str = Field(..., description="Algorithm used")
52
- purpose: str = Field(..., description="Purpose (encryption, signing)")
53
- status: KeyStatus = Field(..., description="Current status of the key")
54
- is_default: bool = Field(..., description="Whether this is the default key for its type")
55
- public_key: Optional[str] = Field(default=None, description="Base64-encoded public key")
52
+ purpose: Optional[str] = Field(default=None, description="Purpose (encryption, signing)")
53
+ status: Optional[KeyStatus] = Field(default=None, description="Current status of the key")
54
+ is_default: bool = Field(default=False, alias="isDefault", description="Default key for its type")
55
+ public_key: Optional[str] = Field(default=None, alias="publicKey", description="Base64-encoded public key")
56
56
  version: int = Field(..., description="Version number of the key")
57
- created_at: datetime = Field(..., description="Creation timestamp")
58
- updated_at: datetime = Field(..., description="Last update timestamp")
59
- expires_at: Optional[datetime] = Field(default=None, description="Expiration date")
57
+ created_at: datetime = Field(..., alias="createdAt", description="Creation timestamp")
58
+ updated_at: Optional[datetime] = Field(default=None, alias="updatedAt", description="Last update timestamp")
59
+ expires_at: Optional[datetime] = Field(default=None, alias="expiresAt", description="Expiration date")
60
60
  labels: Optional[List[str]] = Field(default=None, description="Labels")
61
+ is_post_quantum: Optional[bool] = Field(default=None, alias="isPostQuantum")
62
+ is_active: Optional[bool] = Field(default=None, alias="isActive")
63
+ is_favorite: Optional[bool] = Field(default=None, alias="isFavorite")
64
+ last_rotated_at: Optional[datetime] = Field(default=None, alias="lastRotatedAt")
65
+ state: Optional[str] = Field(default=None)
66
+ scheduled_deletion_date: Optional[datetime] = Field(default=None, alias="scheduledDeletionDate")
67
+ min_decryption_version: Optional[int] = Field(default=None, alias="minDecryptionVersion")
68
+ version_count: Optional[int] = Field(default=None, alias="versionCount")
69
+
70
+ model_config = {"populate_by_name": True}
61
71
 
62
72
 
63
73
  class KeyListResponse(BaseModel):
@@ -66,8 +76,10 @@ class KeyListResponse(BaseModel):
66
76
  keys: List[KeyResponse] = Field(..., description="List of keys")
67
77
  total: int = Field(..., description="Total number of keys")
68
78
  page: int = Field(..., description="Current page number")
69
- page_size: int = Field(..., description="Number of items per page")
70
- has_more: bool = Field(..., description="Whether there are more pages")
79
+ page_size: int = Field(..., alias="pageSize", description="Number of items per page")
80
+ has_more: bool = Field(..., alias="hasMore", description="Whether there are more pages")
81
+
82
+ model_config = {"populate_by_name": True}
71
83
 
72
84
 
73
85
  class ImportKeyRequest(BaseModel):
@@ -0,0 +1,196 @@
1
+ """Pydantic models for the Transit API (``/api/v1/transit``).
2
+
3
+ Field names mirror the backend DTOs (camelCase on the wire, snake_case in Python). Every model
4
+ ignores unknown fields, so new server-side fields never break an older SDK.
5
+ """
6
+
7
+ import base64
8
+ from datetime import datetime
9
+ from typing import List, Optional
10
+ from uuid import UUID
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+ _CONFIG = ConfigDict(populate_by_name=True, extra="ignore")
15
+
16
+
17
+ class TransitEncryptResponse(BaseModel):
18
+ """``POST /transit/encrypt/{keyName}``."""
19
+
20
+ model_config = _CONFIG
21
+
22
+ ciphertext: str = Field(..., description="Ciphertext in vault:v{version}:{base64} format")
23
+ key_name: str = Field(..., alias="keyName")
24
+ key_version: int = Field(..., alias="keyVersion")
25
+
26
+
27
+ class TransitDecryptResponse(BaseModel):
28
+ """``POST /transit/decrypt/{keyName}``."""
29
+
30
+ model_config = _CONFIG
31
+
32
+ plaintext: str = Field(..., description="Decrypted plaintext (base64)")
33
+
34
+ @property
35
+ def plaintext_bytes(self) -> bytes:
36
+ """The decrypted plaintext as raw bytes."""
37
+ return base64.b64decode(self.plaintext)
38
+
39
+
40
+ class TransitRewrapResponse(BaseModel):
41
+ """``POST /transit/rewrap/{keyName}``."""
42
+
43
+ model_config = _CONFIG
44
+
45
+ ciphertext: str
46
+ key_version: int = Field(..., alias="keyVersion")
47
+
48
+
49
+ class TransitSignResponse(BaseModel):
50
+ """``POST /transit/sign/{keyName}``."""
51
+
52
+ model_config = _CONFIG
53
+
54
+ signature: str
55
+ algorithm: str
56
+ key_name: str = Field(..., alias="keyName")
57
+ key_version: int = Field(..., alias="keyVersion")
58
+
59
+
60
+ class TransitVerifyResponse(BaseModel):
61
+ """``POST /transit/verify/{keyName}``."""
62
+
63
+ model_config = _CONFIG
64
+
65
+ valid: bool
66
+
67
+
68
+ class TransitHmacResponse(BaseModel):
69
+ """``POST /transit/hmac/{keyName}``."""
70
+
71
+ model_config = _CONFIG
72
+
73
+ hmac: str
74
+ algorithm: str
75
+ key_version: int = Field(..., alias="keyVersion")
76
+
77
+
78
+ class TransitDataKeyResponse(BaseModel):
79
+ """``POST /transit/datakey/{keyName}[/without-plaintext]``."""
80
+
81
+ model_config = _CONFIG
82
+
83
+ plaintext_key: Optional[str] = Field(default=None, alias="plaintextKey")
84
+ encrypted_key: str = Field(..., alias="encryptedKey")
85
+ key_id: UUID = Field(..., alias="keyId")
86
+ key_version: int = Field(..., alias="keyVersion")
87
+ algorithm: str
88
+
89
+
90
+ class TransitBatchEncryptResultItem(BaseModel):
91
+ """One result of a batch encrypt (``error`` is set when the item failed)."""
92
+
93
+ model_config = _CONFIG
94
+
95
+ index: int
96
+ ciphertext: Optional[str] = None
97
+ error: Optional[str] = None
98
+
99
+
100
+ class TransitBatchEncryptResponse(BaseModel):
101
+ """``POST /transit/batch/encrypt/{keyName}``."""
102
+
103
+ model_config = _CONFIG
104
+
105
+ results: List[TransitBatchEncryptResultItem]
106
+ key_name: str = Field(..., alias="keyName")
107
+ key_version: int = Field(..., alias="keyVersion")
108
+
109
+
110
+ class TransitBatchDecryptResultItem(BaseModel):
111
+ """One result of a batch decrypt (``error`` is set when the item failed)."""
112
+
113
+ model_config = _CONFIG
114
+
115
+ index: int
116
+ plaintext: Optional[str] = None
117
+ error: Optional[str] = None
118
+
119
+
120
+ class TransitBatchDecryptResponse(BaseModel):
121
+ """``POST /transit/batch/decrypt/{keyName}``."""
122
+
123
+ model_config = _CONFIG
124
+
125
+ results: List[TransitBatchDecryptResultItem]
126
+
127
+
128
+ class TransitKey(BaseModel):
129
+ """Transit key metadata (``GET /keys/{id}`` / ``POST /keys``).
130
+
131
+ Tolerant of extra fields (for example ``minDecryptionVersion``, which the server is adding):
132
+ unknown fields are ignored, and optional ones default to None.
133
+ """
134
+
135
+ model_config = _CONFIG
136
+
137
+ id: UUID
138
+ name: str
139
+ description: Optional[str] = None
140
+ key_type: Optional[str] = Field(default=None, alias="keyType")
141
+ algorithm: str
142
+ is_post_quantum: Optional[bool] = Field(default=None, alias="isPostQuantum")
143
+ version: int
144
+ is_active: Optional[bool] = Field(default=None, alias="isActive")
145
+ is_default: Optional[bool] = Field(default=None, alias="isDefault")
146
+ created_at: Optional[datetime] = Field(default=None, alias="createdAt")
147
+ expires_at: Optional[datetime] = Field(default=None, alias="expiresAt")
148
+ last_rotated_at: Optional[datetime] = Field(default=None, alias="lastRotatedAt")
149
+ labels: Optional[List[str]] = None
150
+ state: Optional[str] = None
151
+ min_decryption_version: Optional[int] = Field(default=None, alias="minDecryptionVersion")
152
+
153
+
154
+ class TransitRotateKeyResponse(BaseModel):
155
+ """``POST /keys/{id}/rotate``."""
156
+
157
+ model_config = _CONFIG
158
+
159
+ key_id: UUID = Field(..., alias="keyId")
160
+ new_version: int = Field(..., alias="newVersion")
161
+ previous_version: int = Field(..., alias="previousVersion")
162
+ rotated_at: datetime = Field(..., alias="rotatedAt")
163
+
164
+
165
+ class TransitKeyConfigResponse(BaseModel):
166
+ """``POST /transit/keys/{name}/config`` and ``PUT /keys/{id}/min-decryption-version``."""
167
+
168
+ model_config = _CONFIG
169
+
170
+ key_name: str = Field(..., alias="keyName")
171
+ latest_version: int = Field(..., alias="latestVersion")
172
+ min_decryption_version: int = Field(..., alias="minDecryptionVersion")
173
+
174
+
175
+ class KeyVersionInfo(BaseModel):
176
+ """One version row of ``GET /keys/{id}/versions``."""
177
+
178
+ model_config = _CONFIG
179
+
180
+ id: UUID
181
+ version: int
182
+ created_at: Optional[datetime] = Field(default=None, alias="createdAt")
183
+ rotated_at: Optional[datetime] = Field(default=None, alias="rotatedAt")
184
+ revoked_at: Optional[datetime] = Field(default=None, alias="revokedAt")
185
+ is_active: Optional[bool] = Field(default=None, alias="isActive")
186
+ state: Optional[str] = None
187
+
188
+
189
+ class KeyVersionsResponse(BaseModel):
190
+ """``GET /keys/{id}/versions``."""
191
+
192
+ model_config = _CONFIG
193
+
194
+ key_name: str = Field(..., alias="keyName")
195
+ min_decryption_version: int = Field(..., alias="minDecryptionVersion")
196
+ versions: List[KeyVersionInfo] = Field(default_factory=list)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantumapi
3
- Version: 0.22.1
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:
@@ -22,6 +22,7 @@ quantumapi/client/resource_groups.py
22
22
  quantumapi/client/roles.py
23
23
  quantumapi/client/secrets.py
24
24
  quantumapi/client/sync_client.py
25
+ quantumapi/client/transit.py
25
26
  quantumapi/errors/__init__.py
26
27
  quantumapi/errors/exceptions.py
27
28
  quantumapi/models/__init__.py
@@ -35,10 +36,12 @@ quantumapi/models/qrng.py
35
36
  quantumapi/models/resource_groups.py
36
37
  quantumapi/models/roles.py
37
38
  quantumapi/models/secrets.py
39
+ quantumapi/models/transit.py
38
40
  tests/test_audit.py
39
41
  tests/test_data_keys.py
40
42
  tests/test_end_users.py
41
43
  tests/test_exceptions.py
42
44
  tests/test_models.py
43
45
  tests/test_parity.py
44
- tests/test_qrng.py
46
+ tests/test_qrng.py
47
+ tests/test_transit.py
@@ -0,0 +1,209 @@
1
+ """Tests for the Transit client: exact paths and bodies, models, errors, and the #850 fixes."""
2
+
3
+ from unittest.mock import AsyncMock
4
+ from uuid import uuid4
5
+
6
+ import httpx
7
+ import pytest
8
+
9
+ from quantumapi.client.base import BaseClient
10
+ from quantumapi.client.health import HealthClient
11
+ from quantumapi.client.keys import KeysClient
12
+ from quantumapi.client.transit import TransitClient
13
+ from quantumapi.errors import InsufficientScopeError, KeyRevokedError, PermissionError
14
+
15
+ KEY_ID = uuid4()
16
+
17
+
18
+ def _client(response=None):
19
+ base = AsyncMock()
20
+ base.post.return_value = response
21
+ base.get.return_value = response
22
+ return base, TransitClient(base)
23
+
24
+
25
+ @pytest.mark.asyncio
26
+ async def test_encrypt_bytes_are_base64_and_path_is_quoted():
27
+ base, t = _client({"ciphertext": "vault:v2:abc", "keyName": "my key", "keyVersion": 2})
28
+ out = await t.encrypt("my key", b"hello")
29
+ base.post.assert_awaited_once_with("/api/v1/transit/encrypt/my%20key", json_data={"plaintext": "aGVsbG8="})
30
+ assert (out.ciphertext, out.key_name, out.key_version) == ("vault:v2:abc", "my key", 2)
31
+
32
+
33
+ @pytest.mark.asyncio
34
+ async def test_encrypt_str_with_encoding_passthrough():
35
+ base, t = _client({"ciphertext": "c", "keyName": "k", "keyVersion": 1})
36
+ await t.encrypt("k", "hi", encoding="utf8")
37
+ base.post.assert_awaited_once_with(
38
+ "/api/v1/transit/encrypt/k", json_data={"plaintext": "hi", "encoding": "utf8"}
39
+ )
40
+
41
+
42
+ @pytest.mark.asyncio
43
+ async def test_decrypt_and_plaintext_bytes():
44
+ base, t = _client({"plaintext": "aGVsbG8="})
45
+ out = await t.decrypt("k", "vault:v1:x")
46
+ base.post.assert_awaited_once_with("/api/v1/transit/decrypt/k", json_data={"ciphertext": "vault:v1:x"})
47
+ assert out.plaintext_bytes == b"hello"
48
+
49
+
50
+ @pytest.mark.asyncio
51
+ async def test_rewrap():
52
+ base, t = _client({"ciphertext": "vault:v3:y", "keyVersion": 3, "extra": 1})
53
+ out = await t.rewrap("k", "vault:v1:x")
54
+ base.post.assert_awaited_once_with("/api/v1/transit/rewrap/k", json_data={"ciphertext": "vault:v1:x"})
55
+ assert out.key_version == 3
56
+
57
+
58
+ @pytest.mark.asyncio
59
+ async def test_datakey_routes_and_bodies():
60
+ resp = {"plaintextKey": "cA==", "encryptedKey": "ZW5j", "keyId": str(KEY_ID), "keyVersion": 1, "algorithm": "AES-256-GCM"}
61
+ base, t = _client(resp)
62
+ out = await t.generate_data_key("k", key_bytes=16, context="Y3R4")
63
+ base.post.assert_awaited_with("/api/v1/transit/datakey/k", json_data={"keyBytes": 16, "context": "Y3R4"})
64
+ assert out.plaintext_key == "cA==" and out.key_id == KEY_ID
65
+ await t.generate_data_key("k", include_plaintext=False)
66
+ base.post.assert_awaited_with("/api/v1/transit/datakey/k/without-plaintext", json_data={})
67
+
68
+
69
+ @pytest.mark.asyncio
70
+ async def test_hmac_sign_verify():
71
+ base, t = _client({"hmac": "aa", "algorithm": "sha256", "keyVersion": 1})
72
+ await t.hmac("k", b"data", algorithm="sha512")
73
+ base.post.assert_awaited_with("/api/v1/transit/hmac/k", json_data={"data": "ZGF0YQ==", "algorithm": "sha512"})
74
+ base.post.return_value = {"signature": "sig", "algorithm": "ML-DSA-65", "keyName": "k", "keyVersion": 1}
75
+ out = await t.sign("k", b"data")
76
+ base.post.assert_awaited_with("/api/v1/transit/sign/k", json_data={"data": "ZGF0YQ=="})
77
+ assert out.signature == "sig"
78
+ base.post.return_value = {"valid": True}
79
+ assert (await t.verify("k", "ZGF0YQ==", "sig")).valid is True
80
+ base.post.assert_awaited_with("/api/v1/transit/verify/k", json_data={"data": "ZGF0YQ==", "signature": "sig"})
81
+
82
+
83
+ @pytest.mark.asyncio
84
+ async def test_batch_encrypt_decrypt():
85
+ base, t = _client(
86
+ {"results": [{"index": 0, "ciphertext": "vault:v1:a"}, {"index": 1, "error": "bad"}], "keyName": "k", "keyVersion": 1}
87
+ )
88
+ out = await t.batch_encrypt("k", [b"a", "Yg=="])
89
+ base.post.assert_awaited_with(
90
+ "/api/v1/transit/batch/encrypt/k", json_data={"items": [{"plaintext": "YQ=="}, {"plaintext": "Yg=="}]}
91
+ )
92
+ assert out.results[1].error == "bad"
93
+ base.post.return_value = {"results": [{"index": 0, "plaintext": "YQ=="}]}
94
+ out = await t.batch_decrypt("k", ["vault:v1:a"])
95
+ base.post.assert_awaited_with(
96
+ "/api/v1/transit/batch/decrypt/k", json_data={"items": [{"ciphertext": "vault:v1:a"}]}
97
+ )
98
+ assert out.results[0].plaintext == "YQ=="
99
+
100
+
101
+ @pytest.mark.asyncio
102
+ async def test_key_create_get_rotate_tolerate_extra_fields():
103
+ key = {
104
+ "id": str(KEY_ID), "name": "orders", "keyType": "encryption", "algorithm": "ML-KEM-768",
105
+ "version": 1, "isActive": True, "minDecryptionVersion": 1, "someFutureField": {"a": 1},
106
+ }
107
+ base, t = _client(key)
108
+ created = await t.create_key("orders", labels=["a"])
109
+ base.post.assert_awaited_with(
110
+ "/api/v1/keys",
111
+ json_data={"name": "orders", "keyType": "encryption", "algorithm": "ML-KEM-768", "labels": ["a"]},
112
+ )
113
+ assert created.min_decryption_version == 1
114
+ assert (await t.get_key(KEY_ID)).name == "orders"
115
+ base.get.assert_awaited_with(f"/api/v1/keys/{KEY_ID}")
116
+ base.post.return_value = {
117
+ "keyId": str(KEY_ID), "newVersion": 2, "previousVersion": 1, "rotatedAt": "2026-10-21T10:00:00Z",
118
+ }
119
+ rot = await t.rotate_key(KEY_ID)
120
+ base.post.assert_awaited_with(f"/api/v1/keys/{KEY_ID}/rotate")
121
+ assert rot.new_version == 2
122
+
123
+
124
+ def _http_base(status, body):
125
+ base = BaseClient(api_key="k", base_url="https://api.test", max_retries=0)
126
+ base._client = httpx.AsyncClient(
127
+ transport=httpx.MockTransport(lambda req: httpx.Response(status, json=body)), headers=base._get_default_headers()
128
+ )
129
+ return base
130
+
131
+
132
+ @pytest.mark.asyncio
133
+ async def test_403_key_revoked_and_insufficient_scope_errors():
134
+ with pytest.raises(KeyRevokedError):
135
+ await TransitClient(_http_base(403, {"error": "key_revoked", "message": "revoked"})).decrypt("k", "c")
136
+ with pytest.raises(InsufficientScopeError) as exc:
137
+ await TransitClient(_http_base(403, {"error": "insufficient_scope", "message": "no scope"})).encrypt("k", b"x")
138
+ assert isinstance(exc.value, PermissionError) and exc.value.status_code == 403
139
+
140
+
141
+ @pytest.mark.asyncio
142
+ async def test_health_accepts_real_platform_response():
143
+ health = await HealthClient(_http_base(200, {"status": "Healthy", "version": "0.23.0", "gitSha": "abc1234", "service": "api"})).check()
144
+ assert (health.status, health.git_sha, health.service, health.timestamp) == ("Healthy", "abc1234", "api", None)
145
+
146
+
147
+ @pytest.mark.asyncio
148
+ async def test_keys_generate_sends_camelcase_keytype():
149
+ from quantumapi.models.keys import KeyType
150
+
151
+ base = AsyncMock()
152
+ base.post.return_value = {
153
+ "id": str(KEY_ID), "name": "k", "keyType": "signing", "algorithm": "ML-DSA-65", "version": 1,
154
+ "isActive": True, "isDefault": False, "createdAt": "2026-10-21T10:00:00Z", "isFavorite": False,
155
+ "isPostQuantum": True,
156
+ }
157
+ key = await KeysClient(base).generate("k", KeyType.SIGNING, "ML-DSA-65", set_as_default=False)
158
+ body = base.post.await_args.kwargs["json_data"]
159
+ assert body["keyType"] == "signing" and "key_type" not in body and body["setAsDefault"] is False
160
+ assert key.key_type == KeyType.SIGNING and key.is_post_quantum is True
161
+
162
+
163
+ @pytest.mark.asyncio
164
+ async def test_set_min_decryption_version_transit_and_keys():
165
+ resp = {"keyName": "my key", "latestVersion": 3, "minDecryptionVersion": 2, "extra": True}
166
+ base, t = _client(resp)
167
+ out = await t.set_min_decryption_version("my key", 2)
168
+ base.post.assert_awaited_once_with("/api/v1/transit/keys/my%20key/config", json_data={"minDecryptionVersion": 2})
169
+ assert (out.key_name, out.latest_version, out.min_decryption_version) == ("my key", 3, 2)
170
+
171
+ kbase = AsyncMock()
172
+ kbase.put.return_value = resp
173
+ out = await KeysClient(kbase).set_min_decryption_version(KEY_ID, 2)
174
+ kbase.put.assert_awaited_once_with(
175
+ f"/api/v1/keys/{KEY_ID}/min-decryption-version", json_data={"minDecryptionVersion": 2}
176
+ )
177
+ assert out.min_decryption_version == 2
178
+
179
+
180
+ @pytest.mark.asyncio
181
+ async def test_list_versions_and_all_versions_param():
182
+ kbase = AsyncMock()
183
+ kbase.get.return_value = {
184
+ "keyName": "k", "minDecryptionVersion": 1,
185
+ "versions": [{"id": str(KEY_ID), "version": 1, "createdAt": "2026-10-21T10:00:00Z", "rotatedAt": None,
186
+ "revokedAt": None, "isActive": True, "state": "active", "future": 1}],
187
+ }
188
+ out = await KeysClient(kbase).list_versions(KEY_ID)
189
+ kbase.get.assert_awaited_once_with(f"/api/v1/keys/{KEY_ID}/versions")
190
+ assert out.versions[0].version == 1 and out.versions[0].is_active and out.min_decryption_version == 1
191
+
192
+ kbase.get.reset_mock()
193
+ kbase.get.return_value = {"keys": [], "total": 0, "page": 1, "pageSize": 50, "hasMore": False}
194
+ await KeysClient(kbase).list(all_versions=True)
195
+ kbase.get.assert_awaited_once_with(
196
+ "/api/v1/keys", params={"page": 1, "pageSize": 50, "allVersions": "true"}
197
+ )
198
+ kbase.get.reset_mock()
199
+ await KeysClient(kbase).list()
200
+ kbase.get.assert_awaited_once_with("/api/v1/keys", params={"page": 1, "pageSize": 50})
201
+
202
+
203
+ @pytest.mark.asyncio
204
+ async def test_403_key_version_below_minimum_error():
205
+ from quantumapi.errors import KeyVersionBelowMinimumError
206
+
207
+ with pytest.raises(KeyVersionBelowMinimumError) as exc:
208
+ await TransitClient(_http_base(403, {"error": "key_version_below_minimum", "message": "old"})).decrypt("k", "c")
209
+ assert isinstance(exc.value, PermissionError) and exc.value.error_code == "key_version_below_minimum"
File without changes
File without changes