tigrbl-identity-credentials 0.4.0.dev1__py3-none-any.whl
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.
- tigrbl_identity_credentials/__init__.py +5 -0
- tigrbl_identity_credentials/adapters/__init__.py +14 -0
- tigrbl_identity_credentials/adapters/local.py +47 -0
- tigrbl_identity_credentials/adapters/remote.py +162 -0
- tigrbl_identity_credentials/auth_context.py +28 -0
- tigrbl_identity_credentials/authenticate.py +8 -0
- tigrbl_identity_credentials/authenticators.py +113 -0
- tigrbl_identity_credentials/backends.py +79 -0
- tigrbl_identity_credentials/session_service.py +140 -0
- tigrbl_identity_credentials/token_service.py +455 -0
- tigrbl_identity_credentials-0.4.0.dev1.dist-info/METADATA +20 -0
- tigrbl_identity_credentials-0.4.0.dev1.dist-info/RECORD +13 -0
- tigrbl_identity_credentials-0.4.0.dev1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# tigrbl_auth/v2/adapters/__init__.py
|
|
2
|
+
def __getattr__(name):
|
|
3
|
+
if name == "RemoteAuthNAdapter":
|
|
4
|
+
from .remote_adapter import RemoteAuthNAdapter
|
|
5
|
+
|
|
6
|
+
return RemoteAuthNAdapter
|
|
7
|
+
if name == "LocalAuthNAdapter":
|
|
8
|
+
from .local_adapter import LocalAuthNAdapter
|
|
9
|
+
|
|
10
|
+
return LocalAuthNAdapter
|
|
11
|
+
raise AttributeError(name)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
__all__ = ["LocalAuthNAdapter", "RemoteAuthNAdapter"]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
tigrbl_auth.adapters.local_adapter
|
|
3
|
+
──────────────────
|
|
4
|
+
Concrete implementation of the ``AuthNProvider`` ABC declared by
|
|
5
|
+
``tigrbl.authn_abc``. It merely **adapts** the public helpers that already
|
|
6
|
+
exist in *tigrbl_auth* so that Tigrbl can consume them automatically.
|
|
7
|
+
|
|
8
|
+
Usage
|
|
9
|
+
-----
|
|
10
|
+
>>> from tigrbl_auth.framework import TigrblRouter
|
|
11
|
+
>>> from tigrbl_auth.adapters import LocalAuthNAdapter
|
|
12
|
+
>>> api = TigrblRouter(engine=ENGINE, authn=LocalAuthNAdapter())
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from tigrbl_auth.framework import AuthNProvider, Request
|
|
18
|
+
from tigrbl_auth.security.auth import get_principal
|
|
19
|
+
from tigrbl_auth.security.context import principal_var # noqa: F401 # ensure ContextVar is initialised
|
|
20
|
+
from .auth_context import set_auth_context
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LocalAuthNAdapter(AuthNProvider):
|
|
24
|
+
"""
|
|
25
|
+
Thin wrapper that plugs existing *tigrbl_auth* functions into
|
|
26
|
+
the abstract interface expected by Tigrbl.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
# ------------------------------------------------------------------ #
|
|
30
|
+
# Tigrbl dependency (mandatory) #
|
|
31
|
+
# ------------------------------------------------------------------ #
|
|
32
|
+
async def get_principal(self, request: Request) -> dict: # noqa: D401
|
|
33
|
+
"""
|
|
34
|
+
Delegate to ``tigrbl_auth.security.deps.get_principal`` and forward
|
|
35
|
+
whatever dict it returns.
|
|
36
|
+
|
|
37
|
+
Raises
|
|
38
|
+
------
|
|
39
|
+
tigrbl.types.HTTPException(401)
|
|
40
|
+
If the API‑key / bearer token is invalid or expired.
|
|
41
|
+
"""
|
|
42
|
+
principal = await get_principal(request) # type: ignore[arg-type]
|
|
43
|
+
set_auth_context(request, principal)
|
|
44
|
+
return principal
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
__all__ = ["LocalAuthNAdapter"]
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# tigrbl_auth/v2/adapters/remote_adapter.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
from typing import Final
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from tigrbl_auth.framework import (
|
|
9
|
+
HTTPException,
|
|
10
|
+
Request,
|
|
11
|
+
Security,
|
|
12
|
+
status,
|
|
13
|
+
APIKey,
|
|
14
|
+
AuthNProvider,
|
|
15
|
+
)
|
|
16
|
+
from tigrbl_auth.security.context import principal_var
|
|
17
|
+
from .auth_context import set_auth_context
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# OpenAPI-advertised security scheme (header-based API key)
|
|
21
|
+
_API_KEY_REQUIRED = APIKey(name="X-API-Key", auto_error=True)
|
|
22
|
+
_API_KEY_OPTIONAL = APIKey(name="X-API-Key", auto_error=False)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RemoteAuthNAdapter(AuthNProvider):
|
|
26
|
+
"""
|
|
27
|
+
Authenticate every request by calling a *remote* AuthN service.
|
|
28
|
+
|
|
29
|
+
Parameters
|
|
30
|
+
----------
|
|
31
|
+
base_url:
|
|
32
|
+
Full origin of the AuthN deployment, *without* trailing slash,
|
|
33
|
+
e.g. ``"https://authn.internal:8080"``.
|
|
34
|
+
timeout:
|
|
35
|
+
Float seconds for the outbound HTTP POST (default **0.4 s**).
|
|
36
|
+
cache_ttl:
|
|
37
|
+
TTL in seconds for the in-process API-key cache (default **10 s**).
|
|
38
|
+
cache_size:
|
|
39
|
+
Maximum number of distinct API-keys to cache (default **10,000**).
|
|
40
|
+
client:
|
|
41
|
+
Optional pre-configured ``httpx.AsyncClient``. If omitted, one is created.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
# ------------------------------------------------------------------ #
|
|
45
|
+
# construction #
|
|
46
|
+
# ------------------------------------------------------------------ #
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
*,
|
|
50
|
+
base_url: str,
|
|
51
|
+
timeout: float = 0.4,
|
|
52
|
+
cache_ttl: int = 10,
|
|
53
|
+
cache_size: int = 10_000,
|
|
54
|
+
client: httpx.AsyncClient | None = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
self.base_url = base_url.rstrip("/")
|
|
57
|
+
self._introspect = f"{self.base_url}/introspect"
|
|
58
|
+
self._client = client or httpx.AsyncClient(
|
|
59
|
+
timeout=timeout,
|
|
60
|
+
headers={"User-Agent": "autoauthn-remote-adapter"},
|
|
61
|
+
)
|
|
62
|
+
self._ttl: Final[int] = cache_ttl
|
|
63
|
+
self._max: Final[int] = cache_size
|
|
64
|
+
self._cache: dict[str, tuple[dict, float]] = {} # api_key -> (principal, ts)
|
|
65
|
+
|
|
66
|
+
# ------------------------------------------------------------------ #
|
|
67
|
+
# AuthNProvider : Tigrbl dependencies #
|
|
68
|
+
# ------------------------------------------------------------------ #
|
|
69
|
+
async def get_principal( # strict: header is required (401 on invalid)
|
|
70
|
+
self,
|
|
71
|
+
request: Request,
|
|
72
|
+
api_key: str = Security(_API_KEY_REQUIRED),
|
|
73
|
+
) -> dict:
|
|
74
|
+
"""
|
|
75
|
+
Resolve and return the principal for a required API key.
|
|
76
|
+
|
|
77
|
+
Emits a 401 when the key is invalid/expired. Missing header is handled
|
|
78
|
+
by the security scheme (auto_error=True).
|
|
79
|
+
"""
|
|
80
|
+
principal = self._cache_get(api_key)
|
|
81
|
+
if principal is None:
|
|
82
|
+
principal = await self._introspect_key(api_key)
|
|
83
|
+
if principal is None:
|
|
84
|
+
raise HTTPException(
|
|
85
|
+
status.HTTP_401_UNAUTHORIZED, "Invalid or expired API key"
|
|
86
|
+
)
|
|
87
|
+
self._cache_put(api_key, principal)
|
|
88
|
+
|
|
89
|
+
request.state.principal = principal
|
|
90
|
+
principal_var.set(principal)
|
|
91
|
+
set_auth_context(request, principal)
|
|
92
|
+
return principal
|
|
93
|
+
|
|
94
|
+
async def get_principal_optional( # optional: header may be absent
|
|
95
|
+
self,
|
|
96
|
+
request: Request,
|
|
97
|
+
api_key: str | None = Security(_API_KEY_OPTIONAL),
|
|
98
|
+
) -> dict | None:
|
|
99
|
+
"""
|
|
100
|
+
Resolve and return the principal when the API key header is optional.
|
|
101
|
+
|
|
102
|
+
Returns ``None`` when no API key is provided or when introspection fails.
|
|
103
|
+
Never raises due to missing header (auto_error=False).
|
|
104
|
+
"""
|
|
105
|
+
if not api_key:
|
|
106
|
+
request.state.principal = None
|
|
107
|
+
principal_var.set(None)
|
|
108
|
+
set_auth_context(request, None)
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
principal = self._cache_get(api_key)
|
|
112
|
+
if principal is None:
|
|
113
|
+
principal = await self._introspect_key(api_key)
|
|
114
|
+
if principal is None:
|
|
115
|
+
# For optional auth we do not raise; return None to allow anon flows.
|
|
116
|
+
request.state.principal = None
|
|
117
|
+
principal_var.set(None)
|
|
118
|
+
set_auth_context(request, None)
|
|
119
|
+
return None
|
|
120
|
+
self._cache_put(api_key, principal)
|
|
121
|
+
|
|
122
|
+
request.state.principal = principal
|
|
123
|
+
principal_var.set(principal)
|
|
124
|
+
set_auth_context(request, principal)
|
|
125
|
+
return principal
|
|
126
|
+
|
|
127
|
+
# ------------------------------------------------------------------ #
|
|
128
|
+
# internal helpers #
|
|
129
|
+
# ------------------------------------------------------------------ #
|
|
130
|
+
async def _introspect_key(self, api_key: str) -> dict | None:
|
|
131
|
+
try:
|
|
132
|
+
resp = await self._client.post(self._introspect, data={"token": api_key})
|
|
133
|
+
except Exception:
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
if resp.status_code != 200:
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
body = resp.json()
|
|
141
|
+
except Exception:
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
if not isinstance(body, dict) or not body.get("active"):
|
|
145
|
+
return None
|
|
146
|
+
return body
|
|
147
|
+
|
|
148
|
+
def _cache_get(self, key: str) -> dict | None:
|
|
149
|
+
hit = self._cache.get(key)
|
|
150
|
+
if hit and time.monotonic() - hit[1] < self._ttl:
|
|
151
|
+
return hit[0]
|
|
152
|
+
self._cache.pop(key, None)
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
def _cache_put(self, key: str, principal: dict) -> None:
|
|
156
|
+
if len(self._cache) >= self._max:
|
|
157
|
+
# FIFO eviction
|
|
158
|
+
self._cache.pop(next(iter(self._cache)))
|
|
159
|
+
self._cache[key] = (principal, time.monotonic())
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
__all__ = ["RemoteAuthNAdapter"]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from tigrbl_auth.framework import Request, TIGRBL_AUTH_CONTEXT_ATTR
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def set_auth_context(request: Request, principal: dict | None) -> None:
|
|
7
|
+
"""Populate request.state with the auth context expected by Tigrbl.
|
|
8
|
+
|
|
9
|
+
Parameters
|
|
10
|
+
----------
|
|
11
|
+
request:
|
|
12
|
+
Incoming request whose state should be populated.
|
|
13
|
+
principal:
|
|
14
|
+
Principal dictionary containing ``tenant_id`` (``tid``) and ``user_id``
|
|
15
|
+
(``sub``). May be ``None`` when no authenticated principal is present.
|
|
16
|
+
"""
|
|
17
|
+
ctx: dict[str, str] = {}
|
|
18
|
+
if principal:
|
|
19
|
+
tid = principal.get("tid") or principal.get("tenant_id")
|
|
20
|
+
uid = principal.get("sub") or principal.get("user_id")
|
|
21
|
+
if tid is not None:
|
|
22
|
+
ctx["tenant_id"] = tid
|
|
23
|
+
if uid is not None:
|
|
24
|
+
ctx["user_id"] = uid
|
|
25
|
+
setattr(request.state, TIGRBL_AUTH_CONTEXT_ATTR, ctx)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
__all__ = ["set_auth_context"]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Legacy import facade for canonical authentication backend operations.
|
|
2
|
+
|
|
3
|
+
The authoritative implementations live in ``tigrbl_auth.services.auth_backends``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from tigrbl_auth.services.auth_backends import ApiKeyBackend, AuthError, PasswordBackend
|
|
7
|
+
|
|
8
|
+
__all__ = ["ApiKeyBackend", "AuthError", "PasswordBackend"]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Certified-core auth dependency helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from tigrbl_auth.framework import AsyncSession, Depends, Header, HTTPException, Request, select, status
|
|
6
|
+
from tigrbl_auth.config.deployment import deployment_from_request
|
|
7
|
+
from tigrbl_auth.config.settings import settings
|
|
8
|
+
from tigrbl_auth.security.context import principal_var
|
|
9
|
+
from tigrbl_auth.standards.oidc.session_mgmt import resolve_browser_session
|
|
10
|
+
from tigrbl_auth.services.auth_backends import ApiKeyBackend, AuthError, PasswordBackend
|
|
11
|
+
from tigrbl_auth.services.token_service import JWTCoder, InvalidTokenError
|
|
12
|
+
from tigrbl_auth.standards.oauth2.mtls import presented_certificate_thumbprint
|
|
13
|
+
from tigrbl_auth.standards.oauth2.rfc6750 import extract_bearer_token
|
|
14
|
+
from tigrbl_auth.standards.oauth2.rfc9700 import verify_access_token_sender_constraint
|
|
15
|
+
from tigrbl_auth.tables import User
|
|
16
|
+
from tigrbl_auth.tables.engine import get_db
|
|
17
|
+
from tigrbl_auth.typing import Principal
|
|
18
|
+
|
|
19
|
+
_api_key_backend = ApiKeyBackend()
|
|
20
|
+
_jwt_coder = JWTCoder.default()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def _user_from_jwt(token: str, db: AsyncSession, *, cert_thumbprint: str | None = None) -> User | None:
|
|
24
|
+
try:
|
|
25
|
+
payload = await _jwt_coder.async_decode(token, cert_thumbprint=cert_thumbprint)
|
|
26
|
+
except InvalidTokenError:
|
|
27
|
+
return None
|
|
28
|
+
return await db.scalar(select(User).where(User.id == payload["sub"], User.is_active.is_(True)))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def _user_from_api_key(raw_key: str, db: AsyncSession) -> Principal | None:
|
|
32
|
+
try:
|
|
33
|
+
principal, _ = await _api_key_backend.authenticate(db, raw_key)
|
|
34
|
+
return principal
|
|
35
|
+
except AuthError:
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def _user_from_browser_session(request: Request, db: AsyncSession) -> User | None:
|
|
40
|
+
session = await resolve_browser_session(request)
|
|
41
|
+
if session is None:
|
|
42
|
+
return None
|
|
43
|
+
return await db.scalar(select(User).where(User.id == session.user_id, User.is_active.is_(True)))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def get_principal(
|
|
47
|
+
request: Request,
|
|
48
|
+
authorization: str = Header("", alias="Authorization"),
|
|
49
|
+
api_key: str | None = Header(None, alias="x-api-key"),
|
|
50
|
+
dpop: str | None = Header(None, alias="DPoP"),
|
|
51
|
+
db: AsyncSession = Depends(get_db),
|
|
52
|
+
) -> dict:
|
|
53
|
+
user = await get_current_principal(
|
|
54
|
+
request,
|
|
55
|
+
authorization=authorization,
|
|
56
|
+
api_key=api_key,
|
|
57
|
+
dpop=dpop,
|
|
58
|
+
db=db,
|
|
59
|
+
)
|
|
60
|
+
principal = {"sub": str(user.id), "tid": str(user.tenant_id)}
|
|
61
|
+
request.state.principal = principal
|
|
62
|
+
principal_var.set(principal)
|
|
63
|
+
return principal
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def get_current_principal(
|
|
67
|
+
request: Request,
|
|
68
|
+
authorization: str = Header("", alias="Authorization"),
|
|
69
|
+
api_key: str | None = Header(None, alias="x-api-key"),
|
|
70
|
+
dpop: str | None = Header(None, alias="DPoP"),
|
|
71
|
+
db: AsyncSession = Depends(get_db),
|
|
72
|
+
) -> Principal:
|
|
73
|
+
if api_key:
|
|
74
|
+
if user := await _user_from_api_key(api_key, db):
|
|
75
|
+
return user
|
|
76
|
+
if user := await _user_from_browser_session(request, db):
|
|
77
|
+
return user
|
|
78
|
+
token = await extract_bearer_token(request, authorization)
|
|
79
|
+
if token:
|
|
80
|
+
cert_thumbprint = presented_certificate_thumbprint(request)
|
|
81
|
+
try:
|
|
82
|
+
payload = await _jwt_coder.async_decode(token, cert_thumbprint=cert_thumbprint)
|
|
83
|
+
except InvalidTokenError as exc:
|
|
84
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid token") from exc
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
verify_access_token_sender_constraint(
|
|
88
|
+
request,
|
|
89
|
+
payload,
|
|
90
|
+
deployment_from_request(request, settings),
|
|
91
|
+
access_token=token,
|
|
92
|
+
dpop_proof=dpop,
|
|
93
|
+
)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
detail = getattr(exc, 'description', 'invalid token')
|
|
96
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail) from exc
|
|
97
|
+
|
|
98
|
+
if user := await _user_from_jwt(token, db, cert_thumbprint=cert_thumbprint):
|
|
99
|
+
return user
|
|
100
|
+
raise HTTPException(
|
|
101
|
+
status.HTTP_401_UNAUTHORIZED,
|
|
102
|
+
"invalid or missing credentials",
|
|
103
|
+
headers={"WWW-Authenticate": 'Bearer realm="authn"'},
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
__all__ = [
|
|
108
|
+
"get_current_principal",
|
|
109
|
+
"get_principal",
|
|
110
|
+
"principal_var",
|
|
111
|
+
"PasswordBackend",
|
|
112
|
+
"ApiKeyBackend",
|
|
113
|
+
]
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Authentication backends for password and API-key credentials."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Iterable, Optional
|
|
7
|
+
|
|
8
|
+
from tigrbl_auth.framework import Select, or_, select, AsyncSession
|
|
9
|
+
from tigrbl_auth.services.key_management import verify_pw
|
|
10
|
+
from tigrbl_auth.typing import Principal
|
|
11
|
+
from tigrbl_auth.tables import ApiKey, Client, ServiceKey, User
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AuthError(Exception):
|
|
15
|
+
def __init__(self, reason: str = "authentication failed"):
|
|
16
|
+
super().__init__(reason)
|
|
17
|
+
self.reason = reason
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PasswordBackend:
|
|
21
|
+
async def _get_user_stmt(self, identifier: str) -> Select[tuple[User]]:
|
|
22
|
+
return select(User).where(
|
|
23
|
+
or_(User.username == identifier, User.email == identifier),
|
|
24
|
+
User.is_active.is_(True),
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
async def authenticate(self, db: AsyncSession, identifier: str, password: str) -> User:
|
|
28
|
+
row: Optional[User] = await db.scalar(await self._get_user_stmt(identifier))
|
|
29
|
+
if not row or not verify_pw(password, row.password_hash):
|
|
30
|
+
raise AuthError("invalid username/email or password")
|
|
31
|
+
return row
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ApiKeyBackend:
|
|
35
|
+
async def _get_key_stmt(self, digest: str) -> Select[tuple[ApiKey]]:
|
|
36
|
+
now = datetime.now(timezone.utc)
|
|
37
|
+
return select(ApiKey).where(
|
|
38
|
+
ApiKey.digest == digest,
|
|
39
|
+
or_(ApiKey.valid_to.is_(None), ApiKey.valid_to > now),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
async def _get_service_key_stmt(self, digest: str) -> Select[tuple[ServiceKey]]:
|
|
43
|
+
now = datetime.now(timezone.utc)
|
|
44
|
+
return select(ServiceKey).where(
|
|
45
|
+
ServiceKey.digest == digest,
|
|
46
|
+
or_(ServiceKey.valid_to.is_(None), ServiceKey.valid_to > now),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
async def _get_client_stmt(self) -> Select[tuple[Client]]:
|
|
50
|
+
return select(Client).where(Client.is_active.is_(True))
|
|
51
|
+
|
|
52
|
+
async def authenticate(self, db: AsyncSession, api_key: str) -> tuple[Principal, str]:
|
|
53
|
+
digest = ApiKey.digest_of(api_key)
|
|
54
|
+
|
|
55
|
+
key_row: Optional[ApiKey] = await db.scalar(await self._get_key_stmt(digest))
|
|
56
|
+
user = getattr(key_row, "user", None) or getattr(key_row, "_user", None)
|
|
57
|
+
if key_row and user:
|
|
58
|
+
if not user.is_active:
|
|
59
|
+
raise AuthError("user is inactive")
|
|
60
|
+
key_row.touch()
|
|
61
|
+
return user, "user"
|
|
62
|
+
|
|
63
|
+
svc_row: Optional[ServiceKey] = await db.scalar(await self._get_service_key_stmt(digest))
|
|
64
|
+
service = getattr(svc_row, "service", None) or getattr(svc_row, "_service", None)
|
|
65
|
+
if svc_row and service:
|
|
66
|
+
if not service.is_active:
|
|
67
|
+
raise AuthError("service is inactive")
|
|
68
|
+
svc_row.touch()
|
|
69
|
+
return service, "service"
|
|
70
|
+
|
|
71
|
+
clients: Iterable[Client] = await db.scalars(await self._get_client_stmt())
|
|
72
|
+
for client in clients:
|
|
73
|
+
if client.verify_secret(api_key):
|
|
74
|
+
return client, "client"
|
|
75
|
+
|
|
76
|
+
raise AuthError("API key invalid, revoked, or expired")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
__all__ = ["AuthError", "PasswordBackend", "ApiKeyBackend"]
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Mapping
|
|
6
|
+
|
|
7
|
+
from ._operator_store import OperationContext, TransactionResult, utc_now
|
|
8
|
+
from .audit_service import record_surface_event
|
|
9
|
+
from .operator_service import (
|
|
10
|
+
exchange_token,
|
|
11
|
+
get_record,
|
|
12
|
+
get_resource,
|
|
13
|
+
introspect_token_record,
|
|
14
|
+
list_resource_result,
|
|
15
|
+
revoke_resource,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def token_hash(token: str) -> str:
|
|
20
|
+
return hashlib.sha256(str(token).encode("utf-8")).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _normalized_context(repo_root: Path, *, command: str, resource: str, actor: str | None = None, tenant: str | None = None, issuer: str | None = None, profile: str | None = None, dry_run: bool = False) -> OperationContext:
|
|
24
|
+
return OperationContext(repo_root=repo_root, command=command, resource=resource, dry_run=dry_run, actor=actor or "system", tenant=tenant, issuer=issuer, profile=profile)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def list_sessions_for_context(context: OperationContext, *, status_filter: str | None = None, filter_expr: str | None = None, sort: str = "id", offset: int = 0, limit: int = 50) -> TransactionResult:
|
|
28
|
+
return list_resource_result(context, status_filter=status_filter, filter_expr=filter_expr, sort=sort, offset=offset, limit=limit)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_session_for_context(context: OperationContext, *, record_id: str) -> TransactionResult:
|
|
32
|
+
return get_resource(context, record_id=record_id)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def revoke_session_for_context(context: OperationContext, *, record_id: str) -> TransactionResult:
|
|
36
|
+
return revoke_resource(context, record_id=record_id)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def revoke_all_sessions_for_context(context: OperationContext, *, status_filter: str | None = None, filter_expr: str | None = None) -> TransactionResult:
|
|
40
|
+
return revoke_resource(context, all_records=True, status_filter=status_filter, filter_expr=filter_expr)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def list_tokens_for_context(context: OperationContext, *, status_filter: str | None = None, filter_expr: str | None = None, sort: str = "id", offset: int = 0, limit: int = 50) -> TransactionResult:
|
|
44
|
+
return list_resource_result(context, status_filter=status_filter, filter_expr=filter_expr, sort=sort, offset=offset, limit=limit)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_token_for_context(context: OperationContext, *, record_id: str) -> TransactionResult:
|
|
48
|
+
return get_resource(context, record_id=record_id)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def introspect_token_for_context(context: OperationContext, *, record_id: str) -> TransactionResult:
|
|
52
|
+
result = get_resource(context, record_id=record_id)
|
|
53
|
+
if result.record is None:
|
|
54
|
+
return result
|
|
55
|
+
result.summary = introspect_token_record(result.record)
|
|
56
|
+
return result
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def revoke_token_for_context(context: OperationContext, *, record_id: str) -> TransactionResult:
|
|
60
|
+
return revoke_resource(context, record_id=record_id)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def revoke_all_tokens_for_context(context: OperationContext, *, status_filter: str | None = None, filter_expr: str | None = None) -> TransactionResult:
|
|
64
|
+
return revoke_resource(context, all_records=True, status_filter=status_filter, filter_expr=filter_expr)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def exchange_token_for_context(context: OperationContext, *, subject_token: str | None, requested_token_type: str | None = None, audience: str | None = None, resource: str | None = None, actor_token: str | None = None, extras: Mapping[str, Any] | None = None) -> TransactionResult:
|
|
68
|
+
return exchange_token(context, subject_token=subject_token, requested_token_type=requested_token_type, audience=audience, resource=resource, actor_token=actor_token, extras=extras)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _observe_token_like(repo_root: Path, *, token: str, kind: str, actor: str | None = None, tenant: str | None = None, issuer: str | None = None, details: Mapping[str, Any] | None = None) -> str:
|
|
72
|
+
from .operator_service import create_resource
|
|
73
|
+
|
|
74
|
+
details = dict(details or {})
|
|
75
|
+
record_id = token_hash(token)
|
|
76
|
+
context = _normalized_context(repo_root, command="observe", resource="token", actor=actor, tenant=tenant, issuer=issuer)
|
|
77
|
+
patch = {
|
|
78
|
+
"token_hash": record_id,
|
|
79
|
+
"token_kind": kind,
|
|
80
|
+
"token_type": details.get("token_type") or kind,
|
|
81
|
+
"subject": details.get("subject") or details.get("sub"),
|
|
82
|
+
"client_id": details.get("client_id"),
|
|
83
|
+
"scope": details.get("scope"),
|
|
84
|
+
"issuer": issuer or details.get("issuer"),
|
|
85
|
+
"audience": details.get("audience") or details.get("aud"),
|
|
86
|
+
"issued_at": details.get("issued_at") or utc_now(),
|
|
87
|
+
"expires_at": details.get("expires_at"),
|
|
88
|
+
"claims": details.get("claims"),
|
|
89
|
+
"token": token,
|
|
90
|
+
}
|
|
91
|
+
create_resource(context, record_id=record_id, patch=patch, if_exists="update")
|
|
92
|
+
record_surface_event(repo_root, event_type=f"observe_{kind}", target_type="token", target_id=record_id, outcome="ok", tenant_id=tenant, actor_user_id=actor, details=details, source_surface="runtime")
|
|
93
|
+
return record_id
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def observe_token_response(repo_root: Path, *, access_token: str | None = None, refresh_token: str | None = None, id_token: str | None = None, actor: str | None = None, tenant: str | None = None, issuer: str | None = None, details: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
97
|
+
observed: dict[str, Any] = {}
|
|
98
|
+
if access_token:
|
|
99
|
+
observed["access_token_id"] = _observe_token_like(repo_root, token=access_token, kind="access", actor=actor, tenant=tenant, issuer=issuer, details=details)
|
|
100
|
+
if refresh_token:
|
|
101
|
+
observed["refresh_token_id"] = _observe_token_like(repo_root, token=refresh_token, kind="refresh", actor=actor, tenant=tenant, issuer=issuer, details=details)
|
|
102
|
+
if id_token:
|
|
103
|
+
observed["id_token_id"] = _observe_token_like(repo_root, token=id_token, kind="id", actor=actor, tenant=tenant, issuer=issuer, details=details)
|
|
104
|
+
return observed
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def observe_logout_response(repo_root: Path, *, session_id: str | None, actor: str | None = None, tenant: str | None = None, details: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
108
|
+
record_surface_event(repo_root, event_type="logout", target_type="session", target_id=session_id, outcome="ok", tenant_id=tenant, actor_user_id=actor, details=details, source_surface="runtime")
|
|
109
|
+
return {"session_id": session_id, "status": "ok"}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def observe_device_authorization_response(repo_root: Path, *, device_code: str | None, actor: str | None = None, tenant: str | None = None, details: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
113
|
+
target_id = token_hash(device_code) if device_code else None
|
|
114
|
+
record_surface_event(repo_root, event_type="device_authorization", target_type="token", target_id=target_id, outcome="ok", tenant_id=tenant, actor_user_id=actor, details=details, source_surface="runtime")
|
|
115
|
+
return {"device_code_id": target_id, "status": "ok"}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def observe_par_response(repo_root: Path, *, request_uri: str | None, actor: str | None = None, tenant: str | None = None, details: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
119
|
+
target_id = token_hash(request_uri) if request_uri else None
|
|
120
|
+
record_surface_event(repo_root, event_type="par", target_type="pushed_authorization_request", target_id=target_id, outcome="ok", tenant_id=tenant, actor_user_id=actor, details=details, source_surface="runtime")
|
|
121
|
+
return {"request_uri_id": target_id, "status": "ok"}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
__all__ = [
|
|
125
|
+
"exchange_token_for_context",
|
|
126
|
+
"get_session_for_context",
|
|
127
|
+
"get_token_for_context",
|
|
128
|
+
"introspect_token_for_context",
|
|
129
|
+
"list_sessions_for_context",
|
|
130
|
+
"list_tokens_for_context",
|
|
131
|
+
"observe_device_authorization_response",
|
|
132
|
+
"observe_logout_response",
|
|
133
|
+
"observe_par_response",
|
|
134
|
+
"observe_token_response",
|
|
135
|
+
"revoke_all_sessions_for_context",
|
|
136
|
+
"revoke_all_tokens_for_context",
|
|
137
|
+
"revoke_session_for_context",
|
|
138
|
+
"revoke_token_for_context",
|
|
139
|
+
"token_hash",
|
|
140
|
+
]
|
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
"""JWT minting/verification and operator token wrappers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import json
|
|
8
|
+
from copy import deepcopy
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from threading import Thread
|
|
13
|
+
from typing import Any, Dict, Iterable, Optional, Tuple
|
|
14
|
+
from uuid import uuid4
|
|
15
|
+
|
|
16
|
+
from tigrbl_auth.errors import InvalidTokenError
|
|
17
|
+
|
|
18
|
+
from .key_management import _DEFAULT_KEY_PATH, _ensure_key, _provider
|
|
19
|
+
from .session_service import (
|
|
20
|
+
exchange_token_for_context,
|
|
21
|
+
get_token_for_context,
|
|
22
|
+
introspect_token_for_context,
|
|
23
|
+
list_tokens_for_context,
|
|
24
|
+
revoke_all_tokens_for_context,
|
|
25
|
+
revoke_token_for_context,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
_ACCESS_TTL = timedelta(minutes=60)
|
|
29
|
+
_REFRESH_TTL = timedelta(days=7)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RefreshTokenError(Exception):
|
|
33
|
+
"""Base class for refresh token lifecycle failures."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class InvalidRefreshTokenError(RefreshTokenError):
|
|
37
|
+
"""The presented refresh token is invalid for the retained boundary."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RefreshTokenReuseError(RefreshTokenError):
|
|
41
|
+
"""A refresh token replay was detected and the family was revoked."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _load_runtime() -> dict[str, Any]:
|
|
45
|
+
try:
|
|
46
|
+
from tigrbl_auth.framework import ExportPolicy, FileKeyProvider, JWTTokenService, LocalKeyProvider, JWAAlg, KeyAlg, KeyClass, KeySpec, KeyUse
|
|
47
|
+
from tigrbl_auth.config.settings import settings
|
|
48
|
+
from tigrbl_auth.standards.oauth2.mtls import validate_certificate_binding
|
|
49
|
+
from tigrbl_auth.standards.oauth2.revocation import is_revoked
|
|
50
|
+
from tigrbl_auth.standards.oauth2.introspection import register_token
|
|
51
|
+
except Exception as exc: # pragma: no cover
|
|
52
|
+
raise RuntimeError("runtime token-service dependencies are unavailable") from exc
|
|
53
|
+
return {
|
|
54
|
+
"ExportPolicy": ExportPolicy,
|
|
55
|
+
"FileKeyProvider": FileKeyProvider,
|
|
56
|
+
"JWTTokenService": JWTTokenService,
|
|
57
|
+
"LocalKeyProvider": LocalKeyProvider,
|
|
58
|
+
"JWAAlg": JWAAlg,
|
|
59
|
+
"KeyAlg": KeyAlg,
|
|
60
|
+
"KeyClass": KeyClass,
|
|
61
|
+
"KeySpec": KeySpec,
|
|
62
|
+
"KeyUse": KeyUse,
|
|
63
|
+
"settings": settings,
|
|
64
|
+
"validate_certificate_binding": validate_certificate_binding,
|
|
65
|
+
"is_revoked": is_revoked,
|
|
66
|
+
"register_token": register_token,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _run(coro):
|
|
71
|
+
try:
|
|
72
|
+
asyncio.get_running_loop()
|
|
73
|
+
except RuntimeError:
|
|
74
|
+
return asyncio.run(coro)
|
|
75
|
+
result = None
|
|
76
|
+
|
|
77
|
+
def runner():
|
|
78
|
+
nonlocal result
|
|
79
|
+
result = asyncio.run(coro)
|
|
80
|
+
|
|
81
|
+
thread = Thread(target=runner)
|
|
82
|
+
thread.start()
|
|
83
|
+
thread.join()
|
|
84
|
+
return result
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@lru_cache(maxsize=1)
|
|
88
|
+
def _svc() -> Tuple[Any, str]:
|
|
89
|
+
runtime = _load_runtime()
|
|
90
|
+
kp = _provider()
|
|
91
|
+
if _DEFAULT_KEY_PATH.exists():
|
|
92
|
+
kid = _DEFAULT_KEY_PATH.read_text().strip()
|
|
93
|
+
if kid:
|
|
94
|
+
try:
|
|
95
|
+
_run(kp.get_key(kid, include_secret=False))
|
|
96
|
+
except Exception:
|
|
97
|
+
kid, _, _ = _run(_ensure_key())
|
|
98
|
+
else:
|
|
99
|
+
kid, _, _ = _run(_ensure_key())
|
|
100
|
+
else:
|
|
101
|
+
spec = runtime["KeySpec"](
|
|
102
|
+
klass=runtime["KeyClass"].asymmetric,
|
|
103
|
+
alg=runtime["KeyAlg"].ED25519,
|
|
104
|
+
uses=(runtime["KeyUse"].SIGN, runtime["KeyUse"].VERIFY),
|
|
105
|
+
export_policy=runtime["ExportPolicy"].SECRET_WHEN_ALLOWED,
|
|
106
|
+
label="jwt_ed25519",
|
|
107
|
+
)
|
|
108
|
+
ref = _run(kp.create_key(spec))
|
|
109
|
+
kid = ref.kid
|
|
110
|
+
_DEFAULT_KEY_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
_DEFAULT_KEY_PATH.write_text(kid)
|
|
112
|
+
service = runtime["JWTTokenService"](kp)
|
|
113
|
+
return service, kid
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _header_alg(token: str) -> str:
|
|
117
|
+
try:
|
|
118
|
+
header_segment = token.split(".")[0]
|
|
119
|
+
padded = header_segment + "=" * (-len(header_segment) % 4)
|
|
120
|
+
header = json.loads(base64.urlsafe_b64decode(padded).decode())
|
|
121
|
+
return str(header.get("alg", "")).lower()
|
|
122
|
+
except Exception:
|
|
123
|
+
return ""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class JWTCoder:
|
|
127
|
+
__slots__ = ("_svc", "_kid")
|
|
128
|
+
|
|
129
|
+
def __init__(self, arg1: Any, arg2: Any):
|
|
130
|
+
runtime = _load_runtime()
|
|
131
|
+
if isinstance(arg1, runtime["JWTTokenService"]) and isinstance(arg2, str):
|
|
132
|
+
self._svc = arg1
|
|
133
|
+
self._kid = arg2
|
|
134
|
+
return
|
|
135
|
+
if isinstance(arg1, (bytes, bytearray)) and isinstance(arg2, (bytes, bytearray)):
|
|
136
|
+
kp = runtime["LocalKeyProvider"]()
|
|
137
|
+
spec = runtime["KeySpec"](
|
|
138
|
+
klass=runtime["KeyClass"].asymmetric,
|
|
139
|
+
alg=runtime["KeyAlg"].ED25519,
|
|
140
|
+
uses=(runtime["KeyUse"].SIGN, runtime["KeyUse"].VERIFY),
|
|
141
|
+
export_policy=runtime["ExportPolicy"].SECRET_WHEN_ALLOWED,
|
|
142
|
+
label="jwt_ed25519",
|
|
143
|
+
)
|
|
144
|
+
ref = _run(kp.import_key(spec, arg1, public=arg2))
|
|
145
|
+
self._svc = runtime["JWTTokenService"](kp)
|
|
146
|
+
self._kid = ref.kid
|
|
147
|
+
return
|
|
148
|
+
raise TypeError("JWTCoder requires (JWTTokenService, kid) or (private_pem, public_pem)")
|
|
149
|
+
|
|
150
|
+
@classmethod
|
|
151
|
+
def default(cls) -> "JWTCoder":
|
|
152
|
+
svc, kid = _svc()
|
|
153
|
+
return cls(svc, kid)
|
|
154
|
+
|
|
155
|
+
async def async_sign(
|
|
156
|
+
self,
|
|
157
|
+
*,
|
|
158
|
+
sub: str,
|
|
159
|
+
tid: Optional[str] = None,
|
|
160
|
+
ttl: timedelta = _ACCESS_TTL,
|
|
161
|
+
typ: str = "access",
|
|
162
|
+
issuer: Optional[str] = None,
|
|
163
|
+
audience: Optional[Iterable[str] | str] = None,
|
|
164
|
+
cert_thumbprint: Optional[str] = None,
|
|
165
|
+
**extra: Any,
|
|
166
|
+
) -> str:
|
|
167
|
+
runtime = _load_runtime()
|
|
168
|
+
settings = runtime["settings"]
|
|
169
|
+
now = datetime.now(timezone.utc)
|
|
170
|
+
payload: Dict[str, Any] = {
|
|
171
|
+
"sub": sub,
|
|
172
|
+
"typ": typ,
|
|
173
|
+
"iat": int(now.timestamp()),
|
|
174
|
+
"exp": int((now + ttl).timestamp()),
|
|
175
|
+
"jti": str(uuid4()),
|
|
176
|
+
**extra,
|
|
177
|
+
}
|
|
178
|
+
if tid is not None:
|
|
179
|
+
payload["tid"] = tid
|
|
180
|
+
if getattr(settings, "enable_rfc8705", False) and cert_thumbprint is not None:
|
|
181
|
+
payload["cnf"] = {"x5t#S256": cert_thumbprint}
|
|
182
|
+
if getattr(settings, "enable_rfc9068", False) and typ == "access":
|
|
183
|
+
effective_issuer = issuer or settings.issuer
|
|
184
|
+
effective_audience = audience or settings.protected_resource_identifier
|
|
185
|
+
from tigrbl_auth.standards.oauth2.jwt_access_tokens import add_jwt_access_token_claims
|
|
186
|
+
|
|
187
|
+
payload = add_jwt_access_token_claims(payload, issuer=effective_issuer, audience=effective_audience)
|
|
188
|
+
issuer = effective_issuer
|
|
189
|
+
audience = effective_audience
|
|
190
|
+
token = await self._svc.mint(
|
|
191
|
+
payload,
|
|
192
|
+
alg=runtime["JWAAlg"].EDDSA,
|
|
193
|
+
kid=self._kid,
|
|
194
|
+
lifetime_s=int(ttl.total_seconds()),
|
|
195
|
+
subject=sub,
|
|
196
|
+
issuer=issuer,
|
|
197
|
+
audience=audience,
|
|
198
|
+
)
|
|
199
|
+
if getattr(settings, "enable_rfc7662", False):
|
|
200
|
+
claims = dict(payload)
|
|
201
|
+
claims.setdefault("sub", sub)
|
|
202
|
+
claims.setdefault("kind", typ)
|
|
203
|
+
if tid is not None:
|
|
204
|
+
claims.setdefault("tid", tid)
|
|
205
|
+
if issuer is not None:
|
|
206
|
+
claims.setdefault("iss", issuer)
|
|
207
|
+
if audience is not None:
|
|
208
|
+
claims.setdefault("aud", list(audience) if isinstance(audience, (list, tuple, set)) else audience)
|
|
209
|
+
runtime["register_token"](token, claims)
|
|
210
|
+
return token
|
|
211
|
+
|
|
212
|
+
def sign(self, **kwargs: Any) -> str:
|
|
213
|
+
return _run(self.async_sign(**kwargs))
|
|
214
|
+
|
|
215
|
+
async def async_sign_pair(self, *, sub: str, tid: str, cert_thumbprint: Optional[str] = None, **extra: Any) -> Tuple[str, str]:
|
|
216
|
+
access = await self.async_sign(sub=sub, tid=tid, cert_thumbprint=cert_thumbprint, **extra)
|
|
217
|
+
refresh = await self.async_sign(sub=sub, tid=tid, ttl=_REFRESH_TTL, typ="refresh", cert_thumbprint=cert_thumbprint, **extra)
|
|
218
|
+
return access, refresh
|
|
219
|
+
|
|
220
|
+
def sign_pair(self, **kwargs: Any) -> Tuple[str, str]:
|
|
221
|
+
return _run(self.async_sign_pair(**kwargs))
|
|
222
|
+
|
|
223
|
+
async def async_verify(self, token: str, *, cert_thumbprint: Optional[str] = None, audience: Optional[Iterable[str] | str] = None, issuer: Optional[str] = None) -> Dict[str, Any]:
|
|
224
|
+
runtime = _load_runtime()
|
|
225
|
+
settings = runtime["settings"]
|
|
226
|
+
if _header_alg(token) == "none":
|
|
227
|
+
raise InvalidTokenError("unsigned tokens are not accepted")
|
|
228
|
+
try:
|
|
229
|
+
payload = await self._svc.verify(token, audience=audience, issuer=issuer)
|
|
230
|
+
except Exception as exc:
|
|
231
|
+
raise InvalidTokenError("signature verification failed") from exc
|
|
232
|
+
payload = dict(payload)
|
|
233
|
+
if getattr(settings, "enable_rfc9700", False) and (audience is not None or issuer is not None):
|
|
234
|
+
if payload.get("iss") in {None, "", "placeholder-issuer"}:
|
|
235
|
+
raise InvalidTokenError("missing issuer")
|
|
236
|
+
aud = payload.get("aud")
|
|
237
|
+
if aud in {None, ""} or aud == []:
|
|
238
|
+
raise InvalidTokenError("missing audience")
|
|
239
|
+
cnf = payload.get("cnf") if isinstance(payload.get("cnf"), dict) else {}
|
|
240
|
+
if getattr(settings, "enable_rfc8705", False) and cnf.get("x5t#S256") is not None:
|
|
241
|
+
runtime["validate_certificate_binding"](payload, cert_thumbprint)
|
|
242
|
+
if runtime["is_revoked"](token):
|
|
243
|
+
raise InvalidTokenError("token revoked")
|
|
244
|
+
return payload
|
|
245
|
+
|
|
246
|
+
def verify(self, token: str, **kwargs: Any) -> Dict[str, Any]:
|
|
247
|
+
return _run(self.async_verify(token, **kwargs))
|
|
248
|
+
|
|
249
|
+
async def async_decode(self, token: str, *, verify_exp: bool = True, cert_thumbprint: Optional[str] = None, audience: Optional[Iterable[str] | str] = None, issuer: Optional[str] = None) -> Dict[str, Any]:
|
|
250
|
+
payload = await self.async_verify(token, cert_thumbprint=cert_thumbprint, audience=audience, issuer=issuer)
|
|
251
|
+
if verify_exp:
|
|
252
|
+
exp = payload.get("exp")
|
|
253
|
+
if exp is not None and int(exp) < int(datetime.now(timezone.utc).timestamp()):
|
|
254
|
+
raise InvalidTokenError("token expired")
|
|
255
|
+
return payload
|
|
256
|
+
|
|
257
|
+
def decode(self, token: str, *, verify_exp: bool = True, cert_thumbprint: Optional[str] = None, audience: Optional[Iterable[str] | str] = None, issuer: Optional[str] = None) -> Dict[str, Any]:
|
|
258
|
+
return _run(self.async_decode(token, verify_exp=verify_exp, cert_thumbprint=cert_thumbprint, audience=audience, issuer=issuer))
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
async def issue_persisted_token_pair(
|
|
262
|
+
*,
|
|
263
|
+
jwt: JWTCoder,
|
|
264
|
+
sub: str,
|
|
265
|
+
tid: str,
|
|
266
|
+
client_id: str | None,
|
|
267
|
+
cert_thumbprint: str | None = None,
|
|
268
|
+
refresh_family_id: str | None = None,
|
|
269
|
+
refresh_parent_token: str | None = None,
|
|
270
|
+
authorization_trace: dict[str, Any] | None = None,
|
|
271
|
+
delegation_provenance: dict[str, Any] | None = None,
|
|
272
|
+
**extra: Any,
|
|
273
|
+
) -> tuple[str, str]:
|
|
274
|
+
from tigrbl_auth.services.persistence import token_hash, upsert_token_record_async
|
|
275
|
+
|
|
276
|
+
access_token, refresh_token = await jwt.async_sign_pair(
|
|
277
|
+
sub=sub,
|
|
278
|
+
tid=tid,
|
|
279
|
+
cert_thumbprint=cert_thumbprint,
|
|
280
|
+
**extra,
|
|
281
|
+
)
|
|
282
|
+
access_claims = await jwt.async_decode(access_token, verify_exp=False)
|
|
283
|
+
refresh_claims = await jwt.async_decode(refresh_token, verify_exp=False)
|
|
284
|
+
if authorization_trace is not None:
|
|
285
|
+
access_claims["authorization_trace"] = deepcopy(authorization_trace)
|
|
286
|
+
refresh_claims["authorization_trace"] = deepcopy(authorization_trace)
|
|
287
|
+
if delegation_provenance is not None:
|
|
288
|
+
access_claims["delegation_provenance"] = deepcopy(delegation_provenance)
|
|
289
|
+
refresh_claims["delegation_provenance"] = deepcopy(delegation_provenance)
|
|
290
|
+
if client_id:
|
|
291
|
+
access_claims["client_id"] = client_id
|
|
292
|
+
refresh_claims["client_id"] = client_id
|
|
293
|
+
family_id = refresh_family_id or str(uuid4())
|
|
294
|
+
refresh_parent_hash = token_hash(refresh_parent_token) if refresh_parent_token else None
|
|
295
|
+
await upsert_token_record_async(
|
|
296
|
+
access_token,
|
|
297
|
+
access_claims,
|
|
298
|
+
token_kind="access",
|
|
299
|
+
token_type_hint="access_token",
|
|
300
|
+
refresh_family_id=family_id,
|
|
301
|
+
refresh_parent_hash=refresh_parent_hash,
|
|
302
|
+
)
|
|
303
|
+
await upsert_token_record_async(
|
|
304
|
+
refresh_token,
|
|
305
|
+
refresh_claims,
|
|
306
|
+
token_kind="refresh",
|
|
307
|
+
token_type_hint="refresh_token",
|
|
308
|
+
refresh_family_id=family_id,
|
|
309
|
+
refresh_parent_hash=refresh_parent_hash,
|
|
310
|
+
)
|
|
311
|
+
return access_token, refresh_token
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _normalize_refresh_audience(value: Any) -> str | list[str] | None:
|
|
315
|
+
if value is None or value == "":
|
|
316
|
+
return None
|
|
317
|
+
if isinstance(value, (str, list)):
|
|
318
|
+
return value
|
|
319
|
+
if isinstance(value, tuple):
|
|
320
|
+
return list(value)
|
|
321
|
+
return str(value)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
async def redeem_refresh_token(
|
|
325
|
+
*,
|
|
326
|
+
jwt: JWTCoder,
|
|
327
|
+
refresh_token: str,
|
|
328
|
+
client_id: str,
|
|
329
|
+
cert_thumbprint: str | None = None,
|
|
330
|
+
requested_audience: str | None = None,
|
|
331
|
+
token_type: str = "bearer",
|
|
332
|
+
) -> dict[str, Any]:
|
|
333
|
+
from tigrbl_auth.services.persistence import (
|
|
334
|
+
get_token_record_async,
|
|
335
|
+
mark_token_used_async,
|
|
336
|
+
revoke_refresh_family_async,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
record = await get_token_record_async(refresh_token)
|
|
340
|
+
if record is None:
|
|
341
|
+
raise InvalidRefreshTokenError("refresh token was not issued by this repository")
|
|
342
|
+
if record.token_kind != "refresh":
|
|
343
|
+
raise InvalidRefreshTokenError("presented token is not a refresh token")
|
|
344
|
+
if str(record.client_id or "") not in {"", client_id}:
|
|
345
|
+
raise InvalidRefreshTokenError("refresh token client binding mismatch")
|
|
346
|
+
family_id = str(record.refresh_family_id or "")
|
|
347
|
+
if record.used_at is not None or record.refresh_successor_hash:
|
|
348
|
+
if family_id:
|
|
349
|
+
await revoke_refresh_family_async(family_id, reuse_token=refresh_token)
|
|
350
|
+
raise RefreshTokenReuseError("refresh token replay detected")
|
|
351
|
+
if not record.active or record.revoked_at is not None:
|
|
352
|
+
raise InvalidRefreshTokenError("refresh token is inactive")
|
|
353
|
+
|
|
354
|
+
claims = await jwt.async_decode(refresh_token, verify_exp=True, cert_thumbprint=cert_thumbprint)
|
|
355
|
+
if claims.get("typ") != "refresh":
|
|
356
|
+
raise InvalidRefreshTokenError("presented token is not a refresh token")
|
|
357
|
+
if client_id and str(claims.get("client_id") or record.client_id or "") not in {"", client_id}:
|
|
358
|
+
raise InvalidRefreshTokenError("refresh token client binding mismatch")
|
|
359
|
+
|
|
360
|
+
stored_audience = _normalize_refresh_audience((record.claims or {}).get("aud") if isinstance(record.claims, dict) else None)
|
|
361
|
+
if requested_audience and stored_audience not in {None, "", requested_audience}:
|
|
362
|
+
raise InvalidRefreshTokenError("refresh token audience cannot be widened or changed")
|
|
363
|
+
|
|
364
|
+
preserved_claims = deepcopy(record.claims or claims)
|
|
365
|
+
preserved_claims.pop("iat", None)
|
|
366
|
+
preserved_claims.pop("exp", None)
|
|
367
|
+
preserved_claims.pop("nbf", None)
|
|
368
|
+
preserved_claims.pop("jti", None)
|
|
369
|
+
preserved_claims.pop("typ", None)
|
|
370
|
+
|
|
371
|
+
next_audience = requested_audience or _normalize_refresh_audience(preserved_claims.pop("aud", None))
|
|
372
|
+
next_scope = preserved_claims.pop("scope", None)
|
|
373
|
+
next_issuer = preserved_claims.pop("iss", None)
|
|
374
|
+
preserved_claims.pop("sub", None)
|
|
375
|
+
preserved_claims.pop("tid", None)
|
|
376
|
+
preserved_claims.pop("client_id", None)
|
|
377
|
+
preserved_claims.pop("cnf", None)
|
|
378
|
+
confirmation_claim = claims.get("cnf")
|
|
379
|
+
extra_claims = preserved_claims or {}
|
|
380
|
+
if confirmation_claim:
|
|
381
|
+
extra_claims["cnf"] = confirmation_claim
|
|
382
|
+
|
|
383
|
+
access_token, next_refresh_token = await issue_persisted_token_pair(
|
|
384
|
+
jwt=jwt,
|
|
385
|
+
sub=str(claims.get("sub") or record.subject),
|
|
386
|
+
tid=str(claims.get("tid") or record.tenant_id or ""),
|
|
387
|
+
client_id=client_id,
|
|
388
|
+
cert_thumbprint=cert_thumbprint,
|
|
389
|
+
refresh_family_id=family_id or None,
|
|
390
|
+
refresh_parent_token=refresh_token,
|
|
391
|
+
scope=next_scope,
|
|
392
|
+
issuer=next_issuer,
|
|
393
|
+
audience=next_audience,
|
|
394
|
+
**extra_claims,
|
|
395
|
+
)
|
|
396
|
+
await mark_token_used_async(refresh_token, successor_token=next_refresh_token)
|
|
397
|
+
return {
|
|
398
|
+
"access_token": access_token,
|
|
399
|
+
"refresh_token": next_refresh_token,
|
|
400
|
+
"token_type": token_type,
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
# -----------------------------
|
|
406
|
+
# Operator-plane wrappers
|
|
407
|
+
# -----------------------------
|
|
408
|
+
|
|
409
|
+
def parse_token_patch(raw_patch: dict[str, Any] | None) -> dict[str, Any]:
|
|
410
|
+
patch = dict(raw_patch or {})
|
|
411
|
+
patch.setdefault("issued_at", patch.get("iat") or datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"))
|
|
412
|
+
if "token_type" not in patch and "typ" in patch:
|
|
413
|
+
patch["token_type"] = patch["typ"]
|
|
414
|
+
return patch
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def list_operator_tokens_for_context(context, *, status_filter: str | None = None, filter_expr: str | None = None, sort: str = "id", offset: int = 0, limit: int = 50):
|
|
418
|
+
return list_tokens_for_context(context, status_filter=status_filter, filter_expr=filter_expr, sort=sort, offset=offset, limit=limit)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def get_operator_token_for_context(context, *, record_id: str):
|
|
422
|
+
return get_token_for_context(context, record_id=record_id)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def introspect_operator_token_for_context(context, *, record_id: str):
|
|
426
|
+
return introspect_token_for_context(context, record_id=record_id)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def revoke_operator_token_for_context(context, *, record_id: str):
|
|
430
|
+
return revoke_token_for_context(context, record_id=record_id)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def revoke_all_operator_tokens_for_context(context, *, status_filter: str | None = None, filter_expr: str | None = None):
|
|
434
|
+
return revoke_all_tokens_for_context(context, status_filter=status_filter, filter_expr=filter_expr)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def exchange_operator_token_for_context(context, *, subject_token: str | None, requested_token_type: str | None = None, audience: str | None = None, resource: str | None = None, actor_token: str | None = None, extras: dict[str, Any] | None = None):
|
|
438
|
+
return exchange_token_for_context(context, subject_token=subject_token, requested_token_type=requested_token_type, audience=audience, resource=resource, actor_token=actor_token, extras=extras)
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
__all__ = [
|
|
442
|
+
"InvalidRefreshTokenError",
|
|
443
|
+
"JWTCoder",
|
|
444
|
+
"RefreshTokenError",
|
|
445
|
+
"RefreshTokenReuseError",
|
|
446
|
+
"exchange_operator_token_for_context",
|
|
447
|
+
"get_operator_token_for_context",
|
|
448
|
+
"introspect_operator_token_for_context",
|
|
449
|
+
"issue_persisted_token_pair",
|
|
450
|
+
"list_operator_tokens_for_context",
|
|
451
|
+
"parse_token_patch",
|
|
452
|
+
"redeem_refresh_token",
|
|
453
|
+
"revoke_all_operator_tokens_for_context",
|
|
454
|
+
"revoke_operator_token_for_context",
|
|
455
|
+
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tigrbl-identity-credentials
|
|
3
|
+
Version: 0.4.0.dev1
|
|
4
|
+
Summary: Credential lifecycle and verification surfaces for the Tigrbl identity package suite.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10,<3.15
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# tigrbl-identity-credentials
|
|
16
|
+
|
|
17
|
+
Credential lifecycle and verification surfaces for the Tigrbl identity package suite.
|
|
18
|
+
|
|
19
|
+
This package uses the independent import root `tigrbl_identity_credentials`.
|
|
20
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
tigrbl_identity_credentials/__init__.py,sha256=KYpdJ0xXeyDlxIJpueAzn-xjOwfxVkvV2vN-D0kuPpw,153
|
|
2
|
+
tigrbl_identity_credentials/adapters/__init__.py,sha256=aCn_a-TLFPlgCStOyczwWOnEc79UZMMZ8Va3ak2yxo8,412
|
|
3
|
+
tigrbl_identity_credentials/adapters/local.py,sha256=6R6AJTCGIA_8bNzuG0_CIM1kF9D6YBvs81a8KCC9dtc,1709
|
|
4
|
+
tigrbl_identity_credentials/adapters/remote.py,sha256=a_-1WnK6ZOOd1RH_eKUAWJgz_M5a2uYF3HMLL6qLP9U,5645
|
|
5
|
+
tigrbl_identity_credentials/auth_context.py,sha256=v4gZgsyNtpCEDdpilzzTB7WMu73tqFyxCm8zZkzGYyk,924
|
|
6
|
+
tigrbl_identity_credentials/authenticate.py,sha256=0O6pbyLKTA99omYJkuZVp54p_LOm28_VUJptCnZ0O3w,311
|
|
7
|
+
tigrbl_identity_credentials/authenticators.py,sha256=ZnKG_gPAyTuTqYXIDU9_9Kc5IEF_X8__rcD0a0W74UE,4184
|
|
8
|
+
tigrbl_identity_credentials/backends.py,sha256=6FyeWJK41ZFItifTsFO2opfOFIlNr_igOKaWT2dt_To,3132
|
|
9
|
+
tigrbl_identity_credentials/session_service.py,sha256=NHJutF3sh_rEGwgt87B6h-Vxp1pdx3HMQBOLzUHrsoA,7685
|
|
10
|
+
tigrbl_identity_credentials/token_service.py,sha256=rq5LulYLJj-lH4eEvghpyzMMZ2B8z0clm2DlMG4Sim0,18490
|
|
11
|
+
tigrbl_identity_credentials-0.4.0.dev1.dist-info/METADATA,sha256=FZgp7Cf1XsvmeHyCYWNJIj3Szd3bOEaNB1vH4rvi5d8,772
|
|
12
|
+
tigrbl_identity_credentials-0.4.0.dev1.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
|
|
13
|
+
tigrbl_identity_credentials-0.4.0.dev1.dist-info/RECORD,,
|