auth 3.7.0__tar.gz → 3.7.2__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 (120) hide show
  1. {auth-3.7.0 → auth-3.7.2}/PKG-INFO +1 -1
  2. {auth-3.7.0 → auth-3.7.2}/auth/routes/tenant.py +2 -1
  3. {auth-3.7.0 → auth-3.7.2}/auth/services/base.py +2 -1
  4. {auth-3.7.0 → auth-3.7.2}/auth/services/keys.py +14 -5
  5. {auth-3.7.0 → auth-3.7.2}/auth/services/recovery.py +3 -1
  6. {auth-3.7.0 → auth-3.7.2}/auth/services/tenant.py +15 -4
  7. {auth-3.7.0 → auth-3.7.2}/auth/static_docs/api_reference.md +8 -5
  8. {auth-3.7.0 → auth-3.7.2}/auth.egg-info/PKG-INFO +1 -1
  9. {auth-3.7.0 → auth-3.7.2}/auth.egg-info/SOURCES.txt +2 -0
  10. {auth-3.7.0 → auth-3.7.2}/pyproject.toml +1 -1
  11. auth-3.7.2/tests/test_apikey_cap_expiry.py +102 -0
  12. auth-3.7.2/tests/test_rotate_key_preserves_strict.py +90 -0
  13. {auth-3.7.0 → auth-3.7.2}/LICENSE +0 -0
  14. {auth-3.7.0 → auth-3.7.2}/README.md +0 -0
  15. {auth-3.7.0 → auth-3.7.2}/auth/__init__.py +0 -0
  16. {auth-3.7.0 → auth-3.7.2}/auth/api_keys.py +0 -0
  17. {auth-3.7.0 → auth-3.7.2}/auth/audit.py +0 -0
  18. {auth-3.7.0 → auth-3.7.2}/auth/circuit_breaker.py +0 -0
  19. {auth-3.7.0 → auth-3.7.2}/auth/client/__init__.py +0 -0
  20. {auth-3.7.0 → auth-3.7.2}/auth/client/_transport.py +0 -0
  21. {auth-3.7.0 → auth-3.7.2}/auth/client/base.py +0 -0
  22. {auth-3.7.0 → auth-3.7.2}/auth/client/keys.py +0 -0
  23. {auth-3.7.0 → auth-3.7.2}/auth/client/rbac.py +0 -0
  24. {auth-3.7.0 → auth-3.7.2}/auth/client/workflow.py +0 -0
  25. {auth-3.7.0 → auth-3.7.2}/auth/cmd/__init__.py +0 -0
  26. {auth-3.7.0 → auth-3.7.2}/auth/cmd/server.py +0 -0
  27. {auth-3.7.0 → auth-3.7.2}/auth/config.py +0 -0
  28. {auth-3.7.0 → auth-3.7.2}/auth/core/REST/__init__.py +0 -0
  29. {auth-3.7.0 → auth-3.7.2}/auth/core/REST/client.py +0 -0
  30. {auth-3.7.0 → auth-3.7.2}/auth/core/__init__.py +0 -0
  31. {auth-3.7.0 → auth-3.7.2}/auth/core/models/__init__.py +0 -0
  32. {auth-3.7.0 → auth-3.7.2}/auth/database.py +0 -0
  33. {auth-3.7.0 → auth-3.7.2}/auth/decorators.py +0 -0
  34. {auth-3.7.0 → auth-3.7.2}/auth/docs_page.py +0 -0
  35. {auth-3.7.0 → auth-3.7.2}/auth/encryption.py +0 -0
  36. {auth-3.7.0 → auth-3.7.2}/auth/key_expiry.py +0 -0
  37. {auth-3.7.0 → auth-3.7.2}/auth/keycheck.py +0 -0
  38. {auth-3.7.0 → auth-3.7.2}/auth/logging_config.py +0 -0
  39. {auth-3.7.0 → auth-3.7.2}/auth/main.py +0 -0
  40. {auth-3.7.0 → auth-3.7.2}/auth/migrate.py +0 -0
  41. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01KYTMDEYFVH43HKR0MQWW1EMP_add_auth_api_key.sql +0 -0
  42. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01KYTQN79R1ZBNDPA3ND9AAA73_drop_alembic_version.sql +0 -0
  43. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01KYTRKMWNBDDZPN1H0AXRTT5G_add_auth_tenant_settings.sql +0 -0
  44. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01KYTX0MKVZ775P62CJ87631Z1_grandfather_strict_users.sql +0 -0
  45. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01KZJWHG32K9X1AFBPPB4YJC6A_partition_audit_log.sql +0 -0
  46. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01M2Y4SMRCS9PW29AA0TFCVXKR_add_creator_fp_and_rotate_key.sql +0 -0
  47. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01M2Y4YA6RY6DZWT235CDV9H5W_enable_row_level_security.sql +0 -0
  48. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01M2Y8WEM8SYB1SG8QD35S3T6M_add_encryption_canary.sql +0 -0
  49. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01M2Y9AYF2B7WM3AHMGX14AWWJ_rls_on_new_audit_partitions.sql +0 -0
  50. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01M2Y9FNKBJ513W0XVCYFYPDR9_drop_stale_public_tables.sql +0 -0
  51. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01M2Y9WFEY32ZWDP161SHR1B2M_add_apply_tenant_rls_function.sql +0 -0
  52. {auth-3.7.0 → auth-3.7.2}/auth/migrations/01M2Z040JTSGF3V0AQMP583BDA_create_audit_log_partitioned_if_absent.sql +0 -0
  53. {auth-3.7.0 → auth-3.7.2}/auth/migrations/__init__.py +0 -0
  54. {auth-3.7.0 → auth-3.7.2}/auth/models/sql.py +0 -0
  55. {auth-3.7.0 → auth-3.7.2}/auth/response_format.py +0 -0
  56. {auth-3.7.0 → auth-3.7.2}/auth/rls.py +0 -0
  57. {auth-3.7.0 → auth-3.7.2}/auth/routes/__init__.py +0 -0
  58. {auth-3.7.0 → auth-3.7.2}/auth/routes/_common.py +0 -0
  59. {auth-3.7.0 → auth-3.7.2}/auth/routes/apikeys.py +0 -0
  60. {auth-3.7.0 → auth-3.7.2}/auth/routes/membership.py +0 -0
  61. {auth-3.7.0 → auth-3.7.2}/auth/routes/permissions.py +0 -0
  62. {auth-3.7.0 → auth-3.7.2}/auth/routes/public.py +0 -0
  63. {auth-3.7.0 → auth-3.7.2}/auth/routes/roles.py +0 -0
  64. {auth-3.7.0 → auth-3.7.2}/auth/routes/workflow.py +0 -0
  65. {auth-3.7.0 → auth-3.7.2}/auth/sanitizer.py +0 -0
  66. {auth-3.7.0 → auth-3.7.2}/auth/schema_check.py +0 -0
  67. {auth-3.7.0 → auth-3.7.2}/auth/schema_reconcile.py +0 -0
  68. {auth-3.7.0 → auth-3.7.2}/auth/server.py +0 -0
  69. {auth-3.7.0 → auth-3.7.2}/auth/services/queries.py +0 -0
  70. {auth-3.7.0 → auth-3.7.2}/auth/services/rbac.py +0 -0
  71. {auth-3.7.0 → auth-3.7.2}/auth/services/rotation.py +0 -0
  72. {auth-3.7.0 → auth-3.7.2}/auth/services/service.py +0 -0
  73. {auth-3.7.0 → auth-3.7.2}/auth/static_docs/__init__.py +0 -0
  74. {auth-3.7.0 → auth-3.7.2}/auth/static_docs/claude_guide.md +0 -0
  75. {auth-3.7.0 → auth-3.7.2}/auth/static_docs/landing.md +0 -0
  76. {auth-3.7.0 → auth-3.7.2}/auth/static_docs/page.html +0 -0
  77. {auth-3.7.0 → auth-3.7.2}/auth/validation.py +0 -0
  78. {auth-3.7.0 → auth-3.7.2}/auth/workflow_checker.py +0 -0
  79. {auth-3.7.0 → auth-3.7.2}/auth.egg-info/dependency_links.txt +0 -0
  80. {auth-3.7.0 → auth-3.7.2}/auth.egg-info/entry_points.txt +0 -0
  81. {auth-3.7.0 → auth-3.7.2}/auth.egg-info/requires.txt +0 -0
  82. {auth-3.7.0 → auth-3.7.2}/auth.egg-info/top_level.txt +0 -0
  83. {auth-3.7.0 → auth-3.7.2}/setup.cfg +0 -0
  84. {auth-3.7.0 → auth-3.7.2}/tests/test_api_keys.py +0 -0
  85. {auth-3.7.0 → auth-3.7.2}/tests/test_api_keys_encryption.py +0 -0
  86. {auth-3.7.0 → auth-3.7.2}/tests/test_apikey_audit_outcome.py +0 -0
  87. {auth-3.7.0 → auth-3.7.2}/tests/test_apikey_expiry.py +0 -0
  88. {auth-3.7.0 → auth-3.7.2}/tests/test_audit_integrity.py +0 -0
  89. {auth-3.7.0 → auth-3.7.2}/tests/test_client.py +0 -0
  90. {auth-3.7.0 → auth-3.7.2}/tests/test_client_exceptions_do_not_render_payload.py +0 -0
  91. {auth-3.7.0 → auth-3.7.2}/tests/test_client_rest.py +0 -0
  92. {auth-3.7.0 → auth-3.7.2}/tests/test_cmd_server.py +0 -0
  93. {auth-3.7.0 → auth-3.7.2}/tests/test_config.py +0 -0
  94. {auth-3.7.0 → auth-3.7.2}/tests/test_correctness_hardening.py +0 -0
  95. {auth-3.7.0 → auth-3.7.2}/tests/test_database_pool_settings.py +0 -0
  96. {auth-3.7.0 → auth-3.7.2}/tests/test_database_sslmode.py +0 -0
  97. {auth-3.7.0 → auth-3.7.2}/tests/test_degraded_response_is_a_contract.py +0 -0
  98. {auth-3.7.0 → auth-3.7.2}/tests/test_deploy_lock.py +0 -0
  99. {auth-3.7.0 → auth-3.7.2}/tests/test_docs_page.py +0 -0
  100. {auth-3.7.0 → auth-3.7.2}/tests/test_encryption.py +0 -0
  101. {auth-3.7.0 → auth-3.7.2}/tests/test_encryption_integration.py +0 -0
  102. {auth-3.7.0 → auth-3.7.2}/tests/test_flask.py +0 -0
  103. {auth-3.7.0 → auth-3.7.2}/tests/test_gunicorn_config_invariants.py +0 -0
  104. {auth-3.7.0 → auth-3.7.2}/tests/test_import_footprint.py +0 -0
  105. {auth-3.7.0 → auth-3.7.2}/tests/test_key_rotation.py +0 -0
  106. {auth-3.7.0 → auth-3.7.2}/tests/test_log_redaction.py +0 -0
  107. {auth-3.7.0 → auth-3.7.2}/tests/test_migrate_cli.py +0 -0
  108. {auth-3.7.0 → auth-3.7.2}/tests/test_no_bundled_libpq.py +0 -0
  109. {auth-3.7.0 → auth-3.7.2}/tests/test_phase_a_hardening.py +0 -0
  110. {auth-3.7.0 → auth-3.7.2}/tests/test_provision_script_no_dsn_leak.py +0 -0
  111. {auth-3.7.0 → auth-3.7.2}/tests/test_reencryption.py +0 -0
  112. {auth-3.7.0 → auth-3.7.2}/tests/test_routes_errors.py +0 -0
  113. {auth-3.7.0 → auth-3.7.2}/tests/test_schema_check.py +0 -0
  114. {auth-3.7.0 → auth-3.7.2}/tests/test_self_service_audit.py +0 -0
  115. {auth-3.7.0 → auth-3.7.2}/tests/test_served_docs_host.py +0 -0
  116. {auth-3.7.0 → auth-3.7.2}/tests/test_server.py +0 -0
  117. {auth-3.7.0 → auth-3.7.2}/tests/test_service_lifecycle.py +0 -0
  118. {auth-3.7.0 → auth-3.7.2}/tests/test_settings_do_not_echo_secrets.py +0 -0
  119. {auth-3.7.0 → auth-3.7.2}/tests/test_strict_default.py +0 -0
  120. {auth-3.7.0 → auth-3.7.2}/tests/test_strict_users.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auth
