auth 3.6.0__tar.gz → 3.7.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.
- {auth-3.6.0 → auth-3.7.1}/PKG-INFO +1 -1
- {auth-3.6.0 → auth-3.7.1}/auth/__init__.py +9 -2
- {auth-3.6.0 → auth-3.7.1}/auth/audit.py +1 -0
- {auth-3.6.0 → auth-3.7.1}/auth/client/keys.py +35 -4
- {auth-3.6.0 → auth-3.7.1}/auth/decorators.py +14 -1
- auth-3.7.1/auth/key_expiry.py +39 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/apikeys.py +72 -4
- {auth-3.6.0 → auth-3.7.1}/auth/routes/tenant.py +2 -1
- {auth-3.6.0 → auth-3.7.1}/auth/services/base.py +2 -1
- {auth-3.6.0 → auth-3.7.1}/auth/services/keys.py +51 -10
- {auth-3.6.0 → auth-3.7.1}/auth/services/recovery.py +3 -1
- {auth-3.6.0 → auth-3.7.1}/auth/services/tenant.py +15 -4
- {auth-3.6.0 → auth-3.7.1}/auth/static_docs/api_reference.md +14 -4
- {auth-3.6.0 → auth-3.7.1}/auth.egg-info/PKG-INFO +1 -1
- {auth-3.6.0 → auth-3.7.1}/auth.egg-info/SOURCES.txt +4 -0
- {auth-3.6.0 → auth-3.7.1}/pyproject.toml +1 -1
- auth-3.7.1/tests/test_apikey_audit_outcome.py +134 -0
- auth-3.7.1/tests/test_apikey_expiry.py +231 -0
- auth-3.7.1/tests/test_rotate_key_preserves_strict.py +90 -0
- {auth-3.6.0 → auth-3.7.1}/LICENSE +0 -0
- {auth-3.6.0 → auth-3.7.1}/README.md +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/api_keys.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/circuit_breaker.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/client/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/client/_transport.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/client/base.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/client/rbac.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/client/workflow.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/cmd/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/cmd/server.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/config.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/core/REST/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/core/REST/client.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/core/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/core/models/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/database.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/docs_page.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/encryption.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/keycheck.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/logging_config.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/main.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrate.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01KYTMDEYFVH43HKR0MQWW1EMP_add_auth_api_key.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01KYTQN79R1ZBNDPA3ND9AAA73_drop_alembic_version.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01KYTRKMWNBDDZPN1H0AXRTT5G_add_auth_tenant_settings.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01KYTX0MKVZ775P62CJ87631Z1_grandfather_strict_users.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01KZJWHG32K9X1AFBPPB4YJC6A_partition_audit_log.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01M2Y4SMRCS9PW29AA0TFCVXKR_add_creator_fp_and_rotate_key.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01M2Y4YA6RY6DZWT235CDV9H5W_enable_row_level_security.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01M2Y8WEM8SYB1SG8QD35S3T6M_add_encryption_canary.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01M2Y9AYF2B7WM3AHMGX14AWWJ_rls_on_new_audit_partitions.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01M2Y9FNKBJ513W0XVCYFYPDR9_drop_stale_public_tables.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01M2Y9WFEY32ZWDP161SHR1B2M_add_apply_tenant_rls_function.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/01M2Z040JTSGF3V0AQMP583BDA_create_audit_log_partitioned_if_absent.sql +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/migrations/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/models/sql.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/response_format.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/rls.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/_common.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/membership.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/permissions.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/public.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/roles.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/routes/workflow.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/sanitizer.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/schema_check.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/schema_reconcile.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/server.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/services/queries.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/services/rbac.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/services/rotation.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/services/service.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/static_docs/__init__.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/static_docs/claude_guide.md +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/static_docs/landing.md +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/static_docs/page.html +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/validation.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth/workflow_checker.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth.egg-info/dependency_links.txt +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth.egg-info/entry_points.txt +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth.egg-info/requires.txt +0 -0
- {auth-3.6.0 → auth-3.7.1}/auth.egg-info/top_level.txt +0 -0
- {auth-3.6.0 → auth-3.7.1}/setup.cfg +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_api_keys.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_api_keys_encryption.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_audit_integrity.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_client.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_client_exceptions_do_not_render_payload.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_client_rest.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_cmd_server.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_config.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_correctness_hardening.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_database_pool_settings.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_database_sslmode.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_degraded_response_is_a_contract.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_deploy_lock.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_docs_page.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_encryption.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_encryption_integration.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_flask.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_gunicorn_config_invariants.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_import_footprint.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_key_rotation.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_log_redaction.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_migrate_cli.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_no_bundled_libpq.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_phase_a_hardening.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_provision_script_no_dsn_leak.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_reencryption.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_routes_errors.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_schema_check.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_self_service_audit.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_served_docs_host.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_server.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_service_lifecycle.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_settings_do_not_echo_secrets.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_strict_default.py +0 -0
- {auth-3.6.0 → auth-3.7.1}/tests/test_strict_users.py +0 -0
|
@@ -4,6 +4,7 @@ from importlib.metadata import PackageNotFoundError, version
|
|
|
4
4
|
from typing import TYPE_CHECKING, Optional
|
|
5
5
|
|
|
6
6
|
from auth.database import SessionLocal
|
|
7
|
+
from auth.key_expiry import parse_expiry
|
|
7
8
|
from auth.schema_check import SchemaMismatchError, check_schema
|
|
8
9
|
from auth.services.service import AuthorizationService
|
|
9
10
|
|
|
@@ -150,8 +151,14 @@ class Authorization:
|
|
|
150
151
|
return self.service.set_strict_users(enabled)
|
|
151
152
|
|
|
152
153
|
# Per-user API keys (SPEC 0004)
|
|
153
|
-
def create_api_key(
|
|
154
|
-
|
|
154
|
+
def create_api_key(
|
|
155
|
+
self, user: str, label: Optional[str] = None, expires_at: Optional[str] = None
|
|
156
|
+
):
|
|
157
|
+
expiry = parse_expiry(expires_at) if expires_at is not None else None
|
|
158
|
+
return self.service.create_api_key(user, label, expiry)
|
|
159
|
+
|
|
160
|
+
def set_api_key_expiry(self, user: str, key_id: str, expires_at: str):
|
|
161
|
+
return self.service.set_api_key_expiry(user, key_id, parse_expiry(expires_at))
|
|
155
162
|
|
|
156
163
|
def list_api_keys(self, user: str):
|
|
157
164
|
return self.service.list_api_keys(user)
|
|
@@ -41,6 +41,7 @@ class AuditAction(Enum):
|
|
|
41
41
|
CREATE_API_KEY = "CREATE_API_KEY"
|
|
42
42
|
LIST_API_KEYS = "LIST_API_KEYS"
|
|
43
43
|
REVOKE_API_KEY = "REVOKE_API_KEY"
|
|
44
|
+
UPDATE_API_KEY = "UPDATE_API_KEY"
|
|
44
45
|
VALIDATE_API_KEY = "VALIDATE_API_KEY"
|
|
45
46
|
CHECK_API_KEY_PERMISSION = "CHECK_API_KEY_PERMISSION"
|
|
46
47
|
GET_SETTINGS = "GET_SETTINGS"
|
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
"""Client key rotation, per-user API keys, and tenant settings."""
|
|
2
2
|
|
|
3
|
-
from
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Any, Dict, Optional, Union
|
|
4
5
|
|
|
5
6
|
from auth.client.rbac import RbacMixin
|
|
6
7
|
|
|
7
8
|
|
|
9
|
+
def _iso(value: Union[str, datetime]) -> str:
|
|
10
|
+
if isinstance(value, datetime):
|
|
11
|
+
if value.tzinfo is not None:
|
|
12
|
+
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
|
13
|
+
return value.isoformat()
|
|
14
|
+
return value
|
|
15
|
+
|
|
16
|
+
|
|
8
17
|
class ApiKeyMixin(RbacMixin):
|
|
9
18
|
"""Key rotation, per-user API keys and tenant settings."""
|
|
10
19
|
|
|
@@ -34,7 +43,12 @@ class ApiKeyMixin(RbacMixin):
|
|
|
34
43
|
return response
|
|
35
44
|
|
|
36
45
|
# Per-user API keys (SPEC 0004)
|
|
37
|
-
def create_api_key(
|
|
46
|
+
def create_api_key(
|
|
47
|
+
self,
|
|
48
|
+
user: str,
|
|
49
|
+
label: Optional[str] = None,
|
|
50
|
+
expires_at: Optional[Union[str, datetime]] = None,
|
|
51
|
+
) -> Dict[str, Any]:
|
|
38
52
|
"""Mint an API key for a user; ``data.api_key`` is shown only once.
|
|
39
53
|
|
|
40
54
|
Sent WITHOUT automatic retries: create is not idempotent, and a blind
|
|
@@ -45,12 +59,29 @@ class ApiKeyMixin(RbacMixin):
|
|
|
45
59
|
your unavailable/503 path, never to a denial.
|
|
46
60
|
"""
|
|
47
61
|
endpoint = self.endpoints["apikeys_user"].format(user=user)
|
|
48
|
-
|
|
62
|
+
body: Dict[str, Any] = {}
|
|
63
|
+
if label is not None:
|
|
64
|
+
body["label"] = label
|
|
65
|
+
if expires_at is not None:
|
|
66
|
+
body["expires_at"] = _iso(expires_at)
|
|
49
67
|
try:
|
|
50
|
-
return self._make_request(
|
|
68
|
+
return self._make_request(
|
|
69
|
+
"POST", endpoint, retry=False, json=body or None
|
|
70
|
+
)
|
|
51
71
|
except Exception as e:
|
|
52
72
|
return self._transport_failure(e, data={"user": user, "label": label})
|
|
53
73
|
|
|
74
|
+
def set_api_key_expiry(
|
|
75
|
+
self, user: str, key_id: str, expires_at: Union[str, datetime]
|
|
76
|
+
) -> Dict[str, Any]:
|
|
77
|
+
endpoint = self.endpoints["apikey_revoke"].format(user=user, key_id=key_id)
|
|
78
|
+
try:
|
|
79
|
+
return self._make_request(
|
|
80
|
+
"PATCH", endpoint, json={"expires_at": _iso(expires_at)}
|
|
81
|
+
)
|
|
82
|
+
except Exception as e:
|
|
83
|
+
return self._transport_failure(e, data={"user": user, "key_id": key_id})
|
|
84
|
+
|
|
54
85
|
def list_api_keys(self, user: str) -> Dict[str, Any]:
|
|
55
86
|
"""List a user's API keys (metadata only; never the secrets).
|
|
56
87
|
|
|
@@ -11,6 +11,12 @@ from auth.audit import (
|
|
|
11
11
|
)
|
|
12
12
|
from auth.config import get_settings
|
|
13
13
|
|
|
14
|
+
AUDIT_OUTCOME = "audit_outcome"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def record_outcome(**facts: Any) -> None:
|
|
18
|
+
setattr(g, AUDIT_OUTCOME, facts)
|
|
19
|
+
|
|
14
20
|
|
|
15
21
|
def _status_code(response) -> int:
|
|
16
22
|
"""Best-effort HTTP status of a Flask view return value."""
|
|
@@ -101,6 +107,13 @@ def audit_log(action: AuditAction, resource_extractor=None):
|
|
|
101
107
|
|
|
102
108
|
status_code = _status_code(response)
|
|
103
109
|
success = _derive_success(response)
|
|
110
|
+
details: dict = {"status_code": status_code}
|
|
111
|
+
outcome = g.pop(AUDIT_OUTCOME, None)
|
|
112
|
+
if isinstance(outcome, dict):
|
|
113
|
+
resource = outcome.pop("resource", resource)
|
|
114
|
+
refused = outcome.pop("refused", False)
|
|
115
|
+
success = success and not refused
|
|
116
|
+
details.update(outcome)
|
|
104
117
|
# Stage the audit row on the SAME session as the mutation; the
|
|
105
118
|
# ``with_db_session`` wrapper commits both together. If this raises,
|
|
106
119
|
# the whole request fails closed rather than committing an unaudited
|
|
@@ -111,7 +124,7 @@ def audit_log(action: AuditAction, resource_extractor=None):
|
|
|
111
124
|
user=user,
|
|
112
125
|
action=action,
|
|
113
126
|
resource=resource,
|
|
114
|
-
details=
|
|
127
|
+
details=details,
|
|
115
128
|
ip_address=request.remote_addr,
|
|
116
129
|
user_agent=request.headers.get("User-Agent", ""),
|
|
117
130
|
success=success,
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from datetime import datetime, timedelta, timezone
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
MAX_KEY_LIFETIME = timedelta(days=365)
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class KeyExpiryError(ValueError):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_expiry(value: object) -> datetime:
|
|
12
|
+
if not isinstance(value, str) or not value.strip():
|
|
13
|
+
raise KeyExpiryError("expires_at must be an ISO-8601 date-time string")
|
|
14
|
+
text = value.strip()
|
|
15
|
+
if text.endswith(("Z", "z")):
|
|
16
|
+
text = text[:-1] + "+00:00"
|
|
17
|
+
try:
|
|
18
|
+
parsed = datetime.fromisoformat(text)
|
|
19
|
+
except ValueError:
|
|
20
|
+
raise KeyExpiryError(
|
|
21
|
+
f"expires_at is not an ISO-8601 date-time: {value!r}"
|
|
22
|
+
) from None
|
|
23
|
+
if parsed.tzinfo is not None:
|
|
24
|
+
parsed = parsed.astimezone(timezone.utc).replace(tzinfo=None)
|
|
25
|
+
return parsed
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def check_expiry(
|
|
29
|
+
expires_at: datetime, now: datetime, current: Optional[datetime] = None
|
|
30
|
+
) -> None:
|
|
31
|
+
if expires_at <= now:
|
|
32
|
+
raise KeyExpiryError("expires_at must be in the future")
|
|
33
|
+
if expires_at > now + MAX_KEY_LIFETIME:
|
|
34
|
+
raise KeyExpiryError("expires_at may be at most 365 days from now")
|
|
35
|
+
if current is not None and expires_at >= current:
|
|
36
|
+
raise KeyExpiryError(
|
|
37
|
+
"expires_at may only be moved earlier than the key's current expiry "
|
|
38
|
+
f"({current.isoformat()})"
|
|
39
|
+
)
|
|
@@ -9,7 +9,8 @@ from auth.audit import (
|
|
|
9
9
|
AuditAction,
|
|
10
10
|
client_fingerprint,
|
|
11
11
|
)
|
|
12
|
-
from auth.decorators import audit_log
|
|
12
|
+
from auth.decorators import audit_log, record_outcome
|
|
13
|
+
from auth.key_expiry import KeyExpiryError, parse_expiry
|
|
13
14
|
from auth.response_format import (
|
|
14
15
|
APIResponse,
|
|
15
16
|
)
|
|
@@ -27,6 +28,23 @@ from auth.validation import (
|
|
|
27
28
|
|
|
28
29
|
logger = logging.getLogger(__name__)
|
|
29
30
|
|
|
31
|
+
CREATE_FIELDS = frozenset({"label", "expires_at"})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _record_key_outcome(result, key_id, **extra):
|
|
35
|
+
facts = {
|
|
36
|
+
"resource": f"api_key:{key_id}" if key_id else "api_key",
|
|
37
|
+
"key_id": key_id,
|
|
38
|
+
"valid": bool(result.get("valid")),
|
|
39
|
+
"refused": not result.get("valid"),
|
|
40
|
+
**extra,
|
|
41
|
+
}
|
|
42
|
+
if "reason" in result:
|
|
43
|
+
facts["reason"] = result["reason"]
|
|
44
|
+
if "has_permission" in result:
|
|
45
|
+
facts["has_permission"] = bool(result["has_permission"])
|
|
46
|
+
record_outcome(**facts)
|
|
47
|
+
|
|
30
48
|
|
|
31
49
|
def register(app):
|
|
32
50
|
"""Register the apikeys routes on ``app``."""
|
|
@@ -51,12 +69,19 @@ def register(app):
|
|
|
51
69
|
return APIResponse.bad_request(f"Invalid user name: {user}")
|
|
52
70
|
|
|
53
71
|
label = None
|
|
72
|
+
expires_at = None
|
|
54
73
|
if request.get_data(cache=True):
|
|
55
74
|
body = request.get_json(silent=True, force=True)
|
|
56
75
|
if not isinstance(body, dict):
|
|
57
76
|
return APIResponse.bad_request(
|
|
58
77
|
"Request body, when present, must be a JSON object."
|
|
59
78
|
)
|
|
79
|
+
unknown = sorted(set(body) - CREATE_FIELDS)
|
|
80
|
+
if unknown:
|
|
81
|
+
return APIResponse.bad_request(
|
|
82
|
+
f"Unknown field(s) {', '.join(unknown)}; "
|
|
83
|
+
"the create body accepts only label and expires_at."
|
|
84
|
+
)
|
|
60
85
|
label = body.get("label")
|
|
61
86
|
if label is not None and (
|
|
62
87
|
not isinstance(label, str) or not validate_api_key_label(label)
|
|
@@ -65,14 +90,23 @@ def register(app):
|
|
|
65
90
|
"Invalid label: 1-64 characters of letters, digits, "
|
|
66
91
|
"space, underscore, dot, or hyphen."
|
|
67
92
|
)
|
|
93
|
+
if body.get("expires_at") is not None:
|
|
94
|
+
try:
|
|
95
|
+
expires_at = parse_expiry(body["expires_at"])
|
|
96
|
+
except KeyExpiryError as exc:
|
|
97
|
+
return APIResponse.bad_request(str(exc))
|
|
68
98
|
|
|
69
99
|
auth_service = _get_auth_service(db)
|
|
70
|
-
|
|
100
|
+
try:
|
|
101
|
+
result = auth_service.create_api_key(user, label, expires_at)
|
|
102
|
+
except KeyExpiryError as exc:
|
|
103
|
+
return APIResponse.bad_request(str(exc))
|
|
71
104
|
if result is None:
|
|
72
105
|
return APIResponse.bad_request(
|
|
73
106
|
f"Active API-key limit reached for user '{user}' "
|
|
74
107
|
f"({API_KEYS_PER_USER_CAP}). Revoke an existing key first."
|
|
75
108
|
)
|
|
109
|
+
record_outcome(key_id=result["key_id"], expires_at=result["expires_at"])
|
|
76
110
|
return APIResponse.success(
|
|
77
111
|
data=result,
|
|
78
112
|
message=(
|
|
@@ -136,6 +170,38 @@ def register(app):
|
|
|
136
170
|
message=f"API key {key_id} revoked for user '{user}'",
|
|
137
171
|
)
|
|
138
172
|
|
|
173
|
+
@app.route("/api/apikeys/user/<user>/<key_id>", methods=["PATCH"])
|
|
174
|
+
@with_db_session
|
|
175
|
+
@audit_log(
|
|
176
|
+
AuditAction.UPDATE_API_KEY,
|
|
177
|
+
resource_extractor=lambda kwargs: (
|
|
178
|
+
f"{client_fingerprint(kwargs['user'])}:{kwargs['key_id']}"
|
|
179
|
+
),
|
|
180
|
+
)
|
|
181
|
+
def update_user_api_key(db, user, key_id):
|
|
182
|
+
if not validate_user_name(user):
|
|
183
|
+
return APIResponse.bad_request(f"Invalid user name: {user}")
|
|
184
|
+
if not validate_key_id(key_id):
|
|
185
|
+
return APIResponse.bad_request(
|
|
186
|
+
f"Invalid key id: {key_id}. Must be a UUID4."
|
|
187
|
+
)
|
|
188
|
+
body = request.get_json(silent=True, force=True)
|
|
189
|
+
if not isinstance(body, dict) or set(body) != {"expires_at"}:
|
|
190
|
+
return APIResponse.bad_request(
|
|
191
|
+
'JSON body required: {"expires_at": "<ISO-8601 date-time>"}'
|
|
192
|
+
)
|
|
193
|
+
try:
|
|
194
|
+
expires_at = parse_expiry(body["expires_at"])
|
|
195
|
+
meta = _get_auth_service(db).set_api_key_expiry(user, key_id, expires_at)
|
|
196
|
+
except KeyExpiryError as exc:
|
|
197
|
+
return APIResponse.bad_request(str(exc))
|
|
198
|
+
if meta is None:
|
|
199
|
+
return APIResponse.not_found("API key", key_id)
|
|
200
|
+
record_outcome(key_id=meta["key_id"], expires_at=meta["expires_at"])
|
|
201
|
+
return APIResponse.success(
|
|
202
|
+
data=meta, message=f"API key {key_id} expiry set for user '{user}'"
|
|
203
|
+
)
|
|
204
|
+
|
|
139
205
|
@app.route("/api/apikeys/validate", methods=["POST"])
|
|
140
206
|
@with_db_session
|
|
141
207
|
@audit_log(
|
|
@@ -160,7 +226,8 @@ def register(app):
|
|
|
160
226
|
)
|
|
161
227
|
|
|
162
228
|
auth_service = _get_auth_service(db)
|
|
163
|
-
result = auth_service.
|
|
229
|
+
result, key_id = auth_service.resolve_api_key(api_key)
|
|
230
|
+
_record_key_outcome(result, key_id)
|
|
164
231
|
return APIResponse.success(data=result, message="API key validation completed")
|
|
165
232
|
|
|
166
233
|
@app.route("/api/apikeys/check_permission", methods=["POST"])
|
|
@@ -192,7 +259,8 @@ def register(app):
|
|
|
192
259
|
return APIResponse.bad_request(f"Invalid permission name: {permission!r}")
|
|
193
260
|
|
|
194
261
|
auth_service = _get_auth_service(db)
|
|
195
|
-
result = auth_service.
|
|
262
|
+
result, key_id = auth_service.resolve_api_key_permission(api_key, permission)
|
|
263
|
+
_record_key_outcome(result, key_id, permission=permission)
|
|
196
264
|
return APIResponse.success(
|
|
197
265
|
data=result, message="API-key permission check completed"
|
|
198
266
|
)
|
|
@@ -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
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"""Per-user API keys (SPEC 0004): minting, listing, revocation, validation."""
|
|
2
2
|
|
|
3
|
-
from
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Any, Dict, List, Optional, Tuple, cast
|
|
4
5
|
|
|
5
6
|
from sqlalchemy import func
|
|
6
7
|
|
|
7
8
|
from auth.api_keys import generate_api_key, hash_api_key
|
|
9
|
+
from auth.key_expiry import KeyExpiryError, check_expiry
|
|
8
10
|
from auth.models.sql import (
|
|
9
11
|
AuthApiKey,
|
|
10
12
|
)
|
|
@@ -31,16 +33,21 @@ class ApiKeyMixin(RbacMixin):
|
|
|
31
33
|
construction (this very key just validated), so strict mode never
|
|
32
34
|
blocks the second half.
|
|
33
35
|
"""
|
|
34
|
-
|
|
36
|
+
return self.resolve_api_key_permission(api_key, permission)[0]
|
|
37
|
+
|
|
38
|
+
def resolve_api_key_permission(
|
|
39
|
+
self, api_key: str, permission: str
|
|
40
|
+
) -> Tuple[Dict[str, Any], Optional[str]]:
|
|
41
|
+
validated, key_id = self.resolve_api_key(api_key)
|
|
35
42
|
if not validated["valid"]:
|
|
36
|
-
return validated
|
|
43
|
+
return validated, key_id
|
|
37
44
|
user = cast(str, validated["user"])
|
|
38
45
|
return {
|
|
39
46
|
"valid": True,
|
|
40
47
|
"user": user,
|
|
41
48
|
"key_id": validated["key_id"],
|
|
42
49
|
"has_permission": self.user_has_permission(user, permission),
|
|
43
|
-
}
|
|
50
|
+
}, key_id
|
|
44
51
|
|
|
45
52
|
# --- Per-user API keys (SPEC 0004) -----------------------------------
|
|
46
53
|
|
|
@@ -63,7 +70,10 @@ class ApiKeyMixin(RbacMixin):
|
|
|
63
70
|
}
|
|
64
71
|
|
|
65
72
|
def create_api_key(
|
|
66
|
-
self,
|
|
73
|
+
self,
|
|
74
|
+
user: str,
|
|
75
|
+
label: Optional[str] = None,
|
|
76
|
+
expires_at: Optional[datetime] = None,
|
|
67
77
|
) -> Optional[Dict[str, Any]]:
|
|
68
78
|
"""Mint and store an API key for ``user`` in this tenant's namespace.
|
|
69
79
|
|
|
@@ -72,6 +82,8 @@ class ApiKeyMixin(RbacMixin):
|
|
|
72
82
|
serializes against key rotation so the new row cannot strand under a
|
|
73
83
|
creator that is being moved.
|
|
74
84
|
"""
|
|
85
|
+
if expires_at is not None:
|
|
86
|
+
check_expiry(expires_at, _utcnow())
|
|
75
87
|
self._lock_tenant()
|
|
76
88
|
active = (
|
|
77
89
|
self.db.query(func.count(AuthApiKey.id))
|
|
@@ -97,6 +109,8 @@ class ApiKeyMixin(RbacMixin):
|
|
|
97
109
|
row.user = user
|
|
98
110
|
if label:
|
|
99
111
|
row.label = label
|
|
112
|
+
if expires_at is not None:
|
|
113
|
+
row.expires_at = expires_at # type: ignore[assignment]
|
|
100
114
|
self.db.add(row)
|
|
101
115
|
self.db.flush()
|
|
102
116
|
self._commit()
|
|
@@ -107,7 +121,7 @@ class ApiKeyMixin(RbacMixin):
|
|
|
107
121
|
"label": label,
|
|
108
122
|
"key_prefix": key_prefix,
|
|
109
123
|
"created": row.date_created.isoformat() if row.date_created else None,
|
|
110
|
-
"expires_at": None,
|
|
124
|
+
"expires_at": expires_at.isoformat() if expires_at else None,
|
|
111
125
|
}
|
|
112
126
|
|
|
113
127
|
def list_api_keys(self, user: str) -> List[Dict[str, Any]]:
|
|
@@ -149,6 +163,29 @@ class ApiKeyMixin(RbacMixin):
|
|
|
149
163
|
self._commit()
|
|
150
164
|
return "revoked"
|
|
151
165
|
|
|
166
|
+
def set_api_key_expiry(
|
|
167
|
+
self, user: str, key_id: str, expires_at: datetime
|
|
168
|
+
) -> Optional[Dict[str, Any]]:
|
|
169
|
+
self._lock_tenant()
|
|
170
|
+
row = (
|
|
171
|
+
self.db.query(AuthApiKey)
|
|
172
|
+
.filter(
|
|
173
|
+
AuthApiKey.creator == self.client,
|
|
174
|
+
AuthApiKey.key_id == key_id.lower(),
|
|
175
|
+
AuthApiKey._user == self._get_encrypted_user(user),
|
|
176
|
+
)
|
|
177
|
+
.first()
|
|
178
|
+
)
|
|
179
|
+
if row is None:
|
|
180
|
+
return None
|
|
181
|
+
if not row.is_active:
|
|
182
|
+
raise KeyExpiryError("the key is revoked")
|
|
183
|
+
current = cast(Optional[datetime], row.expires_at)
|
|
184
|
+
check_expiry(expires_at, _utcnow(), current)
|
|
185
|
+
row.expires_at = expires_at # type: ignore[assignment]
|
|
186
|
+
self._commit()
|
|
187
|
+
return self._api_key_meta(row)
|
|
188
|
+
|
|
152
189
|
def validate_api_key(self, api_key: str) -> Dict[str, Any]:
|
|
153
190
|
"""Resolve a presented secret within THIS tenant's namespace.
|
|
154
191
|
|
|
@@ -157,18 +194,22 @@ class ApiKeyMixin(RbacMixin):
|
|
|
157
194
|
foreign tenant cannot probe key existence. Touches ``last_used_at``
|
|
158
195
|
at most once per throttle window.
|
|
159
196
|
"""
|
|
197
|
+
return self.resolve_api_key(api_key)[0]
|
|
198
|
+
|
|
199
|
+
def resolve_api_key(self, api_key: str) -> Tuple[Dict[str, Any], Optional[str]]:
|
|
160
200
|
row = (
|
|
161
201
|
self.db.query(AuthApiKey)
|
|
162
202
|
.filter(AuthApiKey.key_hash == hash_api_key(api_key))
|
|
163
203
|
.first()
|
|
164
204
|
)
|
|
165
205
|
if row is None or row.creator != self.client:
|
|
166
|
-
return {"valid": False, "reason": "unknown_key"}
|
|
206
|
+
return {"valid": False, "reason": "unknown_key"}, None
|
|
207
|
+
key_id = cast(str, row.key_id)
|
|
167
208
|
if not row.is_active:
|
|
168
|
-
return {"valid": False, "reason": "revoked"}
|
|
209
|
+
return {"valid": False, "reason": "revoked"}, key_id
|
|
169
210
|
now = _utcnow()
|
|
170
211
|
if row.expires_at is not None and row.expires_at <= now:
|
|
171
|
-
return {"valid": False, "reason": "expired"}
|
|
212
|
+
return {"valid": False, "reason": "expired"}, key_id
|
|
172
213
|
if (
|
|
173
214
|
row.last_used_at is None
|
|
174
215
|
or (now - row.last_used_at).total_seconds() >= _LAST_USED_THROTTLE_SECONDS
|
|
@@ -181,4 +222,4 @@ class ApiKeyMixin(RbacMixin):
|
|
|
181
222
|
"key_id": row.key_id,
|
|
182
223
|
"label": row.label,
|
|
183
224
|
"expires_at": row.expires_at.isoformat() if row.expires_at else None,
|
|
184
|
-
}
|
|
225
|
+
}, key_id
|
|
@@ -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(
|
|
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
|
-
|
|
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(
|
|
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
|
|
|
@@ -267,11 +267,15 @@ 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
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.
|
|
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
|
|
272
|
+
passes, validate and check_permission answer `{{"valid": false, "reason":
|
|
273
|
+
"expired"}}`.
|
|
271
274
|
|
|
272
275
|
| Method | Path | Returns |
|
|
273
276
|
|---|---|---|
|
|
274
|
-
| POST | `/api/apikeys/user/<user>` | optional body `{{"label": "laptop"}}` → wrapped, `data` = `{{"api_key": "rak_<43 chars, shown ONCE>", "key_id": "<uuid4>", "user": "alice", "label": "laptop", "key_prefix": "rak_ab12cd34", "created": "<iso>", "expires_at": null}}` (400 once 25 active keys exist) |
|
|
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) |
|
|
278
|
+
| 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 |
|
|
275
279
|
| 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>"}}]}}` |
|
|
276
280
|
| 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) |
|
|
277
281
|
| POST | `/api/apikeys/validate` | body `{{"api_key": "rak_..."}}` → wrapped, `data` = `{{"valid": true, "user": "alice", "key_id": "<uuid4>", "label": "laptop", "expires_at": null}}` or `{{"valid": false, "reason": "revoked" | "expired" | "unknown_key"}}` |
|
|
@@ -295,6 +299,11 @@ when, and whether it took effect. Strictly scoped to the calling namespace's
|
|
|
295
299
|
fingerprint: it can never read another tenant's entries, and it never returns a
|
|
296
300
|
raw key or user (client/user fields are non-reversible fingerprints). Use it to
|
|
297
301
|
answer "why did my permission change / why was this denied?" without a human.
|
|
302
|
+
API-key entries carry the `key_id` in `details` when the key belongs to your
|
|
303
|
+
namespace (CREATE, UPDATE, REVOKE, VALIDATE, CHECK_API_KEY_PERMISSION), and
|
|
304
|
+
VALIDATE/CHECK entries record the outcome: `valid`, `reason`, and for checks
|
|
305
|
+
`permission` and `has_permission`. A refused key is recorded with `success:
|
|
306
|
+
false`. Neither the secret nor its hash is ever recorded.
|
|
298
307
|
|
|
299
308
|
| Method | Path | Returns |
|
|
300
309
|
|---|---|---|
|
|
@@ -361,8 +370,9 @@ Methods mirror the endpoints: `create_role`, `delete_role`, `list_roles`,
|
|
|
361
370
|
`get_user_permissions`, `get_role_permissions`, `get_user_roles`,
|
|
362
371
|
`get_role_members`, `which_roles_can`, `which_users_can`,
|
|
363
372
|
`get_users_for_workflow`, `rotate_key`, `ping`, the per-user key lifecycle
|
|
364
|
-
`create_api_key
|
|
365
|
-
`check_api_key_permission`, and tenant
|
|
373
|
+
`create_api_key` (optional `expires_at`), `set_api_key_expiry`, `list_api_keys`,
|
|
374
|
+
`revoke_api_key`, `validate_api_key`, `check_api_key_permission`, and tenant
|
|
375
|
+
settings `get_settings` /
|
|
366
376
|
`set_strict_users`.
|
|
367
377
|
Each returns the parsed JSON body, so the shapes in section 4 still apply.
|
|
368
378
|
`rotate_key()` also switches the live client (and its session header) to the new
|
|
@@ -10,6 +10,7 @@ auth/database.py
|
|
|
10
10
|
auth/decorators.py
|
|
11
11
|
auth/docs_page.py
|
|
12
12
|
auth/encryption.py
|
|
13
|
+
auth/key_expiry.py
|
|
13
14
|
auth/keycheck.py
|
|
14
15
|
auth/logging_config.py
|
|
15
16
|
auth/main.py
|
|
@@ -78,6 +79,8 @@ auth/static_docs/landing.md
|
|
|
78
79
|
auth/static_docs/page.html
|
|
79
80
|
tests/test_api_keys.py
|
|
80
81
|
tests/test_api_keys_encryption.py
|
|
82
|
+
tests/test_apikey_audit_outcome.py
|
|
83
|
+
tests/test_apikey_expiry.py
|
|
81
84
|
tests/test_audit_integrity.py
|
|
82
85
|
tests/test_client.py
|
|
83
86
|
tests/test_client_exceptions_do_not_render_payload.py
|
|
@@ -102,6 +105,7 @@ tests/test_no_bundled_libpq.py
|
|
|
102
105
|
tests/test_phase_a_hardening.py
|
|
103
106
|
tests/test_provision_script_no_dsn_leak.py
|
|
104
107
|
tests/test_reencryption.py
|
|
108
|
+
tests/test_rotate_key_preserves_strict.py
|
|
105
109
|
tests/test_routes_errors.py
|
|
106
110
|
tests/test_schema_check.py
|
|
107
111
|
tests/test_self_service_audit.py
|