rn-forge-auth 0.1.0__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.
@@ -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
+ ...
rn_forge/auth/audit.py ADDED
@@ -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
+ )
@@ -0,0 +1,157 @@
1
+ """The security controls every framework binding must demonstrate.
2
+
3
+ :data:`CASES` has one case per row of the design's security-controls table.
4
+ Each binding's test suite tags tests with a case ID and fails when a case has
5
+ none, so a control added here is a control both bindings must show.
6
+
7
+ A test shows a control by carrying ``@pytest.mark.security_control("<id>")``,
8
+ on a function, a method or a class; :func:`tagged_tests` finds those marks in a
9
+ suite's source without importing it.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ from collections import defaultdict
16
+ from collections.abc import Iterator
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Final
20
+
21
+ __all__ = ["CASES", "SecurityControlCase", "case_by_id", "tagged_tests"]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class SecurityControlCase:
26
+ """One security control.
27
+
28
+ Attributes:
29
+ id: A stable identifier, used as the argument of a test's
30
+ ``security_control`` marker.
31
+ control: What the control requires.
32
+ enforced_by: Where the control is enforced.
33
+ """
34
+
35
+ id: str
36
+ control: str
37
+ enforced_by: str
38
+
39
+
40
+ CASES: Final[tuple[SecurityControlCase, ...]] = (
41
+ SecurityControlCase(
42
+ "oidc-response-checks",
43
+ "state, nonce, PKCE S256, iss response check, UserInfo sub match",
44
+ "OIDC adapter (Authlib) and transaction store",
45
+ ),
46
+ SecurityControlCase(
47
+ "token-profiles",
48
+ "Separate access-token, ID-token and logout-token profiles",
49
+ "Token validation",
50
+ ),
51
+ SecurityControlCase(
52
+ "one-time-transactions",
53
+ "One-time login transactions bound to the browser",
54
+ "Transaction store and transaction cookie",
55
+ ),
56
+ SecurityControlCase(
57
+ "return-to-relative",
58
+ "return_to accepts relative paths only, checked against configured prefixes",
59
+ "Protocol adapter, before the redirect",
60
+ ),
61
+ SecurityControlCase(
62
+ "no-tokens-in-urls-or-logs",
63
+ "No tokens in URLs, browser storage or logs",
64
+ "BFF design; logging filters",
65
+ ),
66
+ SecurityControlCase(
67
+ "one-credential-per-request",
68
+ "One credential per request; no fallback after an invalid bearer token",
69
+ "Framework binding",
70
+ ),
71
+ SecurityControlCase(
72
+ "session-lifecycle",
73
+ "Session ID rotation, idle and absolute timeouts, session versions, "
74
+ "revoked sid values",
75
+ "Framework session binding and supported storage",
76
+ ),
77
+ SecurityControlCase(
78
+ "csrf-and-origin",
79
+ "CSRF token bound to the session, and an origin check, on unsafe methods",
80
+ "CSRF",
81
+ ),
82
+ SecurityControlCase(
83
+ "bearer-scope-ceiling",
84
+ "Scope ceiling on bearer principals",
85
+ "Principal construction",
86
+ ),
87
+ SecurityControlCase(
88
+ "problem-responses",
89
+ "401 and 403 as RFC 9457 problems, with no detail on verification failures",
90
+ "rn-forge-web contract",
91
+ ),
92
+ SecurityControlCase(
93
+ "rate-limiting",
94
+ "Rate limiting on /auth/login/password and callback endpoints",
95
+ "Framework binding, with configurable limits",
96
+ ),
97
+ SecurityControlCase(
98
+ "audit-events",
99
+ "Audit events: login success and failure, logout, account provisioned, "
100
+ "rejected or disabled, authorization denied",
101
+ "AppLogger audit channel",
102
+ ),
103
+ SecurityControlCase(
104
+ "jwks-rotation",
105
+ "JWKS key rotation",
106
+ "PyJWT's PyJWKClient, which refetches for an unknown kid at most once "
107
+ "per cooldown",
108
+ ),
109
+ )
110
+
111
+
112
+ def case_by_id(case_id: str) -> SecurityControlCase:
113
+ """Return the case with ID *case_id*.
114
+
115
+ Raises:
116
+ KeyError: No case has that ID.
117
+ """
118
+ for case in CASES:
119
+ if case.id == case_id:
120
+ return case
121
+ raise KeyError(case_id)
122
+
123
+
124
+ def tagged_tests(root: Path) -> dict[str, list[str]]:
125
+ """Find the tests that carry a ``security_control`` marker under *root*.
126
+
127
+ Args:
128
+ root: A directory of test modules, searched recursively.
129
+
130
+ Returns:
131
+ Each tagged case ID, including an ID no case has, mapped to the
132
+ ``<file>::<class or function>`` names that carry it.
133
+ """
134
+ found: defaultdict[str, list[str]] = defaultdict(list)
135
+ for path in sorted(root.rglob("*.py")):
136
+ tree = ast.parse(path.read_text(encoding="utf-8"))
137
+ for node in ast.walk(tree):
138
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
139
+ for case_id in _security_control_ids(node):
140
+ found[case_id].append(f"{path.relative_to(root)}::{node.name}")
141
+ return dict(found)
142
+
143
+
144
+ def _security_control_ids(
145
+ node: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef,
146
+ ) -> Iterator[str]:
147
+ for decorator in node.decorator_list:
148
+ if (
149
+ isinstance(decorator, ast.Call)
150
+ and isinstance(decorator.func, ast.Attribute)
151
+ and decorator.func.attr == "security_control"
152
+ ):
153
+ for argument in decorator.args:
154
+ if isinstance(argument, ast.Constant) and isinstance(
155
+ argument.value, str
156
+ ):
157
+ yield argument.value
@@ -0,0 +1,38 @@
1
+ """Authorization context contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Protocol, runtime_checkable
8
+
9
+ __all__ = ["AuthorizationContext", "AuthorizationContextProvider"]
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AuthorizationContext:
14
+ """An account's current authorization data.
15
+
16
+ Attributes:
17
+ active: Whether the account may authenticate.
18
+ session_version: The account's current session version.
19
+ permissions: Permission keys the account holds.
20
+ roles: Role names, as a display hint and provider input.
21
+ attributes: Inputs to attribute-based rules, such as tenant, org units
22
+ and locations.
23
+ """
24
+
25
+ active: bool
26
+ session_version: int
27
+ permissions: frozenset[str] = frozenset()
28
+ roles: frozenset[str] = frozenset()
29
+ attributes: Mapping[str, Any] = field(default_factory=dict[str, Any])
30
+
31
+
32
+ @runtime_checkable
33
+ class AuthorizationContextProvider(Protocol):
34
+ """Supplies the :class:`AuthorizationContext` of an account."""
35
+
36
+ def resolve(self, account_id: str) -> AuthorizationContext:
37
+ """Return the current context of *account_id*."""
38
+ ...
@@ -0,0 +1,182 @@
1
+ """In-process cache of authorization contexts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from datetime import timedelta
10
+ from typing import Protocol, runtime_checkable
11
+
12
+ from rn_forge.auth.context import AuthorizationContext, AuthorizationContextProvider
13
+
14
+ __all__ = [
15
+ "AccountStateWriter",
16
+ "AuthorizationContextCache",
17
+ "AuthorizationVersions",
18
+ "InMemoryAuthorizationVersions",
19
+ ]
20
+
21
+
22
+ @runtime_checkable
23
+ class AuthorizationVersions(Protocol):
24
+ """Counters that say when cached authorization contexts are stale."""
25
+
26
+ def current(self, account_id: str) -> tuple[int, int]:
27
+ """Return the account's version and the global version."""
28
+ ...
29
+
30
+ def bump(self, account_id: str) -> None:
31
+ """Increase the version of *account_id*."""
32
+ ...
33
+
34
+ def bump_all(self) -> None:
35
+ """Increase the global version, which every account shares."""
36
+ ...
37
+
38
+
39
+ class InMemoryAuthorizationVersions:
40
+ """:class:`AuthorizationVersions` held in process memory.
41
+
42
+ Thread-safe. The counters are not shared across processes, so a bump is
43
+ seen only by caches that use the same instance.
44
+ """
45
+
46
+ def __init__(self) -> None:
47
+ self._lock = threading.Lock()
48
+ self._accounts: dict[str, int] = {}
49
+ self._global = 0
50
+
51
+ def current(self, account_id: str) -> tuple[int, int]:
52
+ """Return the account's version and the global version."""
53
+ with self._lock:
54
+ return self._accounts.get(account_id, 0), self._global
55
+
56
+ def bump(self, account_id: str) -> None:
57
+ """Increase the version of *account_id*."""
58
+ with self._lock:
59
+ self._accounts[account_id] = self._accounts.get(account_id, 0) + 1
60
+
61
+ def bump_all(self) -> None:
62
+ """Increase the global version."""
63
+ with self._lock:
64
+ self._global += 1
65
+
66
+
67
+ class AccountStateWriter(Protocol):
68
+ """Persists the account state that an authorization context carries."""
69
+
70
+ def set_active(self, account_id: str, active: bool) -> None:
71
+ """Store whether *account_id* may authenticate."""
72
+ ...
73
+
74
+ def bump_session_version(self, account_id: str) -> int:
75
+ """Increase the session version of *account_id* and return the new one."""
76
+ ...
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class _Entry:
81
+ context: AuthorizationContext
82
+ versions: tuple[int, int]
83
+ stored_at: float
84
+
85
+
86
+ class AuthorizationContextCache:
87
+ """An :class:`AuthorizationContextProvider` that caches another one.
88
+
89
+ Each account has one entry, valid while the account and global versions are
90
+ those it was computed at and it is younger than *ttl*. Changes made
91
+ through :meth:`invalidate`, :meth:`invalidate_all`, :meth:`set_active` and
92
+ :meth:`bump_session_version` apply on the next :meth:`resolve`. A change
93
+ made any other way applies once the entry's *ttl* has passed. The cache is
94
+ safe to share between threads and is local to the process.
95
+
96
+ Args:
97
+ provider: The provider that computes contexts.
98
+ ttl: The longest an entry is served. Must be positive.
99
+ versions: The version counters. Defaults to a new
100
+ :class:`InMemoryAuthorizationVersions`.
101
+ writer: Persists account state for :meth:`set_active` and
102
+ :meth:`bump_session_version`.
103
+ clock: Returns the current time in seconds, monotonic.
104
+
105
+ Raises:
106
+ ValueError: *ttl* is not positive.
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ provider: AuthorizationContextProvider,
112
+ *,
113
+ ttl: timedelta = timedelta(seconds=60),
114
+ versions: AuthorizationVersions | None = None,
115
+ writer: AccountStateWriter | None = None,
116
+ clock: Callable[[], float] = time.monotonic,
117
+ ) -> None:
118
+ if ttl <= timedelta(0):
119
+ raise ValueError("ttl must be positive")
120
+ self._provider = provider
121
+ self._ttl = ttl.total_seconds()
122
+ self._versions = (
123
+ versions if versions is not None else InMemoryAuthorizationVersions()
124
+ )
125
+ self._writer = writer
126
+ self._clock = clock
127
+ self._lock = threading.Lock()
128
+ self._entries: dict[str, _Entry] = {}
129
+
130
+ def resolve(self, account_id: str) -> AuthorizationContext:
131
+ """Return the context of *account_id*, computing it on a miss."""
132
+ versions = self._versions.current(account_id)
133
+ now = self._clock()
134
+ with self._lock:
135
+ entry = self._entries.get(account_id)
136
+ if (
137
+ entry is not None
138
+ and entry.versions == versions
139
+ and now - entry.stored_at < self._ttl
140
+ ):
141
+ return entry.context
142
+ # Versions were read before the provider so a bump during the
143
+ # computation leaves the entry stale rather than fresh.
144
+ context = self._provider.resolve(account_id)
145
+ with self._lock:
146
+ self._entries[account_id] = _Entry(context, versions, now)
147
+ return context
148
+
149
+ def invalidate(self, account_id: str) -> None:
150
+ """Make the next :meth:`resolve` of *account_id* recompute."""
151
+ self._versions.bump(account_id)
152
+
153
+ def invalidate_all(self) -> None:
154
+ """Make the next :meth:`resolve` of every account recompute."""
155
+ self._versions.bump_all()
156
+
157
+ def set_active(self, account_id: str, active: bool) -> None:
158
+ """Store the account's ``active`` flag and invalidate its context.
159
+
160
+ Raises:
161
+ RuntimeError: No writer was configured.
162
+ """
163
+ self._require_writer().set_active(account_id, active)
164
+ self.invalidate(account_id)
165
+
166
+ def bump_session_version(self, account_id: str) -> int:
167
+ """Increase the account's session version and invalidate its context.
168
+
169
+ Returns:
170
+ The new session version.
171
+
172
+ Raises:
173
+ RuntimeError: No writer was configured.
174
+ """
175
+ version = self._require_writer().bump_session_version(account_id)
176
+ self.invalidate(account_id)
177
+ return version
178
+
179
+ def _require_writer(self) -> AccountStateWriter:
180
+ if self._writer is None:
181
+ raise RuntimeError("no AccountStateWriter was configured")
182
+ return self._writer