3
- Version: 3.7.0
3
+ Version: 3.7.2
4
4
  Summary: Authorization for humans
5
5
  Author-email: Farshid Ashouri <farsheed.ashouri@gmail.com>
6
6
  License-Expression: MIT
@@ -12,7 +12,7 @@ from auth.audit import (
12
12
  record_audit,
13
13
  )
14
14
  from auth.config import get_settings
15
- from auth.decorators import audit_log
15
+ from auth.decorators import audit_log, record_outcome
16
16
  from auth.response_format import (
17
17
  APIResponse,
18
18
  )
@@ -143,6 +143,7 @@ def register(app):
143
143
  """
144
144
  auth_service = _get_auth_service(db)
145
145
  secret = auth_service.issue_rotate_key()
146
+ record_outcome(**auth_service.rotate_key_settings)
146
147
  if secret is None:
147
148
  return (
148
149
  jsonify(
@@ -8,7 +8,7 @@ chain of mixins rooted here; see :mod:`auth.services.service`.
8
8
 
9
9
  import logging
10
10
  from datetime import datetime, timezone
11
- from typing import Any, Optional
11
+ from typing import Any, Dict, Optional
12
12
 
13
13
  from sqlalchemy import text
14
14
  from sqlalchemy.orm import Session
@@ -53,6 +53,7 @@ class ServiceBase:
53
53
  # an explicit bool overrides it for in-process/library callers.
54
54
  self._strict_override = strict_users
55
55
  self._strict_cache: Optional[bool] = None
56
+ self.rotate_key_settings: Dict[str, Any] = {}
56
57
  # Bind this tenant to the session so Row Level Security can see it. Done
57
58
  # here rather than in the HTTP layer so library callers are covered too,
58
59
  # and via an after_begin listener so it survives the per-method commits
@@ -3,7 +3,7 @@
3
3
  from datetime import datetime
4
4
  from typing import Any, Dict, List, Optional, Tuple, cast
5
5
 
6
- from sqlalchemy import func
6
+ from sqlalchemy import func, or_
7
7
 
8
8
  from auth.api_keys import generate_api_key, hash_api_key
9
9
  from auth.key_expiry import KeyExpiryError, check_expiry
@@ -17,6 +17,8 @@ from auth.services.rbac import RbacMixin
17
17
  # while staying far above any legitimate "one key per device/CI job" usage.
18
18
  API_KEYS_PER_USER_CAP = 25
19
19
 
20
+ _api_key_table = AuthApiKey.__table__
21
+
20
22
  # A validate only rewrites last_used_at when it is at least this stale, so the
21
23
  # hot path does at most one row-update per key per window.
22
24
  _LAST_USED_THROTTLE_SECONDS = 60
@@ -78,12 +80,13 @@ class ApiKeyMixin(RbacMixin):
78
80
  """Mint and store an API key for ``user`` in this tenant's namespace.
