auth 3.5.2__tar.gz → 3.7.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.
- {auth-3.5.2 → auth-3.7.0}/PKG-INFO +4 -4
- {auth-3.5.2 → auth-3.7.0}/README.md +3 -3
- {auth-3.5.2 → auth-3.7.0}/auth/__init__.py +9 -2
- {auth-3.5.2 → auth-3.7.0}/auth/audit.py +1 -0
- {auth-3.5.2 → auth-3.7.0}/auth/client/keys.py +35 -4
- {auth-3.5.2 → auth-3.7.0}/auth/decorators.py +14 -1
- auth-3.7.0/auth/key_expiry.py +39 -0
- {auth-3.5.2 → auth-3.7.0}/auth/keycheck.py +20 -3
- auth-3.7.0/auth/migrate.py +61 -0
- auth-3.7.0/auth/migrations/01KYTMDEYFVH43HKR0MQWW1EMP_add_auth_api_key.sql +41 -0
- auth-3.7.0/auth/migrations/01KYTQN79R1ZBNDPA3ND9AAA73_drop_alembic_version.sql +21 -0
- auth-3.7.0/auth/migrations/01KYTRKMWNBDDZPN1H0AXRTT5G_add_auth_tenant_settings.sql +26 -0
- auth-3.7.0/auth/migrations/01KYTX0MKVZ775P62CJ87631Z1_grandfather_strict_users.sql +85 -0
- auth-3.7.0/auth/migrations/01KZJWHG32K9X1AFBPPB4YJC6A_partition_audit_log.sql +279 -0
- auth-3.7.0/auth/migrations/01M2Y4SMRCS9PW29AA0TFCVXKR_add_creator_fp_and_rotate_key.sql +108 -0
- auth-3.7.0/auth/migrations/01M2Y4YA6RY6DZWT235CDV9H5W_enable_row_level_security.sql +180 -0
- auth-3.7.0/auth/migrations/01M2Y8WEM8SYB1SG8QD35S3T6M_add_encryption_canary.sql +40 -0
- auth-3.7.0/auth/migrations/01M2Y9AYF2B7WM3AHMGX14AWWJ_rls_on_new_audit_partitions.sql +108 -0
- auth-3.7.0/auth/migrations/01M2Y9FNKBJ513W0XVCYFYPDR9_drop_stale_public_tables.sql +104 -0
- auth-3.7.0/auth/migrations/01M2Y9WFEY32ZWDP161SHR1B2M_add_apply_tenant_rls_function.sql +166 -0
- auth-3.7.0/auth/migrations/01M2Z040JTSGF3V0AQMP583BDA_create_audit_log_partitioned_if_absent.sql +117 -0
- auth-3.7.0/auth/migrations/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/apikeys.py +72 -4
- {auth-3.5.2 → auth-3.7.0}/auth/services/keys.py +51 -10
- {auth-3.5.2 → auth-3.7.0}/auth/static_docs/api_reference.md +47 -14
- {auth-3.5.2 → auth-3.7.0}/auth/static_docs/claude_guide.md +5 -4
- {auth-3.5.2 → auth-3.7.0}/auth/static_docs/landing.md +2 -2
- {auth-3.5.2 → auth-3.7.0}/auth.egg-info/PKG-INFO +4 -4
- {auth-3.5.2 → auth-3.7.0}/auth.egg-info/SOURCES.txt +19 -0
- {auth-3.5.2 → auth-3.7.0}/auth.egg-info/entry_points.txt +1 -0
- {auth-3.5.2 → auth-3.7.0}/pyproject.toml +3 -1
- auth-3.7.0/tests/test_apikey_audit_outcome.py +134 -0
- auth-3.7.0/tests/test_apikey_expiry.py +231 -0
- auth-3.7.0/tests/test_migrate_cli.py +104 -0
- auth-3.7.0/tests/test_served_docs_host.py +49 -0
- {auth-3.5.2 → auth-3.7.0}/LICENSE +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/api_keys.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/circuit_breaker.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/client/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/client/_transport.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/client/base.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/client/rbac.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/client/workflow.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/cmd/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/cmd/server.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/config.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/core/REST/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/core/REST/client.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/core/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/core/models/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/database.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/docs_page.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/encryption.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/logging_config.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/main.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/models/sql.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/response_format.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/rls.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/_common.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/membership.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/permissions.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/public.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/roles.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/tenant.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/routes/workflow.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/sanitizer.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/schema_check.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/schema_reconcile.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/server.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/services/base.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/services/queries.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/services/rbac.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/services/recovery.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/services/rotation.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/services/service.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/services/tenant.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/static_docs/__init__.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/static_docs/page.html +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/validation.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth/workflow_checker.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth.egg-info/dependency_links.txt +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth.egg-info/requires.txt +0 -0
- {auth-3.5.2 → auth-3.7.0}/auth.egg-info/top_level.txt +0 -0
- {auth-3.5.2 → auth-3.7.0}/setup.cfg +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_api_keys.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_api_keys_encryption.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_audit_integrity.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_client.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_client_exceptions_do_not_render_payload.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_client_rest.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_cmd_server.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_config.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_correctness_hardening.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_database_pool_settings.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_database_sslmode.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_degraded_response_is_a_contract.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_deploy_lock.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_docs_page.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_encryption.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_encryption_integration.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_flask.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_gunicorn_config_invariants.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_import_footprint.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_key_rotation.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_log_redaction.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_no_bundled_libpq.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_phase_a_hardening.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_provision_script_no_dsn_leak.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_reencryption.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_routes_errors.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_schema_check.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_self_service_audit.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_server.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_service_lifecycle.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_settings_do_not_echo_secrets.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_strict_default.py +0 -0
- {auth-3.5.2 → auth-3.7.0}/tests/test_strict_users.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: auth
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.7.0
|
|
4
4
|
Summary: Authorization for humans
|
|
5
5
|
Author-email: Farshid Ashouri <farsheed.ashouri@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -82,7 +82,7 @@ before you add members or permissions to it.
|
|
|
82
82
|
|
|
83
83
|
```bash
|
|
84
84
|
KEY=$(python3 -c "import uuid; print(uuid.uuid4())")
|
|
85
|
-
BASE=https://auth.rodmena.
|
|
85
|
+
BASE=https://auth.rodmena.com
|
|
86
86
|
|
|
87
87
|
curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/role/engineers
|
|
88
88
|
curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/permission/engineers/deploy
|
|
@@ -117,7 +117,7 @@ With the Python client (`pip install auth`):
|
|
|
117
117
|
```python
|
|
118
118
|
from auth import Client
|
|
119
119
|
|
|
120
|
-
with Client(api_key=KEY, service_url="https://auth.rodmena.
|
|
120
|
+
with Client(api_key=KEY, service_url="https://auth.rodmena.com") as c:
|
|
121
121
|
c.create_role("engineers")
|
|
122
122
|
c.add_permission("engineers", "deploy")
|
|
123
123
|
c.create_api_key("alice") # strict default since 3.0.0
|
|
@@ -163,7 +163,7 @@ with Client(api_key=KEY, service_url="https://auth.rodmena.app") as c:
|
|
|
163
163
|
|
|
164
164
|
| Doc | What's in it |
|
|
165
165
|
|---|---|
|
|
166
|
-
| **Live API reference** — [`/docs`](https://auth.rodmena.
|
|
166
|
+
| **Live API reference** — [`/docs`](https://auth.rodmena.com/docs) · [`/llms.txt`](https://auth.rodmena.com/llms.txt) | Every endpoint and exact response shape, served by the app (agent-friendly). |
|
|
167
167
|
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Design, components, request lifecycle, data model, permission-check and key-rotation flows, diagrams. |
|
|
168
168
|
| [SECURITY.md](SECURITY.md) | Security model (tenant isolation, encryption, audit, rotation), threat notes, reporting. |
|
|
169
169
|
| [MIGRATIONS.md](MIGRATIONS.md) | Schema creation vs migrations, upgrade/rollback runbook. |
|
|
@@ -20,7 +20,7 @@ before you add members or permissions to it.
|
|
|
20
20
|
|
|
21
21
|
```bash
|
|
22
22
|
KEY=$(python3 -c "import uuid; print(uuid.uuid4())")
|
|
23
|
-
BASE=https://auth.rodmena.
|
|
23
|
+
BASE=https://auth.rodmena.com
|
|
24
24
|
|
|
25
25
|
curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/role/engineers
|
|
26
26
|
curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/permission/engineers/deploy
|
|
@@ -55,7 +55,7 @@ With the Python client (`pip install auth`):
|
|
|
55
55
|
```python
|
|
56
56
|
from auth import Client
|
|
57
57
|
|
|
58
|
-
with Client(api_key=KEY, service_url="https://auth.rodmena.
|
|
58
|
+
with Client(api_key=KEY, service_url="https://auth.rodmena.com") as c:
|
|
59
59
|
c.create_role("engineers")
|
|
60
60
|
c.add_permission("engineers", "deploy")
|
|
61
61
|
c.create_api_key("alice") # strict default since 3.0.0
|
|
@@ -101,7 +101,7 @@ with Client(api_key=KEY, service_url="https://auth.rodmena.app") as c:
|
|
|
101
101
|
|
|
102
102
|
| Doc | What's in it |
|
|
103
103
|
|---|---|
|
|
104
|
-
| **Live API reference** — [`/docs`](https://auth.rodmena.
|
|
104
|
+
| **Live API reference** — [`/docs`](https://auth.rodmena.com/docs) · [`/llms.txt`](https://auth.rodmena.com/llms.txt) | Every endpoint and exact response shape, served by the app (agent-friendly). |
|
|
105
105
|
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Design, components, request lifecycle, data model, permission-check and key-rotation flows, diagrams. |
|
|
106
106
|
| [SECURITY.md](SECURITY.md) | Security model (tenant isolation, encryption, audit, rotation), threat notes, reporting. |
|
|
107
107
|
| [MIGRATIONS.md](MIGRATIONS.md) | Schema creation vs migrations, upgrade/rollback runbook. |
|
|
@@ -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
|
+
)
|
|
@@ -164,6 +164,18 @@ def verify_encryption_key(db) -> str:
|
|
|
164
164
|
return _set(OK, "encryption key verified against the deployment canary")
|
|
165
165
|
|
|
166
166
|
|
|
167
|
+
RLS_SCHEMA = "auth_rbac"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _schema_hint(schema: str) -> str:
|
|
171
|
+
if schema == RLS_SCHEMA:
|
|
172
|
+
return ""
|
|
173
|
+
return (
|
|
174
|
+
f" (AUTH_DATABASE_SCHEMA is {schema!r}; auth's migrations and row level"
|
|
175
|
+
f" security are defined in schema {RLS_SCHEMA!r})"
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
167
179
|
def verify_row_level_security(db) -> str:
|
|
168
180
|
"""Confirm RLS is actually in force, not merely enabled.
|
|
169
181
|
|
|
@@ -198,7 +210,10 @@ def verify_row_level_security(db) -> str:
|
|
|
198
210
|
return _set(UNVERIFIED, f"could not read RLS state: {exc.__class__.__name__}")
|
|
199
211
|
|
|
200
212
|
if not rows:
|
|
201
|
-
return _set(
|
|
213
|
+
return _set(
|
|
214
|
+
UNVERIFIED,
|
|
215
|
+
"no tenant tables found to check RLS on" + _schema_hint(schema),
|
|
216
|
+
)
|
|
202
217
|
|
|
203
218
|
# A table that is absent is not a table that is safe. The junction tables
|
|
204
219
|
# are created by the ORM rather than by a migration, so on a fresh database
|
|
@@ -210,7 +225,8 @@ def verify_row_level_security(db) -> str:
|
|
|
210
225
|
return _set(
|
|
211
226
|
MISMATCH,
|
|
212
227
|
"expected tenant tables are absent, so nothing protects them: "
|
|
213
|
-
+ ", ".join(missing)
|
|
228
|
+
+ ", ".join(missing)
|
|
229
|
+
+ _schema_hint(schema),
|
|
214
230
|
)
|
|
215
231
|
|
|
216
232
|
unprotected = [
|
|
@@ -221,7 +237,8 @@ def verify_row_level_security(db) -> str:
|
|
|
221
237
|
MISMATCH,
|
|
222
238
|
"row level security is not in force on: "
|
|
223
239
|
+ ", ".join(sorted(unprotected))
|
|
224
|
-
+ " - tenant isolation would rest on query convention alone"
|
|
240
|
+
+ " - tenant isolation would rest on query convention alone"
|
|
241
|
+
+ _schema_hint(schema),
|
|
225
242
|
)
|
|
226
243
|
return _set(OK, f"row level security forced on {len(rows)} tables")
|
|
227
244
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import List, Mapping, Optional
|
|
7
|
+
|
|
8
|
+
COMMANDS = ("apply", "status", "verify", "head", "list")
|
|
9
|
+
URL_VARIABLES = ("MG_DATABASE_URL", "AUTH_DATABASE_URL", "AUTH_POSTGRESQL_URL")
|
|
10
|
+
DRIVER_PREFIXES = ("postgresql+psycopg://", "postgres+psycopg://")
|
|
11
|
+
USAGE = (
|
|
12
|
+
"usage: auth-migrate {apply,status,verify,head,list} [migretti options]\n"
|
|
13
|
+
"Runs the migrations shipped with this auth release against the database "
|
|
14
|
+
"named by the first of MG_DATABASE_URL, AUTH_DATABASE_URL or "
|
|
15
|
+
"AUTH_POSTGRESQL_URL that is set."
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def migrations_root() -> Path:
|
|
20
|
+
return Path(__file__).resolve().parent
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def database_url(environ: Mapping[str, str]) -> Optional[str]:
|
|
24
|
+
for name in URL_VARIABLES:
|
|
25
|
+
value = environ.get(name, "").strip()
|
|
26
|
+
if not value:
|
|
27
|
+
continue
|
|
28
|
+
for prefix in DRIVER_PREFIXES:
|
|
29
|
+
if value.startswith(prefix):
|
|
30
|
+
return "postgresql://" + value[len(prefix) :]
|
|
31
|
+
return value
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _refuse(message: str) -> int:
|
|
36
|
+
print(f"auth-migrate: {message}", file=sys.stderr)
|
|
37
|
+
return 2
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
41
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
42
|
+
if not args or args[0] not in COMMANDS:
|
|
43
|
+
print(USAGE, file=sys.stderr)
|
|
44
|
+
return 2
|
|
45
|
+
if importlib.util.find_spec("migretti") is None:
|
|
46
|
+
return _refuse('migretti is not installed; install "auth[migrations]"')
|
|
47
|
+
url = database_url(os.environ)
|
|
48
|
+
if url is None:
|
|
49
|
+
return _refuse("set MG_DATABASE_URL, AUTH_DATABASE_URL or AUTH_POSTGRESQL_URL")
|
|
50
|
+
if not url.startswith(("postgresql://", "postgres://")):
|
|
51
|
+
return _refuse("the shipped migrations target PostgreSQL only")
|
|
52
|
+
environment = dict(os.environ, MG_DATABASE_URL=url)
|
|
53
|
+
return subprocess.call(
|
|
54
|
+
[sys.executable, "-m", "migretti", *args],
|
|
55
|
+
cwd=migrations_root(),
|
|
56
|
+
env=environment,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
sys.exit(main())
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
-- migration: add_auth_api_key
|
|
2
|
+
-- id: 01KYTMDEYFVH43HKR0MQWW1EMP
|
|
3
|
+
--
|
|
4
|
+
-- Per-user API-key registry (SPEC 0004, issuedb #9). Mirrors the SQLAlchemy
|
|
5
|
+
-- model auth.models.sql.AuthApiKey exactly — the app's boot-time
|
|
6
|
+
-- create_all(checkfirst=True) may legally create this table first on a fresh
|
|
7
|
+
-- install, so every statement is IF NOT EXISTS and the two DDL paths converge
|
|
8
|
+
-- in either order. Schema is the production/CI deployment schema (auth_rbac,
|
|
9
|
+
-- AUTH_DATABASE_SCHEMA); schemaless SQLite/dev installs are covered by
|
|
10
|
+
-- create_all and never run migretti.
|
|
11
|
+
|
|
12
|
+
-- migrate: up
|
|
13
|
+
CREATE SCHEMA IF NOT EXISTS auth_rbac;
|
|
14
|
+
|
|
15
|
+
CREATE TABLE IF NOT EXISTS auth_rbac.auth_api_key (
|
|
16
|
+
id SERIAL PRIMARY KEY,
|
|
17
|
+
key_id VARCHAR(36) NOT NULL,
|
|
18
|
+
creator VARCHAR(64) NOT NULL,
|
|
19
|
+
"user" TEXT NOT NULL,
|
|
20
|
+
key_hash VARCHAR(64) NOT NULL,
|
|
21
|
+
key_prefix VARCHAR(16) NOT NULL,
|
|
22
|
+
label TEXT,
|
|
23
|
+
is_active BOOLEAN DEFAULT TRUE,
|
|
24
|
+
date_created TIMESTAMP DEFAULT now(),
|
|
25
|
+
modified TIMESTAMP DEFAULT now(),
|
|
26
|
+
revoked_at TIMESTAMP,
|
|
27
|
+
expires_at TIMESTAMP,
|
|
28
|
+
last_used_at TIMESTAMP,
|
|
29
|
+
CONSTRAINT uq_auth_api_key_key_hash UNIQUE (key_hash),
|
|
30
|
+
CONSTRAINT uq_auth_api_key_key_id UNIQUE (key_id)
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_api_key_id
|
|
34
|
+
ON auth_rbac.auth_api_key (id);
|
|
35
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_api_key_creator
|
|
36
|
+
ON auth_rbac.auth_api_key (creator);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS ix_auth_api_key_creator_user
|
|
38
|
+
ON auth_rbac.auth_api_key (creator, "user");
|
|
39
|
+
|
|
40
|
+
-- migrate: down
|
|
41
|
+
DROP TABLE IF EXISTS auth_rbac.auth_api_key;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
-- migration: drop_alembic_version
|
|
2
|
+
-- id: 01KYTQN79R1ZBNDPA3ND9AAA73
|
|
3
|
+
--
|
|
4
|
+
-- Alembic is fully purged (issuedb #14, SPEC 0009): migretti owns all
|
|
5
|
+
-- tracking, so the legacy alembic_version table goes. Its single recorded
|
|
6
|
+
-- revision was 0001_widen_text (varchar->TEXT widening, applied 2026-07);
|
|
7
|
+
-- the revision source now lives in git history only. The down section
|
|
8
|
+
-- faithfully restores the table and its one row. On databases that never ran
|
|
9
|
+
-- Alembic (fresh installs, CI) the up is a no-op.
|
|
10
|
+
|
|
11
|
+
-- migrate: up
|
|
12
|
+
DROP TABLE IF EXISTS auth_rbac.alembic_version;
|
|
13
|
+
|
|
14
|
+
-- migrate: down
|
|
15
|
+
CREATE TABLE IF NOT EXISTS auth_rbac.alembic_version (
|
|
16
|
+
version_num VARCHAR(32) NOT NULL,
|
|
17
|
+
CONSTRAINT alembic_version_pkc PRIMARY KEY (version_num)
|
|
18
|
+
);
|
|
19
|
+
INSERT INTO auth_rbac.alembic_version (version_num)
|
|
20
|
+
VALUES ('0001_widen_text')
|
|
21
|
+
ON CONFLICT DO NOTHING;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
-- migration: add_auth_tenant_settings
|
|
2
|
+
-- id: 01KYTRKMWNBDDZPN1H0AXRTT5G
|
|
3
|
+
--
|
|
4
|
+
-- Per-tenant settings (SPEC 0010, issuedb #15) — one row per creator, absence
|
|
5
|
+
-- means defaults. strict_users gates SPEC 0008 strict user identity (opt-in
|
|
6
|
+
-- in 2.5.0; default flip is 3.0.0, gated on client confirmations). Mirrors
|
|
7
|
+
-- auth.models.sql.AuthTenantSettings; IF NOT EXISTS so create_all(checkfirst)
|
|
8
|
+
-- and mg apply converge in either order.
|
|
9
|
+
|
|
10
|
+
-- migrate: up
|
|
11
|
+
CREATE SCHEMA IF NOT EXISTS auth_rbac;
|
|
12
|
+
|
|
13
|
+
CREATE TABLE IF NOT EXISTS auth_rbac.auth_tenant_settings (
|
|
14
|
+
id SERIAL PRIMARY KEY,
|
|
15
|
+
creator VARCHAR(64) NOT NULL,
|
|
16
|
+
strict_users BOOLEAN NOT NULL DEFAULT FALSE,
|
|
17
|
+
date_created TIMESTAMP DEFAULT now(),
|
|
18
|
+
modified TIMESTAMP DEFAULT now(),
|
|
19
|
+
CONSTRAINT uq_auth_tenant_settings_creator UNIQUE (creator)
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_tenant_settings_id
|
|
23
|
+
ON auth_rbac.auth_tenant_settings (id);
|
|
24
|
+
|
|
25
|
+
-- migrate: down
|
|
26
|
+
DROP TABLE IF EXISTS auth_rbac.auth_tenant_settings;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
-- migration: grandfather_strict_users
|
|
2
|
+
-- id: 01KYTX0MKVZ775P62CJ87631Z1
|
|
3
|
+
--
|
|
4
|
+
-- 3.0.0 flip protection (SPEC 0012, issuedb #18): every creator existing on
|
|
5
|
+
-- this database gets an explicit strict_users=false row, so the 3.0.0
|
|
6
|
+
-- no-row-means-strict default reaches ONLY tenants created afterwards. A
|
|
7
|
+
-- marker row ('__meta:grandfathered-3.0__', reserved) records that the pass
|
|
8
|
+
-- ran; the identical marker-guarded pass in auth.database.create_tables()
|
|
9
|
+
-- composes idempotently with this migration in either order.
|
|
10
|
+
--
|
|
11
|
+
-- The three base RBAC tables are created here IF NOT EXISTS (exact
|
|
12
|
+
-- create_all parity, like add_auth_api_key did for its table): on a fresh
|
|
13
|
+
-- database migrations must be self-sufficient — production already has
|
|
14
|
+
-- them, so these are no-ops there.
|
|
15
|
+
--
|
|
16
|
+
-- down removes the marker only: the grandfather rows are deliberate,
|
|
17
|
+
-- auditable tenant state and are kept on rollback.
|
|
18
|
+
|
|
19
|
+
-- migrate: up
|
|
20
|
+
CREATE SCHEMA IF NOT EXISTS auth_rbac;
|
|
21
|
+
|
|
22
|
+
CREATE TABLE IF NOT EXISTS auth_rbac.auth_group (
|
|
23
|
+
id SERIAL PRIMARY KEY,
|
|
24
|
+
creator VARCHAR(64) NOT NULL,
|
|
25
|
+
role TEXT NOT NULL,
|
|
26
|
+
description TEXT,
|
|
27
|
+
is_active BOOLEAN DEFAULT TRUE,
|
|
28
|
+
date_created TIMESTAMP DEFAULT now(),
|
|
29
|
+
modified TIMESTAMP DEFAULT now(),
|
|
30
|
+
CONSTRAINT uq_auth_group_creator_role UNIQUE (creator, role)
|
|
31
|
+
);
|
|
32
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_group_id ON auth_rbac.auth_group (id);
|
|
33
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_group_creator ON auth_rbac.auth_group (creator);
|
|
34
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_group_role ON auth_rbac.auth_group (role);
|
|
35
|
+
|
|
36
|
+
CREATE TABLE IF NOT EXISTS auth_rbac.auth_membership (
|
|
37
|
+
id SERIAL PRIMARY KEY,
|
|
38
|
+
"user" TEXT NOT NULL,
|
|
39
|
+
creator VARCHAR(64) NOT NULL,
|
|
40
|
+
is_active BOOLEAN DEFAULT TRUE,
|
|
41
|
+
date_created TIMESTAMP DEFAULT now(),
|
|
42
|
+
modified TIMESTAMP DEFAULT now(),
|
|
43
|
+
CONSTRAINT uq_auth_membership_creator_user UNIQUE (creator, "user")
|
|
44
|
+
);
|
|
45
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_membership_id ON auth_rbac.auth_membership (id);
|
|
46
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_membership_creator ON auth_rbac.auth_membership (creator);
|
|
47
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_membership_user ON auth_rbac.auth_membership ("user");
|
|
48
|
+
|
|
49
|
+
CREATE TABLE IF NOT EXISTS auth_rbac.auth_permission (
|
|
50
|
+
id SERIAL PRIMARY KEY,
|
|
51
|
+
name TEXT NOT NULL,
|
|
52
|
+
creator VARCHAR(64) NOT NULL,
|
|
53
|
+
is_active BOOLEAN DEFAULT TRUE,
|
|
54
|
+
date_created TIMESTAMP DEFAULT now(),
|
|
55
|
+
modified TIMESTAMP DEFAULT now(),
|
|
56
|
+
CONSTRAINT uq_auth_permission_creator_name UNIQUE (creator, name)
|
|
57
|
+
);
|
|
58
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_permission_id ON auth_rbac.auth_permission (id);
|
|
59
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_permission_creator ON auth_rbac.auth_permission (creator);
|
|
60
|
+
CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_permission_name ON auth_rbac.auth_permission (name);
|
|
61
|
+
|
|
62
|
+
INSERT INTO auth_rbac.auth_tenant_settings (creator, strict_users)
|
|
63
|
+
SELECT c.creator, FALSE
|
|
64
|
+
FROM (
|
|
65
|
+
SELECT creator FROM auth_rbac.auth_group
|
|
66
|
+
UNION SELECT creator FROM auth_rbac.auth_membership
|
|
67
|
+
UNION SELECT creator FROM auth_rbac.auth_permission
|
|
68
|
+
UNION SELECT creator FROM auth_rbac.auth_api_key
|
|
69
|
+
) c
|
|
70
|
+
WHERE NOT EXISTS (
|
|
71
|
+
SELECT 1 FROM auth_rbac.auth_tenant_settings
|
|
72
|
+
WHERE creator = '__meta:grandfathered-3.0__'
|
|
73
|
+
)
|
|
74
|
+
AND c.creator NOT IN (SELECT creator FROM auth_rbac.auth_tenant_settings);
|
|
75
|
+
|
|
76
|
+
INSERT INTO auth_rbac.auth_tenant_settings (creator, strict_users)
|
|
77
|
+
SELECT '__meta:grandfathered-3.0__', FALSE
|
|
78
|
+
WHERE NOT EXISTS (
|
|
79
|
+
SELECT 1 FROM auth_rbac.auth_tenant_settings
|
|
80
|
+
WHERE creator = '__meta:grandfathered-3.0__'
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
-- migrate: down
|
|
84
|
+
DELETE FROM auth_rbac.auth_tenant_settings
|
|
85
|
+
WHERE creator = '__meta:grandfathered-3.0__';
|