tigrbl-identity-credentials 0.4.0.dev1__tar.gz → 0.4.0.dev2__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.
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/PKG-INFO +1 -1
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/pyproject.toml +13 -13
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/adapters/__init__.py +14 -14
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/backends.py +79 -79
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/token_service.py +243 -243
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/README.md +0 -0
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/__init__.py +0 -0
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/adapters/local.py +0 -0
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/adapters/remote.py +0 -0
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/auth_context.py +0 -0
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/authenticate.py +0 -0
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/authenticators.py +0 -0
- {tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/src/tigrbl_identity_credentials/session_service.py +0 -0
{tigrbl_identity_credentials-0.4.0.dev1 → tigrbl_identity_credentials-0.4.0.dev2}/pyproject.toml
RENAMED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
[project]
|
|
2
|
-
name = "tigrbl-identity-credentials"
|
|
3
|
-
version = "0.4.0.
|
|
4
|
-
description = "Credential lifecycle and verification surfaces for the Tigrbl identity package suite."
|
|
5
|
-
readme = "README.md"
|
|
6
|
-
requires-python = ">=3.10,<3.15"
|
|
7
|
-
license = "Apache-2.0"
|
|
8
|
-
|
|
9
|
-
[build-system]
|
|
10
|
-
requires = ["poetry-core>=1.0.0"]
|
|
11
|
-
build-backend = "poetry.core.masonry.api"
|
|
12
|
-
|
|
13
|
-
[tool.poetry]
|
|
14
|
-
packages = [{ include = "tigrbl_identity_credentials", from = "src" }]
|
|
2
|
+
name = "tigrbl-identity-credentials"
|
|
3
|
+
version = "0.4.0.dev2"
|
|
4
|
+
description = "Credential lifecycle and verification surfaces for the Tigrbl identity package suite."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10,<3.15"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
|
|
9
|
+
[build-system]
|
|
10
|
+
requires = ["poetry-core>=1.0.0"]
|
|
11
|
+
build-backend = "poetry.core.masonry.api"
|
|
12
|
+
|
|
13
|
+
[tool.poetry]
|
|
14
|
+
packages = [{ include = "tigrbl_identity_credentials", from = "src" }]
|
|
@@ -1,14 +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"]
|
|
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"]
|
|
@@ -1,79 +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"]
|
|
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"]
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"""JWT minting/verification and operator token wrappers."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
1
|
+
"""JWT minting/verification and operator token wrappers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
5
|
import asyncio
|
|
6
6
|
import base64
|
|
7
7
|
import json
|
|
@@ -14,17 +14,17 @@ from typing import Any, Dict, Iterable, Optional, Tuple
|
|
|
14
14
|
from uuid import uuid4
|
|
15
15
|
|
|
16
16
|
from tigrbl_auth.errors import InvalidTokenError
|
|
17
|
-
|
|
17
|
+
|
|
18
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
|
-
|
|
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
28
|
_ACCESS_TTL = timedelta(minutes=60)
|
|
29
29
|
_REFRESH_TTL = timedelta(days=7)
|
|
30
30
|
|
|
@@ -39,52 +39,52 @@ class InvalidRefreshTokenError(RefreshTokenError):
|
|
|
39
39
|
|
|
40
40
|
class RefreshTokenReuseError(RefreshTokenError):
|
|
41
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)
|
|
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
88
|
def _svc() -> Tuple[Any, str]:
|
|
89
89
|
runtime = _load_runtime()
|
|
90
90
|
kp = _provider()
|
|
@@ -100,73 +100,73 @@ def _svc() -> Tuple[Any, str]:
|
|
|
100
100
|
else:
|
|
101
101
|
spec = runtime["KeySpec"](
|
|
102
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)
|
|
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
170
|
payload: Dict[str, Any] = {
|
|
171
171
|
"sub": sub,
|
|
172
172
|
"typ": typ,
|
|
@@ -175,85 +175,85 @@ class JWTCoder:
|
|
|
175
175
|
"jti": str(uuid4()),
|
|
176
176
|
**extra,
|
|
177
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
|
-
|
|
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
220
|
def sign_pair(self, **kwargs: Any) -> Tuple[str, str]:
|
|
221
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
|
-
|
|
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
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
258
|
return _run(self.async_decode(token, verify_exp=verify_exp, cert_thumbprint=cert_thumbprint, audience=audience, issuer=issuer))
|
|
259
259
|
|
|
@@ -399,45 +399,45 @@ async def redeem_refresh_token(
|
|
|
399
399
|
"refresh_token": next_refresh_token,
|
|
400
400
|
"token_type": token_type,
|
|
401
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
|
-
|
|
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
441
|
__all__ = [
|
|
442
442
|
"InvalidRefreshTokenError",
|
|
443
443
|
"JWTCoder",
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|