79
81
 
80
82
  Returns the one-time secret plus metadata, or ``None`` when the user
81
- already holds ``API_KEYS_PER_USER_CAP`` active keys. The tenant lock
82
- serializes against key rotation so the new row cannot strand under a
83
- creator that is being moved.
83
+ already holds ``API_KEYS_PER_USER_CAP`` keys that are neither revoked
84
+ nor expired. The tenant lock serializes against key rotation so the
85
+ new row cannot strand under a creator that is being moved.
84
86
  """
87
+ now = _utcnow()
85
88
  if expires_at is not None:
86
- check_expiry(expires_at, _utcnow())
89
+ check_expiry(expires_at, now)
87
90
  self._lock_tenant()
88
91
  active = (
89
92
  self.db.query(func.count(AuthApiKey.id))
@@ -92,6 +95,12 @@ class ApiKeyMixin(RbacMixin):
92
95
  AuthApiKey._user == self._get_encrypted_user(user),
93
96
  AuthApiKey.is_active,
94
97
  )
98
+ .filter(
99
+ or_(
100
+ _api_key_table.c.expires_at.is_(None),
101
+ _api_key_table.c.expires_at > now,
102
+ )
103
+ )
95
104
  .scalar()
96
105
  or 0
97
106
  )
@@ -114,7 +114,9 @@ def recover_namespace(db, secret: str, new_client_key: str) -> Dict[str, Any]:
114
114
  )
115
115
  new_secret, new_hash = generate_rotate_key()
116
116
  if row is None:
117
- row = AuthTenantSettings(creator=new_client_key, strict_users=False)
117
+ row = AuthTenantSettings(
118
+ creator=new_client_key, strict_users=service.default_strict_users()
119
+ )
118
120
  db.add(row)
119
121
  row.rotate_key_hash = new_hash
120
122
  row.rotate_key_issued_at = _utcnow()
@@ -43,11 +43,15 @@ class TenantMixin(ServiceBase):
43
43
  # 3.0.0: tenants with no stored setting follow the server
44
44
  # default (strict). Pre-3.0 tenants never reach this branch —
45
45
  # grandfathering wrote them explicit false rows.
46
- from auth.config import get_settings
47
-
48
- self._strict_cache = bool(get_settings().strict_users_default)
46
+ self._strict_cache = self.default_strict_users()
49
47
  return self._strict_cache
50
48
 
49
+ @staticmethod
50
+ def default_strict_users() -> bool:
51
+ from auth.config import get_settings
52
+
53
+ return bool(get_settings().strict_users_default)
54
+
51
55
  def get_settings(self) -> Dict[str, Any]:
52
56
  """This tenant's settings (defaults when no row exists)."""
