rn-forge-auth 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rohit Narayanan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: rn-forge-auth
3
+ Version: 0.1.0
4
+ Summary: Authentication primitives for Python programming
5
+ Author: Rohit Narayanan
6
+ Author-email: Rohit Narayanan <rohit.nn@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: rn-forge-commons>=0.8.0,<0.9
17
+ Requires-Dist: rn-forge-web>=0.3.0,<0.4
18
+ Requires-Dist: authlib>=1.9.1 ; extra == 'oidc'
19
+ Requires-Dist: joserfc>=1.7.7 ; extra == 'oidc'
20
+ Requires-Dist: pyjwt[crypto]>=2.15.0 ; extra == 'oidc'
21
+ Requires-Dist: requests>=2.34.2 ; extra == 'oidc'
22
+ Requires-Dist: redis>=8.1.0 ; extra == 'redis'
23
+ Requires-Python: >=3.14
24
+ Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-auth/latest/
25
+ Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-auth
26
+ Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-auth/CHANGELOG.md
27
+ Project-URL: Issues, https://github.com/rn-forge/pykit/issues
28
+ Provides-Extra: oidc
29
+ Provides-Extra: redis
30
+ Description-Content-Type: text/markdown
31
+
32
+ # rn-forge-auth
33
+
34
+ [Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-auth/latest/)
35
+ ·
36
+ [Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-auth/CHANGELOG.md)
37
+ · [Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-auth) ·
38
+ [All pykit packages](https://rn-forge.github.io/pykit/)
39
+
40
+ Authentication and authorization primitives for Python programming, built on
41
+ `rn-forge-web`. The base install carries no third-party dependencies.
42
+
43
+ | Module | Extra | Holds |
44
+ | -- | -- | -- |
45
+ | `rn_forge.auth` | none | The core: the identity, account-resolution and authorization-context contracts, `Principal`, `Requirement`, `Authenticator`, `AsyncAuthenticator`, `Authorizer`, `ScopeAuthorizer`, `principal_from_claims`, permissions and the scope limit, `AuthorizationContextCache`, `ResourcePolicy`, the transaction, session and replay stores (in memory), `validate_return_to`, `SessionBody`, `LoginFlow` with `LoginFailed` and `LoginRequest`, and the local login providers of `rn_forge.auth.local` (`PasswordIdentityProvider`, `DevelopmentIdentityProvider`). The facade re-exports the core only. |
46
+ | `rn_forge.auth.oidc` | `oidc` (`pyjwt[crypto]`, `authlib`, `joserfc`, `requests`) | `OidcProvider` (OIDC and OAuth 2.0 login, with RP-initiated logout), `BackchannelLogout`, `OidcAuthenticator` and the access-token, ID-token and logout-token verifiers (`JwtVerifier`, `IdTokenVerifier`, `LogoutTokenVerifier`). The core never imports it; `.importlinter` proves that. |
47
+ | `rn_forge.auth.redis` | `redis` | `RedisTransactionStore`, `RedisSessionStore`, `RedisReplayStore` and `RedisAuthorizationVersions`. The core never imports it either. |
48
+ | `rn_forge.auth.testing` | `oidc` | `FakeOidcProvider` and `Faults`, an offline OIDC provider for tests. The core never imports it. |
49
+
50
+ Start with the [guides](https://rn-forge.github.io/pykit/packages/rn-forge-auth/latest/guides/usage.html).
@@ -0,0 +1,19 @@
1
+ # rn-forge-auth
2
+
3
+ [Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-auth/latest/)
4
+ ·
5
+ [Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-auth/CHANGELOG.md)
6
+ · [Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-auth) ·
7
+ [All pykit packages](https://rn-forge.github.io/pykit/)
8
+
9
+ Authentication and authorization primitives for Python programming, built on
10
+ `rn-forge-web`. The base install carries no third-party dependencies.
11
+
12
+ | Module | Extra | Holds |
13
+ | -- | -- | -- |
14
+ | `rn_forge.auth` | none | The core: the identity, account-resolution and authorization-context contracts, `Principal`, `Requirement`, `Authenticator`, `AsyncAuthenticator`, `Authorizer`, `ScopeAuthorizer`, `principal_from_claims`, permissions and the scope limit, `AuthorizationContextCache`, `ResourcePolicy`, the transaction, session and replay stores (in memory), `validate_return_to`, `SessionBody`, `LoginFlow` with `LoginFailed` and `LoginRequest`, and the local login providers of `rn_forge.auth.local` (`PasswordIdentityProvider`, `DevelopmentIdentityProvider`). The facade re-exports the core only. |
15
+ | `rn_forge.auth.oidc` | `oidc` (`pyjwt[crypto]`, `authlib`, `joserfc`, `requests`) | `OidcProvider` (OIDC and OAuth 2.0 login, with RP-initiated logout), `BackchannelLogout`, `OidcAuthenticator` and the access-token, ID-token and logout-token verifiers (`JwtVerifier`, `IdTokenVerifier`, `LogoutTokenVerifier`). The core never imports it; `.importlinter` proves that. |
16
+ | `rn_forge.auth.redis` | `redis` | `RedisTransactionStore`, `RedisSessionStore`, `RedisReplayStore` and `RedisAuthorizationVersions`. The core never imports it either. |
17
+ | `rn_forge.auth.testing` | `oidc` | `FakeOidcProvider` and `Faults`, an offline OIDC provider for tests. The core never imports it. |
18
+
19
+ Start with the [guides](https://rn-forge.github.io/pykit/packages/rn-forge-auth/latest/guides/usage.html).
@@ -0,0 +1,100 @@
1
+ [project]
2
+ name = "rn-forge-auth"
3
+ version = "0.1.0"
4
+ description = "Authentication primitives for Python programming"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ classifiers = [
9
+ "Development Status :: 3 - Alpha",
10
+ "Intended Audience :: Developers",
11
+ "Operating System :: OS Independent",
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3 :: Only",
14
+ "Programming Language :: Python :: 3.14",
15
+ "Typing :: Typed",
16
+ ]
17
+ requires-python = ">=3.14"
18
+ dependencies = [
19
+ "rn-forge-commons>=0.8.0,<0.9",
20
+ "rn-forge-web>=0.3.0,<0.4",
21
+ ]
22
+
23
+ [[project.authors]]
24
+ name = "Rohit Narayanan"
25
+ email = "rohit.nn@gmail.com"
26
+
27
+ [project.optional-dependencies]
28
+ oidc = [
29
+ "authlib>=1.9.1",
30
+ "joserfc>=1.7.7",
31
+ "pyjwt[crypto]>=2.15.0",
32
+ "requests>=2.34.2",
33
+ ]
34
+ redis = ["redis>=8.1.0"]
35
+
36
+ [project.urls]
37
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-auth/latest/"
38
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-auth"
39
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-auth/CHANGELOG.md"
40
+ Issues = "https://github.com/rn-forge/pykit/issues"
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.11.28,<0.12.0"]
44
+ build-backend = "uv_build"
45
+
46
+ [tool.uv.build-backend]
47
+ module-name = "rn_forge.auth"
48
+
49
+ [tool.uv.sources.rn-forge-auth]
50
+ workspace = true
51
+
52
+ [tool.uv.sources.rn-forge-commons]
53
+ workspace = true
54
+
55
+ [tool.uv.sources.rn-forge-web]
56
+ workspace = true
57
+
58
+ [tool.workspace-ci]
59
+ adapters = [
60
+ "oidc",
61
+ "redis",
62
+ ]
63
+
64
+ [tool.workspace-ci.redis]
65
+ env = "RN_FORGE_AUTH_REDIS_URL"
66
+
67
+ [tool.workspace-ci.smoke]
68
+ modules = ["rn_forge.auth"]
69
+
70
+ [tool.workspace-ci.smoke.extras]
71
+ oidc = [
72
+ "rn_forge.auth.oidc",
73
+ "rn_forge.auth.testing",
74
+ ]
75
+ redis = ["rn_forge.auth.redis"]
76
+
77
+ [tool.pytest.ini_options]
78
+ addopts = "-ra --import-mode=importlib"
79
+ markers = [
80
+ "unit: fast isolated tests",
81
+ "broker: needs Keycloak at RN_FORGE_AUTH_KEYCLOAK_URL",
82
+ ]
83
+
84
+ [dependency-groups]
85
+ dev = [
86
+ "assertpy>=1.1",
87
+ "pyright>=1.1.411",
88
+ "pytest>=9.1.1",
89
+ "pytest-cov>=7.1.0",
90
+ "pytest-randomly>=4.1.0",
91
+ "rn-forge-auth[oidc,redis]",
92
+ "ruff>=0.15.21",
93
+ "types-authlib>=1.8.0",
94
+ ]
95
+ docs = [
96
+ "mkdocs>=1.6.1",
97
+ "mkdocs-material>=9.7.6",
98
+ "mkdocstrings[python]>=1.0.6",
99
+ "rn-forge-auth[oidc,redis]",
100
+ ]
@@ -0,0 +1,95 @@
1
+ [project]
2
+ name = "rn-forge-auth"
3
+ version = "0.1.0"
4
+ description = "Authentication primitives for Python programming"
5
+ readme = "README.md"
6
+ authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "Operating System :: OS Independent",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3 :: Only",
15
+ "Programming Language :: Python :: 3.14",
16
+ "Typing :: Typed",
17
+ ]
18
+ requires-python = ">=3.14"
19
+ # Internal requirements are version ranges (ADR-0004).
20
+ dependencies = [
21
+ "rn-forge-commons>=0.8.0,<0.9",
22
+ "rn-forge-web>=0.3.0,<0.4",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ # Bearer and logout tokens are verified with PyJWT, keys from its `PyJWKClient`;
27
+ # ID tokens with Authlib's core over joserfc. Authlib's OAuth2Session needs
28
+ # requests, which Authlib does not declare.
29
+ oidc = [
30
+ "authlib>=1.9.1",
31
+ "joserfc>=1.7.7",
32
+ "pyjwt[crypto]>=2.15.0",
33
+ "requests>=2.34.2",
34
+ ]
35
+ # GETDEL, SET NX and INCR need Redis 6.2 or later.
36
+ redis = [
37
+ "redis>=8.1.0",
38
+ ]
39
+
40
+ [project.urls]
41
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-auth/latest/"
42
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-auth"
43
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-auth/CHANGELOG.md"
44
+ Issues = "https://github.com/rn-forge/pykit/issues"
45
+
46
+ [build-system]
47
+ requires = ["uv_build>=0.11.28,<0.12.0"]
48
+ build-backend = "uv_build"
49
+
50
+ [tool.uv.build-backend]
51
+ module-name = "rn_forge.auth"
52
+
53
+ [tool.uv.sources]
54
+ rn-forge-auth = { workspace = true }
55
+ rn-forge-commons = { workspace = true }
56
+ rn-forge-web = { workspace = true }
57
+
58
+ [tool.workspace-ci]
59
+ adapters = ["oidc", "redis"]
60
+
61
+ [tool.workspace-ci.redis]
62
+ # The Redis tests read this URL and skip without it.
63
+ env = "RN_FORGE_AUTH_REDIS_URL"
64
+
65
+ [tool.workspace-ci.smoke]
66
+ modules = ["rn_forge.auth"]
67
+
68
+ [tool.workspace-ci.smoke.extras]
69
+ oidc = ["rn_forge.auth.oidc", "rn_forge.auth.testing"]
70
+ redis = ["rn_forge.auth.redis"]
71
+
72
+ [tool.pytest.ini_options]
73
+ addopts = "-ra --import-mode=importlib"
74
+ markers = [
75
+ "unit: fast isolated tests",
76
+ "broker: needs Keycloak at RN_FORGE_AUTH_KEYCLOAK_URL",
77
+ ]
78
+
79
+ [dependency-groups]
80
+ dev = [
81
+ "assertpy>=1.1",
82
+ "pyright>=1.1.411",
83
+ "pytest>=9.1.1",
84
+ "pytest-cov>=7.1.0",
85
+ "pytest-randomly>=4.1.0",
86
+ "rn-forge-auth[oidc,redis]",
87
+ "ruff>=0.15.21",
88
+ "types-authlib>=1.8.0",
89
+ ]
90
+ docs = [
91
+ "mkdocs>=1.6.1",
92
+ "mkdocs-material>=9.7.6",
93
+ "mkdocstrings[python]>=1.0.6",
94
+ "rn-forge-auth[oidc,redis]",
95
+ ]
@@ -0,0 +1,112 @@
1
+ """Authentication primitives.
2
+
3
+ The OIDC adapter, :mod:`rn_forge.auth.oidc`, and the Redis adapter,
4
+ :mod:`rn_forge.auth.redis`, need the ``oidc`` and ``redis`` extras and are
5
+ imported directly.
6
+ """
7
+
8
+ from rn_forge.auth.accounts import AccountRejected, AccountResolver
9
+ from rn_forge.auth.audit import AUDIT_LOGGER, audit
10
+ from rn_forge.auth.authorization import (
11
+ AsyncAuthenticator,
12
+ Authenticator,
13
+ Authorizer,
14
+ ScopeAuthorizer,
15
+ )
16
+ from rn_forge.auth.context import AuthorizationContext, AuthorizationContextProvider
17
+ from rn_forge.auth.context_cache import (
18
+ AccountStateWriter,
19
+ AuthorizationContextCache,
20
+ AuthorizationVersions,
21
+ InMemoryAuthorizationVersions,
22
+ )
23
+ from rn_forge.auth.flow import CompletedLogin, LoginFailed, LoginFlow
24
+ from rn_forge.auth.identity import (
25
+ ExternalIdentity,
26
+ IdentityProvider,
27
+ LoginRequest,
28
+ LoginStart,
29
+ LoginTransaction,
30
+ ProviderKind,
31
+ SessionInfo,
32
+ )
33
+ from rn_forge.auth.local import (
34
+ DevelopmentAccount,
35
+ DevelopmentIdentityProvider,
36
+ DevelopmentModeRequired,
37
+ PasswordIdentityProvider,
38
+ PasswordVerifier,
39
+ )
40
+ from rn_forge.auth.permissions import (
41
+ DEFAULT_PERMISSION_ACTION_MAP,
42
+ effective_permissions,
43
+ requirement_for,
44
+ )
45
+ from rn_forge.auth.policy import ResourcePolicy
46
+ from rn_forge.auth.principal import (
47
+ Mechanism,
48
+ Principal,
49
+ Requirement,
50
+ principal_from_claims,
51
+ )
52
+ from rn_forge.auth.redirects import InvalidReturnTo, validate_return_to
53
+ from rn_forge.auth.session_body import CALLBACK_ERRORS, CallbackError, SessionBody
54
+ from rn_forge.auth.stores import (
55
+ InMemoryReplayStore,
56
+ InMemorySessionStore,
57
+ InMemoryTransactionStore,
58
+ ReplayStore,
59
+ SessionStore,
60
+ TransactionStore,
61
+ )
62
+
63
+ __all__ = [
64
+ "AUDIT_LOGGER",
65
+ "CALLBACK_ERRORS",
66
+ "DEFAULT_PERMISSION_ACTION_MAP",
67
+ "AccountRejected",
68
+ "AccountResolver",
69
+ "AccountStateWriter",
70
+ "AsyncAuthenticator",
71
+ "Authenticator",
72
+ "AuthorizationContext",
73
+ "AuthorizationContextCache",
74
+ "AuthorizationContextProvider",
75
+ "AuthorizationVersions",
76
+ "Authorizer",
77
+ "CallbackError",
78
+ "CompletedLogin",
79
+ "DevelopmentAccount",
80
+ "DevelopmentIdentityProvider",
81
+ "DevelopmentModeRequired",
82
+ "ExternalIdentity",
83
+ "IdentityProvider",
84
+ "InMemoryAuthorizationVersions",
85
+ "InMemoryReplayStore",
86
+ "InMemorySessionStore",
87
+ "InMemoryTransactionStore",
88
+ "InvalidReturnTo",
89
+ "LoginFailed",
90
+ "LoginFlow",
91
+ "LoginRequest",
92
+ "LoginStart",
93
+ "LoginTransaction",
94
+ "Mechanism",
95
+ "PasswordIdentityProvider",
96
+ "PasswordVerifier",
97
+ "Principal",
98
+ "ProviderKind",
99
+ "ReplayStore",
100
+ "Requirement",
101
+ "ResourcePolicy",
102
+ "ScopeAuthorizer",
103
+ "SessionBody",
104
+ "SessionInfo",
105
+ "SessionStore",
106
+ "TransactionStore",
107
+ "audit",
108
+ "effective_permissions",
109
+ "principal_from_claims",
110
+ "requirement_for",
111
+ "validate_return_to",
112
+ ]
@@ -0,0 +1,44 @@
1
+ """Account resolution contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol, runtime_checkable
6
+
7
+ from rn_forge.auth.identity import ExternalIdentity
8
+ from rn_forge.commons import AppException
9
+
10
+ __all__ = ["AccountRejected", "AccountResolver"]
11
+
12
+
13
+ class AccountRejected(AppException):
14
+ """A login was refused by the :class:`AccountResolver`.
15
+
16
+ The reason is for logs and is never shown to the user.
17
+
18
+ Args:
19
+ reason: A short description of why the login was refused.
20
+ """
21
+
22
+ def __init__(self, reason: str) -> None:
23
+ super().__init__("Account rejected: {}", reason, reason=reason)
24
+ self.reason = reason
25
+
26
+
27
+ @runtime_checkable
28
+ class AccountResolver(Protocol):
29
+ """Maps an external identity to an internal account."""
30
+
31
+ def resolve(self, identity: ExternalIdentity) -> str:
32
+ """Link, provision or reject a login, and return the account ID.
33
+
34
+ Raises:
35
+ AccountRejected: The login may not proceed.
36
+ """
37
+ ...
38
+
39
+ def lookup(self, issuer: str, subject: str) -> str | None:
40
+ """Return the account ID linked to *issuer* and *subject*, if any.
41
+
42
+ Never provisions.
43
+ """
44
+ ...
@@ -0,0 +1,29 @@
1
+ """Audit events of the auth surface, on one :class:`AppLogger` channel.
2
+
3
+ An event is one ``INFO`` record on the ``rn_forge.audit.auth`` logger:
4
+ ``audit event=<name> key='value' ...``. Fields are account IDs, provider IDs,
5
+ codes and short reasons; callers never pass a token, code, assertion, password
6
+ or email address.
7
+
8
+ Both framework bindings emit these events with the same names and fields; an
9
+ :class:`~rn_forge.auth.AccountResolver` that provisions accounts records
10
+ ``account.provisioned`` (fields ``account_id`` and ``provider``) with
11
+ :func:`audit` when its account is committed.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Final
17
+
18
+ from rn_forge.commons.logging import AppLogger
19
+
20
+ __all__ = ["AUDIT_LOGGER", "audit"]
21
+
22
+ AUDIT_LOGGER: Final = "rn_forge.audit.auth"
23
+ _CHANNEL: Final = AppLogger.get_logger(AUDIT_LOGGER)
24
+
25
+
26
+ def audit(event: str, **fields: object) -> None:
27
+ """Record the audit event *event* with *fields*; ``None`` fields are left out."""
28
+ detail = " ".join(f"{k}={v!r}" for k, v in fields.items() if v is not None)
29
+ _CHANNEL.info("audit event={} {}", event, detail) # brace-style log format
@@ -0,0 +1,91 @@
1
+ """Authenticator and authorizer contracts.
2
+
3
+ Missing or invalid credentials produce a 401 challenge; an authenticated
4
+ principal without sufficient access produces 403. Verification details must
5
+ not be exposed in the 401 response.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Mapping
11
+ from typing import Any, Protocol, runtime_checkable
12
+
13
+ from rn_forge.auth.principal import Principal, Requirement
14
+ from rn_forge.web.auth import Credentials
15
+ from rn_forge.web.exceptions import PermissionDenied
16
+
17
+ __all__ = [
18
+ "AsyncAuthenticator",
19
+ "Authenticator",
20
+ "Authorizer",
21
+ "ScopeAuthorizer",
22
+ ]
23
+
24
+
25
+ @runtime_checkable
26
+ class Authenticator(Protocol):
27
+ """Turns raw credentials into a verified :class:`Principal`."""
28
+
29
+ def authenticate(self, *, credentials: Credentials) -> Principal:
30
+ """Verify *credentials*.
31
+
32
+ Raises:
33
+ AuthenticationFailed: The credentials are absent, malformed or
34
+ invalid. The message must not say which.
35
+ """
36
+ ...
37
+
38
+
39
+ @runtime_checkable
40
+ class AsyncAuthenticator(Protocol):
41
+ """Asynchronous counterpart of :class:`Authenticator`."""
42
+
43
+ async def authenticate(self, *, credentials: Credentials) -> Principal:
44
+ """See :meth:`Authenticator.authenticate`."""
45
+ ...
46
+
47
+
48
+ @runtime_checkable
49
+ class Authorizer(Protocol):
50
+ """Decides whether a verified principal may proceed."""
51
+
52
+ def authorize(self, principal: Principal, *, requires: Requirement) -> None:
53
+ """Permit the request, or refuse it.
54
+
55
+ Raises:
56
+ PermissionDenied: The principal lacks the required access. Never
57
+ :class:`~rn_forge.web.exceptions.AuthenticationFailed` — the
58
+ caller is authenticated; that is the 401/403 boundary.
59
+ """
60
+ ...
61
+
62
+
63
+ class ScopeAuthorizer:
64
+ """An :class:`Authorizer` that evaluates a :class:`Requirement`.
65
+
66
+ Args:
67
+ log: Optional sink called as ``log(message, context)`` when access is
68
+ refused. ``None`` disables logging.
69
+ """
70
+
71
+ def __init__(
72
+ self, *, log: Callable[[str, Mapping[str, Any]], None] | None = None
73
+ ) -> None:
74
+ self._log = log
75
+
76
+ def authorize(self, principal: Principal, *, requires: Requirement) -> None:
77
+ """See :meth:`Authorizer.authorize`."""
78
+ if requires.is_satisfied_by(principal):
79
+ return
80
+ if self._log is not None:
81
+ self._log(
82
+ "authorization.denied",
83
+ {
84
+ "subject": principal.subject,
85
+ "mechanism": principal.mechanism,
86
+ "required": requires,
87
+ },
88
+ )
89
+ raise PermissionDenied(
90
+ "The authenticated principal lacks the required access", error_code=403
91
+ )