quantumapi 0.2.0b1__tar.gz → 0.21.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 (42) hide show
  1. {quantumapi-0.2.0b1/quantumapi.egg-info → quantumapi-0.21.0}/PKG-INFO +18 -1
  2. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/README.md +17 -0
  3. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/pyproject.toml +1 -1
  4. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/__init__.py +2 -0
  5. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/async_client.py +2 -0
  6. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/end_users.py +42 -0
  7. quantumapi-0.21.0/quantumapi/client/qrng.py +81 -0
  8. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/secrets.py +46 -8
  9. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/sync_client.py +1 -0
  10. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/__init__.py +15 -0
  11. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/applications.py +15 -0
  12. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/end_users.py +16 -0
  13. quantumapi-0.21.0/quantumapi/models/qrng.py +82 -0
  14. {quantumapi-0.2.0b1 → quantumapi-0.21.0/quantumapi.egg-info}/PKG-INFO +18 -1
  15. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi.egg-info/SOURCES.txt +5 -1
  16. quantumapi-0.21.0/tests/test_end_users.py +61 -0
  17. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/tests/test_parity.py +19 -7
  18. quantumapi-0.21.0/tests/test_qrng.py +118 -0
  19. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/LICENSE +0 -0
  20. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/__init__.py +0 -0
  21. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/applications.py +0 -0
  22. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/base.py +0 -0
  23. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/encryption.py +0 -0
  24. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/health.py +0 -0
  25. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/keys.py +0 -0
  26. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/resource_groups.py +0 -0
  27. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/client/roles.py +0 -0
  28. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/errors/__init__.py +0 -0
  29. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/errors/exceptions.py +0 -0
  30. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/encryption.py +0 -0
  31. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/health.py +0 -0
  32. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/keys.py +0 -0
  33. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/resource_groups.py +0 -0
  34. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/roles.py +0 -0
  35. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/models/secrets.py +0 -0
  36. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi/py.typed +0 -0
  37. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi.egg-info/dependency_links.txt +0 -0
  38. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi.egg-info/requires.txt +0 -0
  39. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/quantumapi.egg-info/top_level.txt +0 -0
  40. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/setup.cfg +0 -0
  41. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/tests/test_exceptions.py +0 -0
  42. {quantumapi-0.2.0b1 → quantumapi-0.21.0}/tests/test_models.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantumapi
3
- Version: 0.2.0b1
3
+ Version: 0.21.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
@@ -265,6 +265,23 @@ await client.users.update(
265
265
  await client.users.deactivate(user_id="user-id")
266
266
  ```
267
267
 
268
+ ### End-Users Client
269
+
270
+ End-users are the people who sign in through one of your OIDC applications (not your tenant's team members).
271
+
272
+ ```python
273
+ # List the users in an application's pool
274
+ pool = await client.end_users.list(app_id)
275
+
276
+ # Clear the automatic sign-in lockout (distinct from an administrative block)
277
+ await client.end_users.unlock(app_id, user_id)
278
+
279
+ # Generate a one-time temporary password; the user must change it at next login
280
+ temp = await client.end_users.generate_temporary_password(app_id, user_id)
281
+ print(f"Hand this to {temp.email} over a secure channel: {temp.temporary_password}")
282
+ # The plaintext is returned once and is never stored in clear text.
283
+ ```
284
+
268
285
  ### Applications Client
269
286
 
270
287
  ```python
@@ -224,6 +224,23 @@ await client.users.update(
224
224
  await client.users.deactivate(user_id="user-id")
225
225
  ```
226
226
 
227
+ ### End-Users Client
228
+
229
+ End-users are the people who sign in through one of your OIDC applications (not your tenant's team members).
230
+
231
+ ```python
232
+ # List the users in an application's pool
233
+ pool = await client.end_users.list(app_id)
234
+
235
+ # Clear the automatic sign-in lockout (distinct from an administrative block)
236
+ await client.end_users.unlock(app_id, user_id)
237
+
238
+ # Generate a one-time temporary password; the user must change it at next login
239
+ temp = await client.end_users.generate_temporary_password(app_id, user_id)
240
+ print(f"Hand this to {temp.email} over a secure channel: {temp.temporary_password}")
241
+ # The plaintext is returned once and is never stored in clear text.
242
+ ```
243
+
227
244
  ### Applications Client
228
245
 
229
246
  ```python
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quantumapi"
7
- version = "0.2.0b1"
7
+ version = "0.21.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"
@@ -6,6 +6,7 @@ from quantumapi.client.encryption import EncryptionClient
6
6
  from quantumapi.client.end_users import EndUsersClient
7
7
  from quantumapi.client.health import HealthClient
8
8
  from quantumapi.client.keys import KeysClient
9
+ from quantumapi.client.qrng import QrngClient
9
10
  from quantumapi.client.secrets import SecretsClient
10
11
  from quantumapi.client.sync_client import QuantumAPISyncClient
11
12
 
@@ -16,6 +17,7 @@ __all__ = [
16
17
  "EndUsersClient",
17
18
  "EncryptionClient",
18
19
  "KeysClient",
20
+ "QrngClient",
19
21
  "SecretsClient",
20
22
  "HealthClient",
21
23
  ]
@@ -9,6 +9,7 @@ from quantumapi.client.encryption import EncryptionClient
9
9
  from quantumapi.client.end_users import EndUsersClient
10
10
  from quantumapi.client.health import HealthClient
11
11
  from quantumapi.client.keys import KeysClient
12
+ from quantumapi.client.qrng import QrngClient
12
13
  from quantumapi.client.resource_groups import ResourceGroupsClient
13
14
  from quantumapi.client.roles import RolesClient
14
15
  from quantumapi.client.secrets import SecretsClient
@@ -87,6 +88,7 @@ class QuantumAPIClient:
87
88
  self.end_users = EndUsersClient(self._base_client)
88
89
  self.roles = RolesClient(self._base_client)
89
90
  self.health = HealthClient(self._base_client)
91
+ self.qrng = QrngClient(self._base_client)
90
92
 
91
93
  async def close(self) -> None:
92
94
  """
@@ -9,6 +9,7 @@ from quantumapi.models.end_users import (
9
9
  EndUser,
10
10
  EndUserListResponse,
11
11
  EndUserRole,
12
+ EndUserTemporaryPasswordResponse,
12
13
  UpdateEndUserRequest,
13
14
  )
14
15
 
@@ -218,6 +219,47 @@ class EndUsersClient:
218
219
  """
219
220
  await self._client.post(f"{self._base_url(app_id)}/{user_id}/unblock")
220
221
 
222
+ async def unlock(self, app_id: UUID, user_id: UUID) -> None:
223
+ """
224
+ Clear the automatic sign-in lockout for an end-user.
225
+
226
+ Distinct from :meth:`unblock`, which lifts an administrative block.
227
+
228
+ Args:
229
+ app_id: Application ID
230
+ user_id: End-user ID
231
+
232
+ Example:
233
+ >>> await client.end_users.unlock(app_id, user_id)
234
+ """
235
+ await self._client.post(f"{self._base_url(app_id)}/{user_id}/unlock")
236
+
237
+ async def generate_temporary_password(
238
+ self, app_id: UUID, user_id: UUID
239
+ ) -> EndUserTemporaryPasswordResponse:
240
+ """
241
+ Generate a one-time temporary password for an end-user.
242
+
243
+ The plaintext is returned once and the user must change it at next
244
+ login. Hand it over through a secure channel; it cannot be retrieved
245
+ again.
246
+
247
+ Args:
248
+ app_id: Application ID
249
+ user_id: End-user ID
250
+
251
+ Returns:
252
+ The temporary password and the end-user's email
253
+
254
+ Example:
255
+ >>> result = await client.end_users.generate_temporary_password(app_id, user_id)
256
+ >>> print(result.temporary_password)
257
+ """
258
+ response = await self._client.post(
259
+ f"{self._base_url(app_id)}/{user_id}/generate-temporary-password"
260
+ )
261
+ return EndUserTemporaryPasswordResponse(**response)
262
+
221
263
  async def delete(self, app_id: UUID, user_id: UUID) -> None:
222
264
  """
223
265
  Delete an end-user permanently.
@@ -0,0 +1,81 @@
1
+ """QRNG bridge client for QuantumAPI SDK (#719)."""
2
+
3
+ from typing import Optional
4
+
5
+ from quantumapi.client.base import BaseClient
6
+ from quantumapi.models.qrng import (
7
+ QRNG_FORMAT_BLOCK_SIZE,
8
+ QrngEntropyRequest,
9
+ QrngEntropyResponse,
10
+ )
11
+
12
+ ALLOW_CSPRNG_HEADER = "X-Allow-Csprng"
13
+ """Request header that opts in to CSPRNG bytes when every quantum provider is down."""
14
+
15
+
16
+ class QrngClient:
17
+ """
18
+ Client for the QRNG bridge: draws quantum entropy from the platform's pooled
19
+ providers (Quantum Blockchains, then ANU) through ``POST /api/v1/qrng/entropy``.
20
+
21
+ Requires an API key with the ``qrng:read`` scope. Bytes are charged against the
22
+ tenant's monthly quota and each key is limited to 100 requests per minute. SaaS only.
23
+ """
24
+
25
+ def __init__(self, base_client: BaseClient) -> None:
26
+ """
27
+ Initialize QrngClient.
28
+
29
+ Args:
30
+ base_client: Base HTTP client
31
+ """
32
+ self._client = base_client
33
+
34
+ async def get_entropy(
35
+ self,
36
+ bytes_count: int,
37
+ format: str = "raw",
38
+ allow_csprng: bool = False,
39
+ ) -> QrngEntropyResponse:
40
+ """
41
+ Draw entropy from the pooled quantum providers.
42
+
43
+ Args:
44
+ bytes_count: Entropy bytes to draw, 1..65536 (server default limit). Must be a
45
+ multiple of 16, 4 or 8 for the ``uuid``, ``int32`` and ``int64`` formats.
46
+ format: ``raw`` (base64, default), ``hex``, ``uuid``, ``int32`` or ``int64``.
47
+ allow_csprng: Send ``X-Allow-Csprng: true`` so the server may return CSPRNG
48
+ bytes (source ``csprng``) instead of failing with 503 when no quantum
49
+ provider is available.
50
+
51
+ Returns:
52
+ The entropy plus source, quota and request metadata.
53
+
54
+ Raises:
55
+ ValueError: ``bytes_count`` is below 1 or not a multiple of the format's block size.
56
+ PermissionError: The API key lacks the ``qrng:read`` scope (403 insufficient_scope).
57
+ ValidationError: 400 invalid_request / invalid_format.
58
+ RateLimitError: 429 quota_exceeded (Retry-After = first day of next month,
59
+ ``details['resetsAt']``) or rate_limit_exceeded.
60
+ ServerError: 503 qrng_unavailable (Retry-After: 30).
61
+
62
+ Example:
63
+ >>> entropy = await client.qrng.get_entropy(32, format="hex")
64
+ >>> key = entropy.as_bytes()
65
+ >>> print(entropy.source, entropy.quota_remaining_mb)
66
+ """
67
+ if bytes_count < 1:
68
+ raise ValueError("bytes_count must be at least 1.")
69
+ normalized = (format or "raw").strip().lower()
70
+ block = QRNG_FORMAT_BLOCK_SIZE.get(normalized, 1)
71
+ if bytes_count % block != 0:
72
+ raise ValueError(f"bytes_count must be a multiple of {block} for format '{normalized}'.")
73
+
74
+ request = QrngEntropyRequest(bytes_count=bytes_count, format=normalized)
75
+ headers: Optional[dict] = {ALLOW_CSPRNG_HEADER: "true"} if allow_csprng else None
76
+ response = await self._client.post(
77
+ "/api/v1/qrng/entropy",
78
+ json_data=request.model_dump(by_alias=True, exclude_none=True),
79
+ headers=headers,
80
+ )
81
+ return QrngEntropyResponse(**response)
@@ -1,5 +1,6 @@
1
1
  """Secrets client for QuantumAPI SDK."""
2
2
 
3
+ import warnings
3
4
  from typing import Any, Dict, List, Optional
4
5
  from uuid import UUID
5
6
 
@@ -238,6 +239,9 @@ class SecretsClient:
238
239
  """
239
240
  Update secret value (creates new version).
240
241
 
242
+ The secret keeps its id across versions, so a stored id stays valid
243
+ after rotation (#747).
244
+
241
245
  Args:
242
246
  secret_id: Secret ID
243
247
  value: New secret value
@@ -260,7 +264,10 @@ class SecretsClient:
260
264
 
261
265
  async def delete(self, secret_id: UUID) -> None:
262
266
  """
263
- Delete a secret.
267
+ Permanently delete a secret.
268
+
269
+ This is irreversible and cannot be undone by :meth:`activate` — use
270
+ :meth:`deactivate` for a recoverable delete.
264
271
 
265
272
  Args:
266
273
  secret_id: Secret ID
@@ -270,21 +277,52 @@ class SecretsClient:
270
277
  """
271
278
  await self._client.delete(f"/api/v1/secrets/{secret_id}")
272
279
 
273
- async def restore(self, secret_id: UUID) -> SecretWithValueResponse:
280
+ async def deactivate(self, secret_id: UUID) -> None:
274
281
  """
275
- Restore a soft-deleted secret.
282
+ Soft-delete a secret.
283
+
284
+ Its value can no longer be retrieved and it drops out of :meth:`list`
285
+ unless ``include_inactive=True``, but the record is kept for audit and
286
+ :meth:`activate` brings it back.
276
287
 
277
288
  Args:
278
289
  secret_id: Secret ID
279
290
 
280
- Returns:
281
- Restored secret metadata
291
+ Example:
292
+ >>> await client.secrets.deactivate(secret_id)
293
+ """
294
+ await self._client.post(f"/api/v1/secrets/{secret_id}/deactivate")
295
+
296
+ async def activate(self, secret_id: UUID) -> None:
297
+ """
298
+ Restore a secret that was soft-deleted with :meth:`deactivate`.
299
+
300
+ Args:
301
+ secret_id: Secret ID
282
302
 
283
303
  Example:
284
- >>> secret = await client.secrets.restore(secret_id)
304
+ >>> await client.secrets.activate(secret_id)
285
305
  """
286
- response = await self._client.post(f"/api/v1/secrets/{secret_id}/restore")
287
- return SecretWithValueResponse(**response)
306
+ await self._client.post(f"/api/v1/secrets/{secret_id}/activate")
307
+
308
+ async def restore(self, secret_id: UUID) -> None:
309
+ """
310
+ Restore a soft-deleted secret.
311
+
312
+ .. deprecated::
313
+ Use :meth:`activate`. This method targeted a ``/restore`` route the API
314
+ has never served, so it 404ed for every secret. See issue #746.
315
+
316
+ Args:
317
+ secret_id: Secret ID
318
+ """
319
+ warnings.warn(
320
+ "secrets.restore() is deprecated; use secrets.activate(). The /restore "
321
+ "route it called does not exist. See issue #746.",
322
+ DeprecationWarning,
323
+ stacklevel=2,
324
+ )
325
+ await self.activate(secret_id)
288
326
 
289
327
  async def list_versions(self, secret_id: UUID) -> SecretVersionListResponse:
290
328
  """
@@ -106,6 +106,7 @@ class QuantumAPISyncClient:
106
106
  self.end_users = _SyncProxy(self._async_client.end_users)
107
107
  self.roles = _SyncProxy(self._async_client.roles)
108
108
  self.health = _SyncProxy(self._async_client.health)
109
+ self.qrng = _SyncProxy(self._async_client.qrng)
109
110
 
110
111
  def close(self) -> None:
111
112
  """Close HTTP client connections."""
@@ -15,6 +15,7 @@ from quantumapi.models.end_users import (
15
15
  EndUserConnection,
16
16
  EndUserListResponse,
17
17
  EndUserRole,
18
+ EndUserTemporaryPasswordResponse,
18
19
  UpdateEndUserRequest,
19
20
  )
20
21
  from quantumapi.models.encryption import (
@@ -40,6 +41,13 @@ from quantumapi.models.keys import (
40
41
  RotateKeyRequest,
41
42
  UpdateKeyRequest,
42
43
  )
44
+ from quantumapi.models.qrng import (
45
+ QRNG_FORMAT_BLOCK_SIZE,
46
+ QrngEntropyFormat,
47
+ QrngEntropyRequest,
48
+ QrngEntropyResponse,
49
+ QrngSourceDetails,
50
+ )
43
51
  from quantumapi.models.resource_groups import (
44
52
  AddResourceGroupItemRequest,
45
53
  CreateResourceGroupRequest,
@@ -78,6 +86,7 @@ __all__ = [
78
86
  # End Users
79
87
  "EndUser",
80
88
  "EndUserRole",
89
+ "EndUserTemporaryPasswordResponse",
81
90
  "EndUserConnection",
82
91
  "EndUserListResponse",
83
92
  "CreateEndUserRequest",
@@ -117,6 +126,12 @@ __all__ = [
117
126
  "ImportSecretItem",
118
127
  "ImportSecretsRequest",
119
128
  "ImportSecretsResponse",
129
+ # QRNG bridge
130
+ "QRNG_FORMAT_BLOCK_SIZE",
131
+ "QrngEntropyFormat",
132
+ "QrngEntropyRequest",
133
+ "QrngEntropyResponse",
134
+ "QrngSourceDetails",
120
135
  # Resource Groups
121
136
  "ResourceGroup",
122
137
  "ResourceGroupDetail",
@@ -42,6 +42,10 @@ class Application(BaseModel):
42
42
  default_factory=list, alias="postLogoutRedirectUris", description="Post-logout redirect URIs"
43
43
  )
44
44
  allowed_scopes: List[str] = Field(default_factory=list, alias="allowedScopes", description="Allowed OAuth2 scopes")
45
+ resources: List[str] = Field(
46
+ default_factory=list,
47
+ description="RFC 8707 resource indicators declared on the application",
48
+ )
45
49
  custom_domain: Optional[str] = Field(default=None, alias="customDomain", description="Custom domain")
46
50
  custom_domain_verified: bool = Field(default=False, alias="customDomainVerified", description="Custom domain verified")
47
51
  created_at: datetime = Field(..., alias="createdAt", description="Creation timestamp")
@@ -84,6 +88,10 @@ class CreateApplicationRequest(BaseModel):
84
88
  allowed_scopes: Optional[List[str]] = Field(
85
89
  default=None, alias="allowedScopes", description="Allowed OAuth2 scopes"
86
90
  )
91
+ resources: Optional[List[str]] = Field(
92
+ default=None,
93
+ description="RFC 8707 resource indicators (absolute URIs) the app may request at /connect/authorize",
94
+ )
87
95
 
88
96
  model_config = {"populate_by_name": True}
89
97
 
@@ -101,5 +109,12 @@ class UpdateApplicationRequest(BaseModel):
101
109
  allowed_scopes: Optional[List[str]] = Field(
102
110
  default=None, alias="allowedScopes", description="Allowed OAuth2 scopes"
103
111
  )
112
+ resources: Optional[List[str]] = Field(
113
+ default=None,
114
+ description=(
115
+ "RFC 8707 resource indicators. None = leave the existing list intact; "
116
+ "[] clears all entries; a populated list replaces the current set."
117
+ ),
118
+ )
104
119
 
105
120
  model_config = {"populate_by_name": True}
@@ -50,6 +50,7 @@ class EndUser(BaseModel):
50
50
  )
51
51
  metadata: Optional[str] = Field(default=None, description="Custom metadata (JSON)")
52
52
  is_blocked: bool = Field(..., alias="isBlocked", description="Whether the user is blocked")
53
+ is_locked_out: bool = Field(default=False, alias="isLockedOut", description="Whether the account is auto-locked after repeated failed sign-ins")
53
54
  blocked_reason: Optional[str] = Field(default=None, alias="blockedReason", description="Block reason")
54
55
  blocked_at: Optional[datetime] = Field(default=None, alias="blockedAt", description="Block timestamp")
55
56
  last_login_at: Optional[datetime] = Field(default=None, alias="lastLoginAt", description="Last login")
@@ -74,6 +75,21 @@ class EndUserListResponse(BaseModel):
74
75
  model_config = {"populate_by_name": True}
75
76
 
76
77
 
78
+ class EndUserTemporaryPasswordResponse(BaseModel):
79
+ """Result of generating a temporary password for an end-user.
80
+
81
+ The plaintext password is returned exactly once and never persisted in
82
+ clear text; the end-user is forced to change it at next login.
83
+ """
84
+
85
+ temporary_password: str = Field(
86
+ ..., alias="temporaryPassword", description="Generated temporary password (shown once)"
87
+ )
88
+ email: str = Field(..., description="Email of the end-user the password belongs to")
89
+
90
+ model_config = {"populate_by_name": True}
91
+
92
+
77
93
  class CreateEndUserRequest(BaseModel):
78
94
  """Request to create an end-user."""
79
95
 
@@ -0,0 +1,82 @@
1
+ """Pydantic models for the QRNG bridge (POST /api/v1/qrng/entropy, #719)."""
2
+
3
+ import base64
4
+ from datetime import datetime
5
+ from typing import List, Literal, Optional, Union
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+ QrngEntropyFormat = Literal["raw", "hex", "uuid", "int32", "int64"]
10
+ """Output formats accepted by the QRNG bridge. Matched case-insensitively by the server."""
11
+
12
+ QRNG_FORMAT_BLOCK_SIZE = {"raw": 1, "hex": 1, "uuid": 16, "int32": 4, "int64": 8}
13
+ """Entropy bytes consumed per output element of each format."""
14
+
15
+
16
+ class QrngEntropyRequest(BaseModel):
17
+ """Request body for ``POST /api/v1/qrng/entropy``."""
18
+
19
+ bytes_count: int = Field(
20
+ ...,
21
+ alias="bytes",
22
+ ge=1,
23
+ description="Entropy bytes to draw, 1..65536 (server default limit). Must be a multiple of 16/4/8 for uuid/int32/int64.",
24
+ )
25
+ format: Optional[str] = Field(
26
+ default=None,
27
+ description="Output format: raw (base64, default), hex, uuid, int32 or int64",
28
+ )
29
+
30
+ model_config = {"populate_by_name": True}
31
+
32
+
33
+ class QrngSourceDetails(BaseModel):
34
+ """Provider metadata attached to a QRNG bridge response."""
35
+
36
+ provider: str = Field(..., description="Internal provider name (QuantumBlockchains, ANU, SystemRandom)")
37
+ is_quantum: bool = Field(..., alias="isQuantum", description="True when the bytes came from quantum hardware")
38
+ served_at: datetime = Field(..., alias="servedAt", description="UTC time at which the entropy was served")
39
+
40
+ model_config = {"populate_by_name": True}
41
+
42
+
43
+ class QrngEntropyResponse(BaseModel):
44
+ """
45
+ Response of ``POST /api/v1/qrng/entropy``.
46
+
47
+ ``entropy`` keeps the payload exactly as the server encoded it: a base64 string for
48
+ ``raw``, a lowercase hex string for ``hex``, a list of UUID strings for ``uuid`` and a
49
+ list of signed little-endian integers for ``int32`` / ``int64``. Use :meth:`as_bytes`
50
+ to decode the ``raw`` and ``hex`` formats.
51
+ """
52
+
53
+ entropy: Union[str, List[str], List[int]] = Field(..., description="Entropy in the requested format")
54
+ format: str = Field(..., description="Canonical name of the format used for entropy")
55
+ source: str = Field(..., description="quantum-blockchains, anu or csprng")
56
+ source_details: QrngSourceDetails = Field(..., alias="sourceDetails", description="Provider metadata")
57
+ consumed_bytes: int = Field(..., alias="consumedBytes", description="Bytes charged against the monthly quota")
58
+ quota_limit_mb: float = Field(..., alias="quotaLimitMb", description="Monthly quota in MB")
59
+ quota_remaining_mb: float = Field(..., alias="quotaRemainingMb", description="MB still available this month")
60
+ request_id: str = Field(..., alias="requestId", description="Request id, also recorded in the audit log")
61
+
62
+ model_config = {"populate_by_name": True}
63
+
64
+ @property
65
+ def is_quantum(self) -> bool:
66
+ """True when the bytes came from a quantum provider rather than the CSPRNG fallback."""
67
+ return self.source_details.is_quantum
68
+
69
+ def as_bytes(self) -> bytes:
70
+ """
71
+ Decode the entropy of a ``raw`` (base64) or ``hex`` response.
72
+
73
+ Raises:
74
+ ValueError: The response is in the uuid, int32 or int64 format.
75
+ """
76
+ if not isinstance(self.entropy, str):
77
+ raise ValueError(f"Entropy in format '{self.format}' is not a byte string; read .entropy directly.")
78
+ if self.format == "hex":
79
+ return bytes.fromhex(self.entropy)
80
+ if self.format == "raw":
81
+ return base64.b64decode(self.entropy)
82
+ raise ValueError(f"Cannot decode entropy in format '{self.format}' to bytes.")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantumapi
3
- Version: 0.2.0b1
3
+ Version: 0.21.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
@@ -265,6 +265,23 @@ await client.users.update(
265
265
  await client.users.deactivate(user_id="user-id")
266
266
  ```
267
267
 
268
+ ### End-Users Client
269
+
270
+ End-users are the people who sign in through one of your OIDC applications (not your tenant's team members).
271
+
272
+ ```python
273
+ # List the users in an application's pool
274
+ pool = await client.end_users.list(app_id)
275
+
276
+ # Clear the automatic sign-in lockout (distinct from an administrative block)
277
+ await client.end_users.unlock(app_id, user_id)
278
+
279
+ # Generate a one-time temporary password; the user must change it at next login
280
+ temp = await client.end_users.generate_temporary_password(app_id, user_id)
281
+ print(f"Hand this to {temp.email} over a secure channel: {temp.temporary_password}")
282
+ # The plaintext is returned once and is never stored in clear text.
283
+ ```
284
+
268
285
  ### Applications Client
269
286
 
270
287
  ```python
@@ -16,6 +16,7 @@ quantumapi/client/encryption.py
16
16
  quantumapi/client/end_users.py
17
17
  quantumapi/client/health.py
18
18
  quantumapi/client/keys.py
19
+ quantumapi/client/qrng.py
19
20
  quantumapi/client/resource_groups.py
20
21
  quantumapi/client/roles.py
21
22
  quantumapi/client/secrets.py
@@ -28,9 +29,12 @@ quantumapi/models/encryption.py
28
29
  quantumapi/models/end_users.py
29
30
  quantumapi/models/health.py
30
31
  quantumapi/models/keys.py
32
+ quantumapi/models/qrng.py
31
33
  quantumapi/models/resource_groups.py
32
34
  quantumapi/models/roles.py
33
35
  quantumapi/models/secrets.py
36
+ tests/test_end_users.py
34
37
  tests/test_exceptions.py
35
38
  tests/test_models.py
36
- tests/test_parity.py
39
+ tests/test_parity.py
40
+ tests/test_qrng.py
@@ -0,0 +1,61 @@
1
+ """Tests for EndUsersClient: temporary-password and unlock parity (#733)."""
2
+
3
+ from unittest.mock import AsyncMock
4
+ from uuid import uuid4
5
+
6
+ import pytest
7
+
8
+ from quantumapi.client.end_users import EndUsersClient
9
+ from quantumapi.models.end_users import EndUserTemporaryPasswordResponse
10
+
11
+
12
+ class TestEndUserTemporaryPasswordResponse:
13
+ """Tests for the EndUserTemporaryPasswordResponse model."""
14
+
15
+ def test_parses_camel_case_payload(self):
16
+ resp = EndUserTemporaryPasswordResponse(
17
+ **{"temporaryPassword": "Xk9#mP2vQ7wL4nRt", "email": "alice@example.com"}
18
+ )
19
+ assert resp.temporary_password == "Xk9#mP2vQ7wL4nRt"
20
+ assert resp.email == "alice@example.com"
21
+
22
+ def test_accepts_snake_case_by_name(self):
23
+ resp = EndUserTemporaryPasswordResponse(
24
+ temporary_password="Xk9#mP2vQ7wL4nRt", email="alice@example.com"
25
+ )
26
+ assert resp.temporary_password == "Xk9#mP2vQ7wL4nRt"
27
+
28
+
29
+ class TestEndUsersClientGenerateTemporaryPassword:
30
+ """Tests for EndUsersClient.generate_temporary_password."""
31
+
32
+ @pytest.mark.asyncio
33
+ async def test_posts_to_generate_temporary_password_route(self):
34
+ base = AsyncMock()
35
+ base.post.return_value = {
36
+ "temporaryPassword": "Xk9#mP2vQ7wL4nRt",
37
+ "email": "alice@example.com",
38
+ }
39
+ client = EndUsersClient(base)
40
+ app_id, user_id = uuid4(), uuid4()
41
+
42
+ result = await client.generate_temporary_password(app_id, user_id)
43
+
44
+ base.post.assert_awaited_once_with(
45
+ f"/api/v1/applications/{app_id}/end-users/{user_id}/generate-temporary-password"
46
+ )
47
+ assert result.temporary_password == "Xk9#mP2vQ7wL4nRt"
48
+ assert result.email == "alice@example.com"
49
+
50
+ @pytest.mark.asyncio
51
+ async def test_unlock_posts_to_unlock_route(self):
52
+ base = AsyncMock()
53
+ base.post.return_value = {}
54
+ client = EndUsersClient(base)
55
+ app_id, user_id = uuid4(), uuid4()
56
+
57
+ await client.unlock(app_id, user_id)
58
+
59
+ base.post.assert_awaited_once_with(
60
+ f"/api/v1/applications/{app_id}/end-users/{user_id}/unlock"
61
+ )
@@ -434,23 +434,35 @@ class TestImportSecretsModels:
434
434
  # ---------------------------------------------------------------------------
435
435
 
436
436
  class TestSecretsClientRestore:
437
- """Tests for SecretsClient.restore method."""
437
+ """Tests for the deprecated SecretsClient.restore method (#746)."""
438
438
 
439
439
  @pytest.fixture
440
440
  def base_client(self):
441
441
  client = MagicMock()
442
- client.post = AsyncMock()
442
+ client.post = AsyncMock(return_value=None)
443
443
  return client
444
444
 
445
- async def test_restore_secret(self, base_client):
445
+ async def test_restore_secret_delegates_to_activate(self, base_client):
446
446
  secret_id = uuid4()
447
- base_client.post.return_value = _make_secret_response(id=secret_id)
448
447
 
449
448
  secrets_client = SecretsClient(base_client)
450
- result = await secrets_client.restore(secret_id)
449
+ with pytest.warns(DeprecationWarning, match="secrets.activate"):
450
+ result = await secrets_client.restore(secret_id)
451
451
 
452
- base_client.post.assert_called_once_with(f"/api/v1/secrets/{secret_id}/restore")
453
- assert isinstance(result, SecretWithValueResponse)
452
+ base_client.post.assert_called_once_with(f"/api/v1/secrets/{secret_id}/activate")
453
+ assert result is None
454
+
455
+ async def test_activate_and_deactivate_routes(self, base_client):
456
+ secret_id = uuid4()
457
+ secrets_client = SecretsClient(base_client)
458
+
459
+ await secrets_client.deactivate(secret_id)
460
+ await secrets_client.activate(secret_id)
461
+
462
+ assert [c.args[0] for c in base_client.post.call_args_list] == [
463
+ f"/api/v1/secrets/{secret_id}/deactivate",
464
+ f"/api/v1/secrets/{secret_id}/activate",
465
+ ]
454
466
 
455
467
 
456
468
  class TestSecretsClientListVersions:
@@ -0,0 +1,118 @@
1
+ """Tests for QrngClient and the QRNG bridge models (#719)."""
2
+
3
+ import base64
4
+ from unittest.mock import AsyncMock
5
+
6
+ import pytest
7
+
8
+ from quantumapi.client.qrng import ALLOW_CSPRNG_HEADER, QrngClient
9
+ from quantumapi.client.sync_client import QuantumAPISyncClient
10
+ from quantumapi.models.qrng import QrngEntropyRequest, QrngEntropyResponse
11
+
12
+
13
+ def _envelope(entropy, fmt, source="quantum-blockchains", is_quantum=True):
14
+ return {
15
+ "entropy": entropy,
16
+ "format": fmt,
17
+ "source": source,
18
+ "sourceDetails": {
19
+ "provider": "QuantumBlockchains" if is_quantum else "SystemRandom",
20
+ "isQuantum": is_quantum,
21
+ "servedAt": "2026-09-02T10:00:00+00:00",
22
+ },
23
+ "consumedBytes": 32,
24
+ "quotaLimitMb": 100.0,
25
+ "quotaRemainingMb": 99.997,
26
+ "requestId": "3f1a2b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b",
27
+ }
28
+
29
+
30
+ class TestQrngModels:
31
+ def test_request_serializes_bytes_alias(self):
32
+ req = QrngEntropyRequest(bytes_count=32, format="hex")
33
+ assert req.model_dump(by_alias=True, exclude_none=True) == {"bytes": 32, "format": "hex"}
34
+
35
+ def test_request_rejects_zero_bytes(self):
36
+ with pytest.raises(Exception):
37
+ QrngEntropyRequest(bytes_count=0)
38
+
39
+ def test_response_parses_camel_case_and_decodes_raw(self):
40
+ raw = bytes(range(32))
41
+ resp = QrngEntropyResponse(**_envelope(base64.b64encode(raw).decode(), "raw"))
42
+ assert resp.as_bytes() == raw
43
+ assert resp.is_quantum is True
44
+ assert resp.source_details.provider == "QuantumBlockchains"
45
+ assert resp.quota_remaining_mb == 99.997
46
+ assert resp.request_id == "3f1a2b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b"
47
+
48
+ def test_response_decodes_hex(self):
49
+ resp = QrngEntropyResponse(**_envelope("deadbeef", "hex"))
50
+ assert resp.as_bytes() == b"\xde\xad\xbe\xef"
51
+
52
+ def test_response_keeps_int64_precision_and_refuses_as_bytes(self):
53
+ values = [-(2**63), -1, 2**63 - 1]
54
+ resp = QrngEntropyResponse(**_envelope(values, "int64"))
55
+ assert resp.entropy == values
56
+ with pytest.raises(ValueError):
57
+ resp.as_bytes()
58
+
59
+ def test_response_keeps_uuid_list(self):
60
+ resp = QrngEntropyResponse(**_envelope(["0f1e2d3c-4b5a-4978-8695-a4b3c2d1e0f0"], "uuid"))
61
+ assert resp.entropy == ["0f1e2d3c-4b5a-4978-8695-a4b3c2d1e0f0"]
62
+
63
+
64
+ class TestQrngClientGetEntropy:
65
+ @pytest.mark.asyncio
66
+ async def test_posts_to_entropy_route_without_csprng_header(self):
67
+ base = AsyncMock()
68
+ base.post.return_value = _envelope(base64.b64encode(bytes(32)).decode(), "raw")
69
+ client = QrngClient(base)
70
+
71
+ result = await client.get_entropy(32)
72
+
73
+ base.post.assert_awaited_once_with(
74
+ "/api/v1/qrng/entropy",
75
+ json_data={"bytes": 32, "format": "raw"},
76
+ headers=None,
77
+ )
78
+ assert result.format == "raw"
79
+ assert result.as_bytes() == bytes(32)
80
+
81
+ @pytest.mark.asyncio
82
+ async def test_sends_allow_csprng_header_and_normalizes_format(self):
83
+ base = AsyncMock()
84
+ base.post.return_value = _envelope("00ff", "hex", source="csprng", is_quantum=False)
85
+ client = QrngClient(base)
86
+
87
+ result = await client.get_entropy(2, format=" HEX ", allow_csprng=True)
88
+
89
+ base.post.assert_awaited_once_with(
90
+ "/api/v1/qrng/entropy",
91
+ json_data={"bytes": 2, "format": "hex"},
92
+ headers={ALLOW_CSPRNG_HEADER: "true"},
93
+ )
94
+ assert result.source == "csprng"
95
+ assert result.is_quantum is False
96
+
97
+ @pytest.mark.asyncio
98
+ @pytest.mark.parametrize(
99
+ "bytes_count,fmt",
100
+ [(0, "raw"), (15, "uuid"), (6, "int32"), (12, "int64")],
101
+ )
102
+ async def test_rejects_invalid_byte_counts_before_sending(self, bytes_count, fmt):
103
+ base = AsyncMock()
104
+ client = QrngClient(base)
105
+
106
+ with pytest.raises(ValueError):
107
+ await client.get_entropy(bytes_count, format=fmt)
108
+
109
+ base.post.assert_not_awaited()
110
+
111
+
112
+ class TestSyncProxy:
113
+ def test_sync_client_exposes_qrng(self):
114
+ client = QuantumAPISyncClient(api_key="qapi_test")
115
+ try:
116
+ assert hasattr(client.qrng, "get_entropy")
117
+ finally:
118
+ client.close()
File without changes
File without changes