quantumapi 0.21.0__tar.gz → 0.22.1__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 (46) hide show
  1. {quantumapi-0.21.0/quantumapi.egg-info → quantumapi-0.22.1}/PKG-INFO +23 -2
  2. {quantumapi-0.21.0 → quantumapi-0.22.1}/README.md +22 -1
  3. {quantumapi-0.21.0 → quantumapi-0.22.1}/pyproject.toml +1 -1
  4. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/__init__.py +4 -0
  5. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/__init__.py +2 -0
  6. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/async_client.py +2 -0
  7. quantumapi-0.22.1/quantumapi/client/audit.py +66 -0
  8. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/base.py +15 -0
  9. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/keys.py +106 -0
  10. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/sync_client.py +1 -0
  11. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/errors/__init__.py +4 -0
  12. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/errors/exceptions.py +26 -4
  13. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/__init__.py +5 -0
  14. quantumapi-0.22.1/quantumapi/models/audit.py +47 -0
  15. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/keys.py +28 -0
  16. {quantumapi-0.21.0 → quantumapi-0.22.1/quantumapi.egg-info}/PKG-INFO +23 -2
  17. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi.egg-info/SOURCES.txt +4 -0
  18. quantumapi-0.22.1/tests/test_audit.py +99 -0
  19. quantumapi-0.22.1/tests/test_data_keys.py +121 -0
  20. {quantumapi-0.21.0 → quantumapi-0.22.1}/LICENSE +0 -0
  21. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/applications.py +0 -0
  22. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/encryption.py +0 -0
  23. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/end_users.py +0 -0
  24. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/health.py +0 -0
  25. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/qrng.py +0 -0
  26. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/resource_groups.py +0 -0
  27. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/roles.py +0 -0
  28. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/client/secrets.py +0 -0
  29. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/applications.py +0 -0
  30. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/encryption.py +0 -0
  31. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/end_users.py +0 -0
  32. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/health.py +0 -0
  33. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/qrng.py +0 -0
  34. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/resource_groups.py +0 -0
  35. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/roles.py +0 -0
  36. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/models/secrets.py +0 -0
  37. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi/py.typed +0 -0
  38. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi.egg-info/dependency_links.txt +0 -0
  39. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi.egg-info/requires.txt +0 -0
  40. {quantumapi-0.21.0 → quantumapi-0.22.1}/quantumapi.egg-info/top_level.txt +0 -0
  41. {quantumapi-0.21.0 → quantumapi-0.22.1}/setup.cfg +0 -0
  42. {quantumapi-0.21.0 → quantumapi-0.22.1}/tests/test_end_users.py +0 -0
  43. {quantumapi-0.21.0 → quantumapi-0.22.1}/tests/test_exceptions.py +0 -0
  44. {quantumapi-0.21.0 → quantumapi-0.22.1}/tests/test_models.py +0 -0
  45. {quantumapi-0.21.0 → quantumapi-0.22.1}/tests/test_parity.py +0 -0
  46. {quantumapi-0.21.0 → quantumapi-0.22.1}/tests/test_qrng.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantumapi
3
- Version: 0.21.0
3
+ Version: 0.22.1
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
@@ -171,6 +171,27 @@ is_valid = await client.encryption.verify(
171
171
  )
172
172
  ```
173
173
 
174
+ ### Audit Client
175
+
176
+ Requires an API key with the `audit:read` scope (403 otherwise) or a JWT owner/admin.
177
+
178
+ ```python
179
+ logs = await client.audit.list(
180
+ category="keys",
181
+ action=["Encrypt", "Decrypt"], # or "Encrypt,Decrypt"
182
+ key_id="key-id",
183
+ from_="2026-10-01T00:00:00Z",
184
+ page=1,
185
+ page_size=100, # max 200
186
+ )
187
+ for e in logs.items:
188
+ print(e.timestamp, e.action, e.actor, e.outcome)
189
+ print(logs.total_count)
190
+ ```
191
+
192
+ Creating or importing a key with a name already in use raises `ConflictError`
193
+ (`error_code == "key_name_conflict"`).
194
+
174
195
  ### Keys Client
175
196
 
176
197
  ```python
@@ -572,7 +593,7 @@ See [CHANGELOG.md](CHANGELOG.md) for a history of changes to this SDK.
572
593
 
573
594
  ## Security
574
595
 
575
- For security concerns, please email it@kovimatic.ie. Do not create public issues for security vulnerabilities.
596
+ For security concerns, please email victorxata@icloud.com. Do not create public issues for security vulnerabilities.
576
597
 
577
598
  ## Links
578
599
 
@@ -130,6 +130,27 @@ is_valid = await client.encryption.verify(
130
130
  )
131
131
  ```
132
132
 
133
+ ### Audit Client
134
+
135
+ Requires an API key with the `audit:read` scope (403 otherwise) or a JWT owner/admin.
136
+
137
+ ```python
138
+ logs = await client.audit.list(
139
+ category="keys",
140
+ action=["Encrypt", "Decrypt"], # or "Encrypt,Decrypt"
141
+ key_id="key-id",
142
+ from_="2026-10-01T00:00:00Z",
143
+ page=1,
144
+ page_size=100, # max 200
145
+ )
146
+ for e in logs.items:
147
+ print(e.timestamp, e.action, e.actor, e.outcome)
148
+ print(logs.total_count)
149
+ ```
150
+
151
+ Creating or importing a key with a name already in use raises `ConflictError`
152
+ (`error_code == "key_name_conflict"`).
153
+
133
154
  ### Keys Client
134
155
 
135
156
  ```python
@@ -531,7 +552,7 @@ See [CHANGELOG.md](CHANGELOG.md) for a history of changes to this SDK.
531
552
 
532
553
  ## Security
533
554
 
534
- For security concerns, please email it@kovimatic.ie. Do not create public issues for security vulnerabilities.
555
+ For security concerns, please email victorxata@icloud.com. Do not create public issues for security vulnerabilities.
535
556
 
536
557
  ## Links
537
558
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quantumapi"
7
- version = "0.21.0"
7
+ version = "0.22.1"
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"
@@ -17,6 +17,8 @@ from quantumapi.client.async_client import QuantumAPIClient
17
17
  from quantumapi.client.sync_client import QuantumAPISyncClient
18
18
  from quantumapi.errors.exceptions import (
19
19
  AuthenticationError,
20
+ ConflictError,
21
+ KeyRevokedError,
20
22
  NetworkError,
21
23
  NotFoundError,
22
24
  PermissionError,
@@ -36,7 +38,9 @@ __all__ = [
36
38
  "QuantumAPIError",
37
39
  "AuthenticationError",
38
40
  "PermissionError",
41
+ "KeyRevokedError",
39
42
  "NotFoundError",
43
+ "ConflictError",
40
44
  "RateLimitError",
41
45
  "ValidationError",
42
46
  "ServerError",
@@ -5,6 +5,7 @@ from quantumapi.client.async_client import QuantumAPIClient
5
5
  from quantumapi.client.encryption import EncryptionClient
6
6
  from quantumapi.client.end_users import EndUsersClient
7
7
  from quantumapi.client.health import HealthClient
8
+ from quantumapi.client.audit import AuditClient
8
9
  from quantumapi.client.keys import KeysClient
9
10
  from quantumapi.client.qrng import QrngClient
10
11
  from quantumapi.client.secrets import SecretsClient
@@ -17,6 +18,7 @@ __all__ = [
17
18
  "EndUsersClient",
18
19
  "EncryptionClient",
19
20
  "KeysClient",
21
+ "AuditClient",
20
22
  "QrngClient",
21
23
  "SecretsClient",
22
24
  "HealthClient",
@@ -8,6 +8,7 @@ from quantumapi.client.base import BaseClient
8
8
  from quantumapi.client.encryption import EncryptionClient
9
9
  from quantumapi.client.end_users import EndUsersClient
10
10
  from quantumapi.client.health import HealthClient
11
+ from quantumapi.client.audit import AuditClient
11
12
  from quantumapi.client.keys import KeysClient
12
13
  from quantumapi.client.qrng import QrngClient
13
14
  from quantumapi.client.resource_groups import ResourceGroupsClient
@@ -82,6 +83,7 @@ class QuantumAPIClient:
82
83
  # Initialize service clients
83
84
  self.encryption = EncryptionClient(self._base_client)
84
85
  self.keys = KeysClient(self._base_client)
86
+ self.audit = AuditClient(self._base_client)
85
87
  self.secrets = SecretsClient(self._base_client)
86
88
  self.resource_groups = ResourceGroupsClient(self._base_client)
87
89
  self.applications = ApplicationsClient(self._base_client)
@@ -0,0 +1,66 @@
1
+ """Audit logs client for QuantumAPI SDK."""
2
+
3
+ from datetime import datetime
4
+ from typing import Optional, Sequence, Union
5
+ from uuid import UUID
6
+
7
+ from quantumapi.client.base import BaseClient
8
+ from quantumapi.models.audit import AuditLogListResponse
9
+
10
+
11
+ def _iso(value: Union[str, datetime]) -> str:
12
+ return value.isoformat() if isinstance(value, datetime) else value
13
+
14
+
15
+ class AuditClient:
16
+ """Client for the tenant audit log (requires the ``audit:read`` API-key scope)."""
17
+
18
+ def __init__(self, base_client: BaseClient) -> None:
19
+ self._client = base_client
20
+
21
+ async def list(
22
+ self,
23
+ category: Optional[str] = None,
24
+ action: Optional[Union[str, Sequence[str]]] = None,
25
+ key_id: Optional[Union[str, UUID]] = None,
26
+ actor: Optional[str] = None,
27
+ from_: Optional[Union[str, datetime]] = None,
28
+ to: Optional[Union[str, datetime]] = None,
29
+ page: int = 1,
30
+ page_size: int = 50,
31
+ ) -> AuditLogListResponse:
32
+ """
33
+ List the tenant's audit log, newest first.
34
+
35
+ Args:
36
+ category: Filter by category (e.g. ``"keys"``)
37
+ action: One action or a list (Encrypt, Decrypt, Sign, Verify, Rewrap,
38
+ Hmac, GenerateDataKey, KeyCreated, ...)
39
+ key_id: Only events for this key
40
+ actor: Case-insensitive substring match on the actor
41
+ from_: Only events at or after this time (ISO-8601 string or datetime)
42
+ to: Only events at or before this time (ISO-8601 string or datetime)
43
+ page: Page number (1-based)
44
+ page_size: Items per page (max 200)
45
+
46
+ Raises:
47
+ PermissionError: The API key lacks the ``audit:read`` scope (403)
48
+
49
+ Example:
50
+ >>> logs = await client.audit.list(category="keys", action=["Encrypt", "Decrypt"])
51
+ """
52
+ params: dict = {"page": page, "pageSize": page_size}
53
+ if category:
54
+ params["category"] = category
55
+ if action:
56
+ params["action"] = action if isinstance(action, str) else ",".join(action)
57
+ if key_id:
58
+ params["keyId"] = str(key_id)
59
+ if actor:
60
+ params["actor"] = actor
61
+ if from_:
62
+ params["from"] = _iso(from_)
63
+ if to:
64
+ params["to"] = _iso(to)
65
+ response = await self._client.get("/api/v1/audit-logs", params=params)
66
+ return AuditLogListResponse(**response)
@@ -9,6 +9,8 @@ from httpx import Response
9
9
 
10
10
  from quantumapi.errors import (
11
11
  AuthenticationError,
12
+ ConflictError,
13
+ KeyRevokedError,
12
14
  NetworkError,
13
15
  NotFoundError,
14
16
  PermissionError,
@@ -128,6 +130,12 @@ class BaseClient:
128
130
  status_code=401,
129
131
  )
130
132
  elif response.status_code == 403:
133
+ if error_code == "key_revoked":
134
+ raise KeyRevokedError(
135
+ message=error_message,
136
+ error_code=error_code,
137
+ details=error_details,
138
+ )
131
139
  raise PermissionError(
132
140
  message=error_message,
133
141
  error_code=error_code,
@@ -141,6 +149,13 @@ class BaseClient:
141
149
  details=error_details,
142
150
  status_code=404,
143
151
  )
152
+ elif response.status_code == 409:
153
+ raise ConflictError(
154
+ message=error_message,
155
+ error_code=error_code,
156
+ details=error_details,
157
+ status_code=409,
158
+ )
144
159
  elif response.status_code == 400 or response.status_code == 422:
145
160
  raise ValidationError(
146
161
  message=error_message,
@@ -2,10 +2,12 @@
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
8
9
  from quantumapi.models.keys import (
10
+ GenerateDataKeyResponse,
9
11
  GenerateKeyRequest,
10
12
  ImportKeyRequest,
11
13
  KeyHealthReport,
@@ -14,6 +16,7 @@ from quantumapi.models.keys import (
14
16
  KeyType,
15
17
  PublicKeyResponse,
16
18
  RotateKeyRequest,
19
+ UnwrapKeyResponse,
17
20
  UpdateKeyRequest,
18
21
  )
19
22
 
@@ -329,6 +332,109 @@ class KeysClient:
329
332
  )
330
333
  return PublicKeyResponse(**response)
331
334
 
335
+ @staticmethod
336
+ def _data_key_body(
337
+ key_bytes: Optional[int], algorithm: Optional[str], context: Optional[str]
338
+ ) -> dict:
339
+ body: dict = {}
340
+ if algorithm is not None:
341
+ body["algorithm"] = algorithm
342
+ if key_bytes is not None:
343
+ body["keyBytes"] = key_bytes
344
+ if context is not None:
345
+ body["context"] = context
346
+ return body
347
+
348
+ async def generate_data_key(
349
+ self,
350
+ key_id: UUID,
351
+ key_bytes: Optional[int] = None,
352
+ algorithm: Optional[str] = None,
353
+ context: Optional[str] = None,
354
+ ) -> GenerateDataKeyResponse:
355
+ """
356
+ Generate a data key for envelope encryption
357
+ (``POST /api/v1/keys/{key_id}/generate-data-key``).
358
+
359
+ Args:
360
+ key_id: Master key that wraps the data key
361
+ key_bytes: Data key length: 16, 24 or 32 (server default 32)
362
+ algorithm: Data key algorithm label (server default AES-256-GCM)
363
+ context: Optional base64 encryption context (AAD); pass it again on unwrap
364
+
365
+ Returns:
366
+ Plaintext and encrypted data key
367
+ """
368
+ response = await self._client.post(
369
+ f"/api/v1/keys/{key_id}/generate-data-key",
370
+ json_data=self._data_key_body(key_bytes, algorithm, context),
371
+ )
372
+ return GenerateDataKeyResponse(**response)
373
+
374
+ async def generate_data_key_without_plaintext(
375
+ self,
376
+ key_id: UUID,
377
+ key_bytes: Optional[int] = None,
378
+ algorithm: Optional[str] = None,
379
+ context: Optional[str] = None,
380
+ ) -> GenerateDataKeyResponse:
381
+ """Like :meth:`generate_data_key` but ``plaintext_key`` is None
382
+ (``POST /api/v1/keys/{key_id}/generate-data-key-without-plaintext``)."""
383
+ response = await self._client.post(
384
+ f"/api/v1/keys/{key_id}/generate-data-key-without-plaintext",
385
+ json_data=self._data_key_body(key_bytes, algorithm, context),
386
+ )
387
+ return GenerateDataKeyResponse(**response)
388
+
389
+ async def generate_transit_data_key(
390
+ self,
391
+ key_name: str,
392
+ key_bytes: Optional[int] = None,
393
+ algorithm: Optional[str] = None,
394
+ context: Optional[str] = None,
395
+ ) -> GenerateDataKeyResponse:
396
+ """Generate a data key with a named Transit key
397
+ (``POST /api/v1/transit/datakey/{key_name}``)."""
398
+ response = await self._client.post(
399
+ f"/api/v1/transit/datakey/{quote(key_name, safe='')}",
400
+ json_data=self._data_key_body(key_bytes, algorithm, context),
401
+ )
402
+ return GenerateDataKeyResponse(**response)
403
+
404
+ async def generate_transit_data_key_without_plaintext(
405
+ self,
406
+ key_name: str,
407
+ key_bytes: Optional[int] = None,
408
+ algorithm: Optional[str] = None,
409
+ context: Optional[str] = None,
410
+ ) -> GenerateDataKeyResponse:
411
+ """Transit data key without plaintext
412
+ (``POST /api/v1/transit/datakey/{key_name}/without-plaintext``)."""
413
+ response = await self._client.post(
414
+ f"/api/v1/transit/datakey/{quote(key_name, safe='')}/without-plaintext",
415
+ json_data=self._data_key_body(key_bytes, algorithm, context),
416
+ )
417
+ return GenerateDataKeyResponse(**response)
418
+
419
+ async def unwrap(
420
+ self,
421
+ key_id: UUID,
422
+ wrapped_key: str,
423
+ context: Optional[str] = None,
424
+ ) -> UnwrapKeyResponse:
425
+ """
426
+ Unwrap a wrapped key, or the ``encrypted_key`` of a data key, with the master key
427
+ (``POST /api/v1/keys/{key_id}/unwrap``).
428
+
429
+ Raises:
430
+ KeyRevokedError: HTTP 403 ``key_revoked`` when the master key was revoked
431
+ """
432
+ body = {"wrappedKey": wrapped_key}
433
+ if context is not None:
434
+ body["context"] = context
435
+ response = await self._client.post(f"/api/v1/keys/{key_id}/unwrap", json_data=body)
436
+ return UnwrapKeyResponse(**response)
437
+
332
438
  async def check(self, key_id: UUID) -> KeyHealthReport:
333
439
  """
334
440
  Check the health of a key.
@@ -100,6 +100,7 @@ class QuantumAPISyncClient:
100
100
 
101
101
  self.encryption = _SyncProxy(self._async_client.encryption)
102
102
  self.keys = _SyncProxy(self._async_client.keys)
103
+ self.audit = _SyncProxy(self._async_client.audit)
103
104
  self.secrets = _SyncProxy(self._async_client.secrets)
104
105
  self.resource_groups = _SyncProxy(self._async_client.resource_groups)
105
106
  self.applications = _SyncProxy(self._async_client.applications)
@@ -2,7 +2,9 @@
2
2
 
3
3
  from quantumapi.errors.exceptions import (
4
4
  AuthenticationError,
5
+ ConflictError,
5
6
  InvalidRequestError,
7
+ KeyRevokedError,
6
8
  NetworkError,
7
9
  NotFoundError,
8
10
  PermissionError,
@@ -17,7 +19,9 @@ __all__ = [
17
19
  "QuantumAPIError",
18
20
  "AuthenticationError",
19
21
  "PermissionError",
22
+ "KeyRevokedError",
20
23
  "NotFoundError",
24
+ "ConflictError",
21
25
  "ValidationError",
22
26
  "RateLimitError",
23
27
  "ServerError",
@@ -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
- super().__init__(message, status_code=401, **kwargs)
43
+ kwargs.setdefault("status_code", 401)
44
+ super().__init__(message, **kwargs)
44
45
 
45
46
 
46
47
  class PermissionError(QuantumAPIError):
@@ -48,7 +49,17 @@ class PermissionError(QuantumAPIError):
48
49
 
49
50
  def __init__(self, message: str = "Permission denied", **kwargs: Any) -> None:
50
51
  """Initialize PermissionError."""
51
- super().__init__(message, status_code=403, **kwargs)
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)
52
63
 
53
64
 
54
65
  class NotFoundError(QuantumAPIError):
@@ -56,7 +67,17 @@ class NotFoundError(QuantumAPIError):
56
67
 
57
68
  def __init__(self, message: str = "Resource not found", **kwargs: Any) -> None:
58
69
  """Initialize NotFoundError."""
59
- super().__init__(message, status_code=404, **kwargs)
70
+ kwargs.setdefault("status_code", 404)
71
+ super().__init__(message, **kwargs)
72
+
73
+
74
+ class ConflictError(QuantumAPIError):
75
+ """Raised on HTTP 409, e.g. ``key_name_conflict`` when a key name is already in use."""
76
+
77
+ def __init__(self, message: str = "Conflict", **kwargs: Any) -> None:
78
+ """Initialize ConflictError."""
79
+ kwargs.setdefault("status_code", 409)
80
+ super().__init__(message, **kwargs)
60
81
 
61
82
 
62
83
  class ValidationError(QuantumAPIError):
@@ -64,7 +85,8 @@ class ValidationError(QuantumAPIError):
64
85
 
65
86
  def __init__(self, message: str = "Validation failed", **kwargs: Any) -> None:
66
87
  """Initialize ValidationError."""
67
- super().__init__(message, status_code=400, **kwargs)
88
+ kwargs.setdefault("status_code", 400)
89
+ super().__init__(message, **kwargs)
68
90
 
69
91
 
70
92
  class RateLimitError(QuantumAPIError):
@@ -9,6 +9,7 @@ from quantumapi.models.applications import (
9
9
  RotateSecretResponse,
10
10
  UpdateApplicationRequest,
11
11
  )
12
+ from quantumapi.models.audit import AUDIT_READ_SCOPE, AuditLogEntry, AuditLogListResponse
12
13
  from quantumapi.models.end_users import (
13
14
  CreateEndUserRequest,
14
15
  EndUser,
@@ -75,6 +76,10 @@ from quantumapi.models.secrets import (
75
76
  )
76
77
 
77
78
  __all__ = [
79
+ # Audit
80
+ "AUDIT_READ_SCOPE",
81
+ "AuditLogEntry",
82
+ "AuditLogListResponse",
78
83
  # Applications
79
84
  "Application",
80
85
  "ApplicationType",
@@ -0,0 +1,47 @@
1
+ """Pydantic models for the tenant audit log (GET /api/v1/audit-logs)."""
2
+
3
+ from datetime import datetime
4
+ from typing import List, Optional
5
+ from uuid import UUID
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+ #: API-key scope required to read the audit log with an API key.
10
+ AUDIT_READ_SCOPE = "audit:read"
11
+
12
+
13
+ class AuditLogEntry(BaseModel):
14
+ """One entry of the tenant audit log."""
15
+
16
+ id: UUID = Field(..., description="Entry ID")
17
+ timestamp: datetime = Field(..., description="When the event happened")
18
+ action: str = Field(..., description="Audit action, e.g. Encrypt, Decrypt, Sign, Verify, KeyCreated")
19
+ category: str = Field(..., description="'keys' for key events, 'other' otherwise")
20
+ actor: str = Field(..., description="User e-mail, 'apikey:{name}' or another principal marker")
21
+ actor_type: str = Field(..., alias="actorType", description="'user', 'apiKey' or 'other'")
22
+ resource_type: str = Field(..., alias="resourceType", description="Resource type, e.g. CryptoKey")
23
+ resource_id: UUID = Field(..., alias="resourceId", description="Resource ID")
24
+ resource_name: Optional[str] = Field(default=None, alias="resourceName", description="Resource name")
25
+ outcome: str = Field(..., description="'success', 'failure' or 'denied'")
26
+ valid: Optional[bool] = Field(default=None, description="Verify only: whether the signature was valid")
27
+ error: Optional[str] = Field(default=None, description="Error code for failures")
28
+ algorithm: Optional[str] = Field(default=None, description="Algorithm used")
29
+ key_version: Optional[int] = Field(default=None, alias="keyVersion", description="Key version used")
30
+ channel: Optional[str] = Field(default=None, description="'eaas' or 'transit' for key usage events")
31
+ ip_address: Optional[str] = Field(default=None, alias="ipAddress", description="Caller IP address")
32
+ user_agent: Optional[str] = Field(default=None, alias="userAgent", description="Caller user agent")
33
+ batch_size: Optional[int] = Field(default=None, alias="batchSize", description="Batch size, if a batch call")
34
+ failed_items: Optional[int] = Field(default=None, alias="failedItems", description="Failed items in a batch")
35
+
36
+ model_config = {"populate_by_name": True}
37
+
38
+
39
+ class AuditLogListResponse(BaseModel):
40
+ """Paginated tenant audit log."""
41
+
42
+ items: List[AuditLogEntry] = Field(default_factory=list, description="Entries, newest first")
43
+ total_count: int = Field(..., alias="totalCount", description="Total entries matching the filters")
44
+ page: int = Field(..., description="Current page (1-based)")
45
+ page_size: int = Field(..., alias="pageSize", description="Page size used by the server")
46
+
47
+ model_config = {"populate_by_name": True}
@@ -155,3 +155,31 @@ class KeyHealthReport(BaseModel):
155
155
  healthy: bool = Field(..., description="Whether the key is healthy")
156
156
  issues: List[str] = Field(default_factory=list, description="Critical issues found")
157
157
  warnings: List[str] = Field(default_factory=list, description="Warnings found")
158
+
159
+
160
+ class GenerateDataKeyResponse(BaseModel):
161
+ """Response of the generate-data-key routes (envelope encryption)."""
162
+
163
+ plaintext_key: Optional[str] = Field(
164
+ default=None,
165
+ alias="plaintextKey",
166
+ description="Plaintext data key (base64); None for the without-plaintext variants",
167
+ )
168
+ encrypted_key: str = Field(
169
+ ..., alias="encryptedKey", description="Data key encrypted by the master key (base64)"
170
+ )
171
+ key_id: UUID = Field(..., alias="keyId", description="Master key that wrapped the data key")
172
+ key_version: int = Field(..., alias="keyVersion", description="Master key version used")
173
+ algorithm: str = Field(..., description="Data key algorithm, e.g. AES-256-GCM")
174
+
175
+ model_config = {"populate_by_name": True}
176
+
177
+
178
+ class UnwrapKeyResponse(BaseModel):
179
+ """Response of ``POST /api/v1/keys/{keyId}/unwrap``."""
180
+
181
+ key_material: str = Field(..., alias="keyMaterial", description="Unwrapped key material (base64)")
182
+ key_id: UUID = Field(..., alias="keyId", description="Wrapping key used")
183
+ key_version: int = Field(..., alias="keyVersion", description="Wrapping key version used")
184
+
185
+ model_config = {"populate_by_name": True}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantumapi
3
- Version: 0.21.0
3
+ Version: 0.22.1
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
@@ -171,6 +171,27 @@ is_valid = await client.encryption.verify(
171
171
  )
172
172
  ```
173
173
 
174
+ ### Audit Client
175
+
176
+ Requires an API key with the `audit:read` scope (403 otherwise) or a JWT owner/admin.
177
+
178
+ ```python
179
+ logs = await client.audit.list(
180
+ category="keys",
181
+ action=["Encrypt", "Decrypt"], # or "Encrypt,Decrypt"
182
+ key_id="key-id",
183
+ from_="2026-10-01T00:00:00Z",
184
+ page=1,
185
+ page_size=100, # max 200
186
+ )
187
+ for e in logs.items:
188
+ print(e.timestamp, e.action, e.actor, e.outcome)
189
+ print(logs.total_count)
190
+ ```
191
+
192
+ Creating or importing a key with a name already in use raises `ConflictError`
193
+ (`error_code == "key_name_conflict"`).
194
+
174
195
  ### Keys Client
175
196
 
176
197
  ```python
@@ -572,7 +593,7 @@ See [CHANGELOG.md](CHANGELOG.md) for a history of changes to this SDK.
572
593
 
573
594
  ## Security
574
595
 
575
- For security concerns, please email it@kovimatic.ie. Do not create public issues for security vulnerabilities.
596
+ For security concerns, please email victorxata@icloud.com. Do not create public issues for security vulnerabilities.
576
597
 
577
598
  ## Links
578
599
 
@@ -11,6 +11,7 @@ quantumapi.egg-info/top_level.txt
11
11
  quantumapi/client/__init__.py
12
12
  quantumapi/client/applications.py
13
13
  quantumapi/client/async_client.py
14
+ quantumapi/client/audit.py
14
15
  quantumapi/client/base.py
15
16
  quantumapi/client/encryption.py
16
17
  quantumapi/client/end_users.py
@@ -25,6 +26,7 @@ quantumapi/errors/__init__.py
25
26
  quantumapi/errors/exceptions.py
26
27
  quantumapi/models/__init__.py
27
28
  quantumapi/models/applications.py
29
+ quantumapi/models/audit.py
28
30
  quantumapi/models/encryption.py
29
31
  quantumapi/models/end_users.py
30
32
  quantumapi/models/health.py
@@ -33,6 +35,8 @@ quantumapi/models/qrng.py
33
35
  quantumapi/models/resource_groups.py
34
36
  quantumapi/models/roles.py
35
37
  quantumapi/models/secrets.py
38
+ tests/test_audit.py
39
+ tests/test_data_keys.py
36
40
  tests/test_end_users.py
37
41
  tests/test_exceptions.py
38
42
  tests/test_models.py
@@ -0,0 +1,99 @@
1
+ """Tests for AuditClient and 409 key_name_conflict mapping."""
2
+
3
+ from datetime import datetime, timezone
4
+ from unittest.mock import AsyncMock, MagicMock
5
+ from uuid import uuid4
6
+
7
+ import pytest
8
+
9
+ from quantumapi.client.audit import AuditClient
10
+ from quantumapi.client.base import BaseClient
11
+ from quantumapi.errors import ConflictError
12
+ from quantumapi.models.audit import AUDIT_READ_SCOPE, AuditLogListResponse
13
+
14
+ ENTRY = {
15
+ "id": str(uuid4()),
16
+ "timestamp": "2026-10-20T10:00:00+00:00",
17
+ "action": "Encrypt",
18
+ "category": "keys",
19
+ "actor": "apikey:ci",
20
+ "actorType": "apiKey",
21
+ "resourceType": "CryptoKey",
22
+ "resourceId": str(uuid4()),
23
+ "resourceName": "k1",
24
+ "outcome": "success",
25
+ "channel": "transit",
26
+ "keyVersion": 2,
27
+ "batchSize": 3,
28
+ }
29
+ PAYLOAD = {"items": [ENTRY], "totalCount": 1, "page": 1, "pageSize": 50}
30
+
31
+
32
+ def test_scope_constant():
33
+ assert AUDIT_READ_SCOPE == "audit:read"
34
+
35
+
36
+ def test_parses_response():
37
+ resp = AuditLogListResponse(**PAYLOAD)
38
+ assert resp.total_count == 1 and resp.page_size == 50
39
+ e = resp.items[0]
40
+ assert e.actor_type == "apiKey" and e.key_version == 2 and e.batch_size == 3
41
+ assert e.valid is None and e.error is None
42
+
43
+
44
+ @pytest.mark.asyncio
45
+ async def test_list_default_params():
46
+ base = AsyncMock()
47
+ base.get.return_value = PAYLOAD
48
+ resp = await AuditClient(base).list()
49
+ base.get.assert_awaited_once_with("/api/v1/audit-logs", params={"page": 1, "pageSize": 50})
50
+ assert len(resp.items) == 1
51
+
52
+
53
+ @pytest.mark.asyncio
54
+ async def test_list_all_filters():
55
+ base = AsyncMock()
56
+ base.get.return_value = PAYLOAD
57
+ key_id = uuid4()
58
+ start = datetime(2026, 10, 1, tzinfo=timezone.utc)
59
+ await AuditClient(base).list(
60
+ category="keys",
61
+ action=["Encrypt", "Rewrap"],
62
+ key_id=key_id,
63
+ actor="ci",
64
+ from_=start,
65
+ to="2026-10-20T00:00:00Z",
66
+ page=2,
67
+ page_size=200,
68
+ )
69
+ params = base.get.call_args.kwargs["params"]
70
+ assert params == {
71
+ "page": 2,
72
+ "pageSize": 200,
73
+ "category": "keys",
74
+ "action": "Encrypt,Rewrap",
75
+ "keyId": str(key_id),
76
+ "actor": "ci",
77
+ "from": start.isoformat(),
78
+ "to": "2026-10-20T00:00:00Z",
79
+ }
80
+
81
+
82
+ @pytest.mark.asyncio
83
+ async def test_list_action_string_passthrough():
84
+ base = AsyncMock()
85
+ base.get.return_value = PAYLOAD
86
+ await AuditClient(base).list(action="Sign,Verify")
87
+ assert base.get.call_args.kwargs["params"]["action"] == "Sign,Verify"
88
+
89
+
90
+ @pytest.mark.asyncio
91
+ async def test_409_maps_to_conflict_error():
92
+ client = BaseClient(api_key="qapi_x", base_url="https://example.test")
93
+ resp = MagicMock()
94
+ resp.status_code = 409
95
+ resp.json.return_value = {"error": "key_name_conflict", "message": "Key name in use"}
96
+ with pytest.raises(ConflictError) as exc:
97
+ await client._handle_response(resp)
98
+ assert exc.value.error_code == "key_name_conflict"
99
+ assert exc.value.status_code == 409
@@ -0,0 +1,121 @@
1
+ """Tests for data key / unwrap routes and the 403 key_revoked mapping."""
2
+
3
+ from unittest.mock import AsyncMock, MagicMock
4
+ from uuid import uuid4
5
+
6
+ import pytest
7
+
8
+ from quantumapi.client.base import BaseClient
9
+ from quantumapi.client.keys import KeysClient
10
+ from quantumapi.errors import KeyRevokedError, PermissionError
11
+
12
+ KEY_ID = uuid4()
13
+ DATA_KEY = {
14
+ "plaintextKey": "cA==",
15
+ "encryptedKey": "ZW5j",
16
+ "keyId": str(KEY_ID),
17
+ "keyVersion": 3,
18
+ "algorithm": "AES-256-GCM",
19
+ }
20
+
21
+
22
+ @pytest.mark.asyncio
23
+ async def test_generate_data_key_route_and_body():
24
+ base = AsyncMock()
25
+ base.post.return_value = DATA_KEY
26
+ resp = await KeysClient(base).generate_data_key(KEY_ID, key_bytes=16, context="Y3R4")
27
+ base.post.assert_awaited_once_with(
28
+ f"/api/v1/keys/{KEY_ID}/generate-data-key",
29
+ json_data={"keyBytes": 16, "context": "Y3R4"},
30
+ )
31
+ assert resp.plaintext_key == "cA==" and resp.encrypted_key == "ZW5j"
32
+ assert resp.key_id == KEY_ID and resp.key_version == 3 and resp.algorithm == "AES-256-GCM"
33
+
34
+
35
+ @pytest.mark.asyncio
36
+ async def test_generate_data_key_default_body_is_empty():
37
+ base = AsyncMock()
38
+ base.post.return_value = DATA_KEY
39
+ await KeysClient(base).generate_data_key(KEY_ID)
40
+ base.post.assert_awaited_once_with(f"/api/v1/keys/{KEY_ID}/generate-data-key", json_data={})
41
+
42
+
43
+ @pytest.mark.asyncio
44
+ async def test_generate_data_key_without_plaintext_route():
45
+ base = AsyncMock()
46
+ base.post.return_value = {**DATA_KEY, "plaintextKey": None}
47
+ resp = await KeysClient(base).generate_data_key_without_plaintext(KEY_ID, algorithm="AES-256-GCM")
48
+ base.post.assert_awaited_once_with(
49
+ f"/api/v1/keys/{KEY_ID}/generate-data-key-without-plaintext",
50
+ json_data={"algorithm": "AES-256-GCM"},
51
+ )
52
+ assert resp.plaintext_key is None
53
+
54
+
55
+ @pytest.mark.asyncio
56
+ async def test_transit_data_key_routes():
57
+ base = AsyncMock()
58
+ base.post.return_value = DATA_KEY
59
+ client = KeysClient(base)
60
+ await client.generate_transit_data_key("my key", key_bytes=32)
61
+ base.post.assert_awaited_with("/api/v1/transit/datakey/my%20key", json_data={"keyBytes": 32})
62
+ await client.generate_transit_data_key_without_plaintext("orders")
63
+ base.post.assert_awaited_with("/api/v1/transit/datakey/orders/without-plaintext", json_data={})
64
+
65
+
66
+ @pytest.mark.asyncio
67
+ async def test_unwrap_route_and_body():
68
+ base = AsyncMock()
69
+ base.post.return_value = {"keyMaterial": "bWF0", "keyId": str(KEY_ID), "keyVersion": 2}
70
+ resp = await KeysClient(base).unwrap(KEY_ID, "ZW5j", context="Y3R4")
71
+ base.post.assert_awaited_once_with(
72
+ f"/api/v1/keys/{KEY_ID}/unwrap", json_data={"wrappedKey": "ZW5j", "context": "Y3R4"}
73
+ )
74
+ assert resp.key_material == "bWF0" and resp.key_version == 2
75
+
76
+
77
+ @pytest.mark.asyncio
78
+ async def test_unwrap_omits_context_when_absent():
79
+ base = AsyncMock()
80
+ base.post.return_value = {"keyMaterial": "bWF0", "keyId": str(KEY_ID), "keyVersion": 2}
81
+ await KeysClient(base).unwrap(KEY_ID, "ZW5j")
82
+ base.post.assert_awaited_once_with(f"/api/v1/keys/{KEY_ID}/unwrap", json_data={"wrappedKey": "ZW5j"})
83
+
84
+
85
+ def _resp(status, payload):
86
+ r = MagicMock()
87
+ r.status_code = status
88
+ r.json.return_value = payload
89
+ return r
90
+
91
+
92
+ @pytest.mark.asyncio
93
+ async def test_403_key_revoked_maps_to_key_revoked_error():
94
+ client = BaseClient(api_key="qapi_x", base_url="https://example.test")
95
+ with pytest.raises(KeyRevokedError) as exc:
96
+ await client._handle_response(
97
+ _resp(403, {"error": "key_revoked", "message": "Key 'k' has been revoked"})
98
+ )
99
+ assert exc.value.error_code == "key_revoked"
100
+ assert exc.value.status_code == 403
101
+ assert isinstance(exc.value, PermissionError)
102
+
103
+
104
+ @pytest.mark.asyncio
105
+ async def test_other_403_stays_permission_error():
106
+ client = BaseClient(api_key="qapi_x", base_url="https://example.test")
107
+ with pytest.raises(PermissionError) as exc:
108
+ await client._handle_response(_resp(403, {"error": "forbidden", "message": "no"}))
109
+ assert not isinstance(exc.value, KeyRevokedError)
110
+ assert exc.value.status_code == 403
111
+
112
+
113
+ @pytest.mark.asyncio
114
+ async def test_404_and_401_do_not_raise_type_error():
115
+ client = BaseClient(api_key="qapi_x", base_url="https://example.test")
116
+ from quantumapi.errors import AuthenticationError, NotFoundError, ValidationError
117
+
118
+ for status, cls in [(401, AuthenticationError), (404, NotFoundError), (400, ValidationError)]:
119
+ with pytest.raises(cls) as exc:
120
+ await client._handle_response(_resp(status, {"error": "e", "message": "m"}))
121
+ assert exc.value.status_code == status
File without changes
File without changes