53
57
  return {"strict_users": self.strict_users_enabled()}
@@ -86,10 +90,17 @@ class TenantMixin(ServiceBase):
86
90
  .filter(AuthTenantSettings.creator == self.client)
87
91
  .first()
88
92
  )
93
+ created = row is None
89
94
  if row is None:
90
- row = AuthTenantSettings(creator=self.client, strict_users=False)
95
+ row = AuthTenantSettings(
96
+ creator=self.client, strict_users=self.default_strict_users()
97
+ )
91
98
  self.db.add(row)
92
99
  self.db.flush()
100
+ self.rotate_key_settings = {
101
+ "strict_users": bool(row.strict_users),
102
+ "settings_row_created": created,
103
+ }
93
104
  if cast(Optional[datetime], row.rotate_key_issued_at) is not None:
94
105
  return None
95
106
 
@@ -266,15 +266,18 @@ Keys for your *users*, held in your namespace. The `api_key` secret appears
266
266
  only in the creating response (auth stores its SHA-256, nothing recoverable).
267
267
  Listing shows revoked keys too (`is_active: false`) so a UI can render
268
268
  history. Validate answers `valid: false` with a `reason` rather than erroring;
269
- a key from another tenant is indistinguishable from an unknown one. At most 25
270
- active keys per user — revoke to free a slot. `expires_at` is UTC; a value with
271
- an offset is converted and one without is read as UTC. From the moment it
269
+ a key from another tenant is indistinguishable from an unknown one. A user can
270
+ hold at most 25 keys that are neither revoked nor expired. Revoking a key frees
271
+ its slot, and so does reaching its `expires_at`. `expires_at` is UTC; a value
272
+ with an offset is converted and one without is read as UTC. From the moment it
272
273
  passes, validate and check_permission answer `{{"valid": false, "reason":
273
- "expired"}}`.
274
+ "expired"}}`. An expired key still lists `is_active: true` until it is revoked,
275
+ so compare `expires_at` with the current UTC time, or ask validate, to know
276
+ whether a key still works.
274
277
 
275
278
  | Method | Path | Returns |
276
279
  |---|---|---|
277
- | POST | `/api/apikeys/user/<user>` | optional body `{{"label": "laptop", "expires_at": "2027-01-01T00:00:00Z"}}` (both optional; any other field is a 400) → wrapped, `data` = `{{"api_key": "rak_<43 chars, shown ONCE>", "key_id": "<uuid4>", "user": "alice", "label": "laptop", "key_prefix": "rak_ab12cd34", "created": "<iso>", "expires_at": "<iso or null>"}}` (400 once 25 active keys exist, or when expires_at is in the past or more than 365 days ahead) |
280
+ | POST | `/api/apikeys/user/<user>` | optional body `{{"label": "laptop", "expires_at": "2027-01-01T00:00:00Z"}}` (both optional; any other field is a 400) → wrapped, `data` = `{{"api_key": "rak_<43 chars, shown ONCE>", "key_id": "<uuid4>", "user": "alice", "label": "laptop", "key_prefix": "rak_ab12cd34", "created": "<iso>", "expires_at": "<iso or null>"}}` (400 once the user holds 25 keys that are neither revoked nor expired, or when expires_at is in the past or more than 365 days ahead) |
278
281
  | PATCH | `/api/apikeys/user/<user>/<key_id>` | body `{{"expires_at": "<ISO-8601>"}}` → wrapped, `data` = the key's listing entry. Shorten-only: the new time must be in the future, earlier than the current expiry, and at most 365 days ahead; 400 otherwise, also for a revoked key; 404 JSON if no such key |
279
282
  | GET | `/api/apikeys/user/<user>` | wrapped, `data` = `{{"count": 1, "keys": [{{"key_id": "<uuid4>", "key_prefix": "rak_ab12cd34", "label": "laptop", "is_active": true, "created": "<iso>", "revoked_at": null, "expires_at": null, "last_used_at": "<iso>"}}]}}` |
280
283
  | DELETE | `/api/apikeys/user/<user>/<key_id>` | wrapped, `data` = `{{"revoked": true, "already_revoked": false}}` (repeat calls idempotent; 404 JSON if no such key for that user in your namespace) |
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auth
3
- Version: 3.7.0
3
+ Version: 3.7.2
4
4
  Summary: Authorization for humans
5
5
  Author-email: Farshid Ashouri <farsheed.ashouri@gmail.com>
6
6
  License-Expression: MIT
@@ -80,6 +80,7 @@ auth/static_docs/page.html
80
80
  tests/test_api_keys.py
81
81
  tests/test_api_keys_encryption.py
82
82
  tests/test_apikey_audit_outcome.py
83
+ tests/test_apikey_cap_expiry.py
83
84
  tests/test_apikey_expiry.py
84
85
  tests/test_audit_integrity.py
85
86
  tests/test_client.py
@@ -105,6 +106,7 @@ tests/test_no_bundled_libpq.py
105
106
  tests/test_phase_a_hardening.py
106
107
  tests/test_provision_script_no_dsn_leak.py
107
108
  tests/test_reencryption.py
109
+ tests/test_rotate_key_preserves_strict.py
108
110
  tests/test_routes_errors.py
109
111
  tests/test_schema_check.py
110
112
  tests/test_self_service_audit.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "auth"
7
- version = "3.7.0"
7
+ version = "3.7.2"
8
8
  description = "Authorization for humans"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1,102 @@
1
+ import uuid
2
+ from datetime import datetime, timedelta, timezone
3
+
4
+ import pytest
5
+
6
+ import auth.services.keys as keys_module
7
+ from auth.main import create_app
8
+ from auth.services.keys import API_KEYS_PER_USER_CAP
9
+
10
+
11
+ @pytest.fixture
12
+ def client():
13
+ application = create_app()
14
+ application.config["TESTING"] = True
15
+ return application.test_client()
16
+
17
+
18
+ def _h(key):
19
+ return {"Authorization": f"Bearer {key}"}
20
+
21
+
22
+ def _now():
23
+ return datetime.now(timezone.utc).replace(tzinfo=None)
24
+
25
+
26
+ def _namespace(client):
27
+ key = str(uuid.uuid4())
28
+ client.put("/api/settings", json={"strict_users": False}, headers=_h(key))
29
+ return key
30
+
31
+
32
+ def _mint(client, key, body=None, user="svc"):
33
+ return client.post(f"/api/apikeys/user/{user}", json=body or {}, headers=_h(key))
34
+
35
+
36
+ def _listing(client, key, user="svc"):
37
+ return client.get(f"/api/apikeys/user/{user}", headers=_h(key)).get_json()["data"]
38
+
39
+
40
+ def _fill(client, key, live):
41
+ ids = []
42
+ for i in range(live):
43
+ resp = _mint(client, key, {"label": f"k{i}"})
44
+ assert resp.status_code == 200, resp.get_json()
45
+ ids.append(resp.get_json()["data"]["key_id"])
46
+ return ids
47
+
48
+
49
+ def test_cap_refuses_once_full_of_unexpired_keys(client):
50
+ key = _namespace(client)
51
+ _fill(client, key, API_KEYS_PER_USER_CAP)
52
+ refused = _mint(client, key, {"label": "one-too-many"})
53
+ assert refused.status_code == 400
54
+ assert "limit reached" in refused.get_json()["message"]
55
+ assert _listing(client, key)["count"] == API_KEYS_PER_USER_CAP
56
+
57
+
58
+ def test_expired_key_frees_its_slot_exactly_at_expiry(client, monkeypatch):
59
+ key = _namespace(client)
60
+ _fill(client, key, API_KEYS_PER_USER_CAP - 1)
61
+ when = (_now() + timedelta(days=1)).replace(microsecond=0)
62
+ short = _mint(client, key, {"label": "short", "expires_at": when.isoformat()})
63
+ assert short.status_code == 200
64
+ short_id = short.get_json()["data"]["key_id"]
65
+
66
+ monkeypatch.setattr(keys_module, "_utcnow", lambda: when - timedelta(seconds=1))
67
+ before = _mint(client, key, {"label": "before-expiry"})
68
+ assert before.status_code == 400
69
+
70
+ monkeypatch.setattr(keys_module, "_utcnow", lambda: when)
71
+ after = _mint(client, key, {"label": "at-expiry"})
72
+ assert after.status_code == 200, after.get_json()
73
+
74
+ again = _mint(client, key, {"label": "cap-again"})
75
+ assert again.status_code == 400
76
+
77
+ listing = _listing(client, key)
78
+ assert listing["count"] == API_KEYS_PER_USER_CAP + 1
79
+ expired = next(k for k in listing["keys"] if k["key_id"] == short_id)
80
+ assert expired["is_active"] is True
81
+ assert expired["revoked_at"] is None
82
+ assert expired["expires_at"] == when.isoformat()
83
+
84
+
85
+ def test_revoked_key_still_frees_its_slot(client):
86
+ key = _namespace(client)
87
+ ids = _fill(client, key, API_KEYS_PER_USER_CAP)
88
+ assert _mint(client, key).status_code == 400
89
+ revoked = client.delete(f"/api/apikeys/user/svc/{ids[0]}", headers=_h(key))
90
+ assert revoked.get_json()["data"] == {"revoked": True, "already_revoked": False}
91
+ assert _mint(client, key).status_code == 200
92
+ assert _mint(client, key).status_code == 400
93
+
94
+
95
+ def test_other_users_expired_keys_do_not_free_this_users_slots(client, monkeypatch):
96
+ key = _namespace(client)
97
+ when = (_now() + timedelta(days=1)).replace(microsecond=0)
98
+ other = _mint(client, key, {"expires_at": when.isoformat()}, user="other")
99
+ assert other.status_code == 200
100
+ _fill(client, key, API_KEYS_PER_USER_CAP)
101
+ monkeypatch.setattr(keys_module, "_utcnow", lambda: when)
102
+ assert _mint(client, key).status_code == 400
@@ -0,0 +1,90 @@
1
+ import uuid
2
+
3
+ import pytest
4
+
5
+ from auth.config import get_settings
6
+ from auth.main import create_app
7
+
8
+
9
+ @pytest.fixture(autouse=True)
10
+ def production_default(monkeypatch):
11
+ monkeypatch.setattr(get_settings(), "strict_users_default", True)
12
+
13
+
14
+ @pytest.fixture
15
+ def client():
16
+ application = create_app()
17
+ application.config["TESTING"] = True
18
+ return application.test_client()
19
+
20
+
21
+ def _h(key):
22
+ return {"Authorization": f"Bearer {key}"}
23
+
24
+
25
+ def _strict(client, key):
26
+ return client.get("/api/settings", headers=_h(key)).get_json()["data"]["strict_users"]
27
+
28
+
29
+ def _rotate_key(client, key):
30
+ response = client.post("/api/keys/get_rotate_key", headers=_h(key))
31
+ assert response.status_code == 200
32
+ return response.get_json()["data"]["rotate_key"]
33
+
34
+
35
+ def _updates(client, key):
36
+ return client.get("/api/audit?action=UPDATE_SETTINGS", headers=_h(key)).get_json()["data"]["total"]
37
+
38
+
39
+ def test_fetching_the_rotate_key_keeps_a_default_strict_namespace_strict(client):
40
+ key = str(uuid.uuid4())
41
+ client.post("/api/role/viewer", headers=_h(key))
42
+ assert _strict(client, key) is True
43
+ _rotate_key(client, key)
44
+ assert _strict(client, key) is True
45
+ refused = client.post("/api/membership/nokey/viewer", headers=_h(key))
46
+ assert refused.status_code == 409
47
+ assert refused.get_json()["reason"] == "user_not_key_backed"
48
+ assert _updates(client, key) == 0
49
+
50
+
51
+ def test_fetching_the_rotate_key_keeps_an_opted_out_namespace_non_strict(client):
52
+ key = str(uuid.uuid4())
53
+ client.put("/api/settings", json={"strict_users": False}, headers=_h(key))
54
+ _rotate_key(client, key)
55
+ assert _strict(client, key) is False
56
+
57
+
58
+ def test_the_row_follows_the_configured_default(client, monkeypatch):
59
+ monkeypatch.setattr(get_settings(), "strict_users_default", False)
60
+ key = str(uuid.uuid4())
61
+ _rotate_key(client, key)
62
+ monkeypatch.setattr(get_settings(), "strict_users_default", True)
63
+ assert _strict(client, key) is False
64
+
65
+
66
+ def test_recovery_keeps_the_namespace_strict(client):
67
+ key = str(uuid.uuid4())
68
+ client.post("/api/role/viewer", headers=_h(key))
69
+ secret = _rotate_key(client, key)
70
+ new_key = str(uuid.uuid4())
71
+ recovered = client.post(
72
+ "/api/keys/recover", json={"rotate_key": secret, "new_client_key": new_key}
73
+ )
74
+ assert recovered.status_code == 200
75
+ assert _strict(client, new_key) is True
76
+ assert client.post("/api/membership/nokey/viewer", headers=_h(new_key)).status_code == 409
77
+
78
+
79
+ def test_rotate_key_audit_records_the_strict_value(client):
80
+ key = str(uuid.uuid4())
81
+ _rotate_key(client, key)
82
+ client.post("/api/keys/get_rotate_key", headers=_h(key))
83
+ entries = client.get(
84
+ "/api/audit?action=GET_ROTATE_KEY", headers=_h(key)
85
+ ).get_json()["data"]["entries"]
86
+ second, first = entries[0], entries[1]
87
+ assert first["details"]["strict_users"] is True
88
+ assert first["details"]["settings_row_created"] is True
89
+ assert second["details"]["strict_users"] is True
90
+ assert second["details"]["settings_row_created"] is False
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes