gt-auth-sdk-python 0.4.2__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.
gt_auth_sdk/me.py ADDED
@@ -0,0 +1,188 @@
1
+ import hashlib
2
+ import time
3
+ from collections.abc import Callable, Mapping
4
+ from concurrent.futures import Future
5
+ from dataclasses import dataclass
6
+ from threading import Lock
7
+ from typing import Any
8
+
9
+ import httpx
10
+ import jwt
11
+
12
+ from gt_auth_sdk.errors import GtAuthError
13
+ from gt_auth_sdk.settings import GtAuthSettings
14
+
15
+ ME_PATH = "/api/auth/me"
16
+ SESSION_REJECTIONS = frozenset({401, 403})
17
+ MAX_CACHE_ENTRIES = 1000
18
+
19
+ FetchMe = Callable[[str], httpx.Response]
20
+ Clock = Callable[[], float]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class CurrentAccess:
25
+ """What gt-auth knows about a token right now."""
26
+
27
+ user: Mapping[str, Any]
28
+ app_name: str | None
29
+
30
+
31
+ class GtAuthMeClient:
32
+ def __init__(
33
+ self,
34
+ base_url: str,
35
+ timeout_seconds: float,
36
+ transport: httpx.BaseTransport | None = None,
37
+ ) -> None:
38
+ self._base_url = base_url.rstrip("/")
39
+ self._timeout_seconds = timeout_seconds
40
+ self._transport = transport
41
+ self._client: httpx.Client | None = None
42
+
43
+ def __call__(self, token: str) -> httpx.Response:
44
+ if not self._base_url:
45
+ raise httpx.UnsupportedProtocol("GT_AUTH_BASE_URL is not configured")
46
+ return self._http_client().get(ME_PATH, headers={"Authorization": f"Bearer {token}"})
47
+
48
+ def _http_client(self) -> httpx.Client:
49
+ # Created on first use so importing the application never opens a connection pool.
50
+ if self._client is None:
51
+ self._client = httpx.Client(
52
+ base_url=self._base_url,
53
+ timeout=self._timeout_seconds,
54
+ transport=self._transport,
55
+ )
56
+ return self._client
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class _CacheEntry:
61
+ access: CurrentAccess
62
+ expires_at: float
63
+
64
+
65
+ class MeSource:
66
+ """Asks gt-auth for the current access of a token, remembering only successful answers.
67
+
68
+ A rejected or failed lookup is asked again every time, so a revocation takes at most one TTL
69
+ to apply.
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ settings: GtAuthSettings,
75
+ *,
76
+ fetch_me: FetchMe | None = None,
77
+ clock: Clock = time.time,
78
+ ) -> None:
79
+ self._fetch_me = fetch_me or GtAuthMeClient(
80
+ settings.base_url, settings.request_timeout_seconds
81
+ )
82
+ self._ttl_seconds = max(settings.cache_ttl_seconds, 0.0)
83
+ self._clock = clock
84
+ self._entries: dict[str, _CacheEntry] = {}
85
+ self._in_flight: dict[str, Future[CurrentAccess]] = {}
86
+ self._lock = Lock()
87
+
88
+ def current_access(self, token: str) -> CurrentAccess:
89
+ if self._ttl_seconds == 0:
90
+ return self._request(token)
91
+
92
+ key = _cache_key(token)
93
+ with self._lock:
94
+ cached = self._fresh(key)
95
+ if cached is not None:
96
+ return cached
97
+ shared = self._in_flight.get(key)
98
+ if shared is None:
99
+ own: Future[CurrentAccess] = Future()
100
+ self._in_flight[key] = own
101
+
102
+ if shared is not None:
103
+ return shared.result()
104
+
105
+ try:
106
+ access = self._request(token)
107
+ except BaseException as error:
108
+ with self._lock:
109
+ del self._in_flight[key]
110
+ own.set_exception(error)
111
+ raise
112
+
113
+ with self._lock:
114
+ self._remember(key, access, _unverified_expiry(token))
115
+ del self._in_flight[key]
116
+ own.set_result(access)
117
+ return access
118
+
119
+ def forget(self, token: str) -> None:
120
+ with self._lock:
121
+ self._entries.pop(_cache_key(token), None)
122
+
123
+ def _fresh(self, key: str) -> CurrentAccess | None:
124
+ entry = self._entries.get(key)
125
+ if entry is None:
126
+ return None
127
+ if entry.expires_at <= self._clock():
128
+ del self._entries[key]
129
+ return None
130
+ return entry.access
131
+
132
+ def _remember(self, key: str, access: CurrentAccess, token_expiry: float | None) -> None:
133
+ now = self._clock()
134
+ expires_at = now + self._ttl_seconds
135
+ if token_expiry is not None:
136
+ expires_at = min(expires_at, token_expiry)
137
+ if expires_at <= now:
138
+ return
139
+
140
+ self._entries = {k: entry for k, entry in self._entries.items() if entry.expires_at > now}
141
+ if len(self._entries) >= MAX_CACHE_ENTRIES:
142
+ del self._entries[next(iter(self._entries))]
143
+ self._entries[key] = _CacheEntry(access, expires_at)
144
+
145
+ def _request(self, token: str) -> CurrentAccess:
146
+ try:
147
+ response = self._fetch_me(token)
148
+ except httpx.HTTPError as error:
149
+ raise GtAuthError.gt_auth_unavailable() from error
150
+
151
+ if response.status_code in SESSION_REJECTIONS:
152
+ raise GtAuthError.session_rejected(response.status_code)
153
+ if not response.is_success:
154
+ raise GtAuthError.gt_auth_unavailable()
155
+
156
+ try:
157
+ body = response.json()
158
+ except ValueError as error:
159
+ raise GtAuthError.gt_auth_unavailable() from error
160
+
161
+ user = body.get("user") if isinstance(body, dict) else None
162
+ if not isinstance(user, dict) or not isinstance(user.get("userRoles"), list):
163
+ raise GtAuthError.gt_auth_unavailable()
164
+
165
+ app_name = body.get("appName")
166
+ return CurrentAccess(user=user, app_name=app_name if isinstance(app_name, str) else None)
167
+
168
+
169
+ def unverified_claims(token: str) -> dict[str, Any]:
170
+ """Reads a token payload without checking its signature.
171
+
172
+ Only safe for a token gt-auth has just accepted, or for non-security data such as its expiry.
173
+ """
174
+ try:
175
+ claims = jwt.decode(token, options={"verify_signature": False})
176
+ except jwt.InvalidTokenError:
177
+ return {}
178
+ return claims if isinstance(claims, dict) else {}
179
+
180
+
181
+ def _unverified_expiry(token: str) -> float | None:
182
+ expiry = unverified_claims(token).get("exp")
183
+ return float(expiry) if isinstance(expiry, (int, float)) else None
184
+
185
+
186
+ def _cache_key(token: str) -> str:
187
+ # Never the raw token: a memory dump must not hand out sessions.
188
+ return hashlib.sha256(token.encode()).hexdigest()
@@ -0,0 +1,220 @@
1
+ from collections.abc import Iterable, Mapping
2
+ from dataclasses import dataclass, field
3
+ from typing import Any, Literal
4
+ from uuid import UUID
5
+
6
+ UserType = Literal["internal", "external"]
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class Role:
11
+ name: str
12
+ permissions: tuple[str, ...] = ()
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class ScopedRole:
17
+ name: str
18
+ permissions: tuple[str, ...] = ()
19
+ scopes: tuple[str, ...] = ()
20
+
21
+ def covers(self, submodule: str) -> bool:
22
+ # The dot keeps "…f29" from granting access to "…f29_anual".
23
+ return any(submodule == scope or submodule.startswith(f"{scope}.") for scope in self.scopes)
24
+
25
+ def reaches_module(self, module: str) -> bool:
26
+ return any(scope.startswith(f"{module}.") for scope in self.scopes)
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Principal:
31
+ """The authenticated user, with the same shape in every gt-auth SDK."""
32
+
33
+ id: UUID
34
+ name: str | None = None
35
+ email: str | None = None
36
+ user_type: UserType | None = None
37
+ audience: str | None = None
38
+ business_line_id: UUID | None = None
39
+ organization_id: UUID | None = None
40
+ roles: tuple[Role, ...] = ()
41
+ scoped_roles: tuple[ScopedRole, ...] = ()
42
+ data_user: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False)
43
+
44
+ @property
45
+ def permissions(self) -> tuple[str, ...]:
46
+ """Whole-module permissions only. Scoped permissions are never included here."""
47
+ return tuple(sorted({permission for role in self.roles for permission in role.permissions}))
48
+
49
+ def granted_permissions(
50
+ self,
51
+ *,
52
+ submodule: str | Iterable[str] | None = None,
53
+ any_submodule_of: str | None = None,
54
+ ) -> frozenset[str]:
55
+ """Permissions that count for a check.
56
+
57
+ ``submodule`` may be several keys: a scoped role counts if it covers any of them.
58
+ """
59
+ submodules = _as_tuple(submodule)
60
+ granted = {permission for role in self.roles for permission in role.permissions}
61
+ for scoped_role in self.scoped_roles:
62
+ in_submodule = any(scoped_role.covers(key) for key in submodules)
63
+ in_module = any_submodule_of is not None and scoped_role.reaches_module(
64
+ any_submodule_of
65
+ )
66
+ if in_submodule or in_module:
67
+ granted.update(scoped_role.permissions)
68
+ return frozenset(granted)
69
+
70
+ def all_permissions(self) -> frozenset[str]:
71
+ """Every permission the user holds anywhere, scoped or not. Use it for deny lists."""
72
+ scoped = {
73
+ permission
74
+ for scoped_role in self.scoped_roles
75
+ for permission in scoped_role.permissions
76
+ }
77
+ return self.granted_permissions() | scoped
78
+
79
+ def can(
80
+ self,
81
+ permission: str,
82
+ *,
83
+ submodule: str | Iterable[str] | None = None,
84
+ any_submodule_of: str | None = None,
85
+ ) -> bool:
86
+ return self.can_any((permission,), submodule=submodule, any_submodule_of=any_submodule_of)
87
+
88
+ def can_any(
89
+ self,
90
+ permissions: Iterable[str],
91
+ *,
92
+ submodule: str | Iterable[str] | None = None,
93
+ any_submodule_of: str | None = None,
94
+ ) -> bool:
95
+ granted = self.granted_permissions(submodule=submodule, any_submodule_of=any_submodule_of)
96
+ return any(str(permission) in granted for permission in permissions)
97
+
98
+ def has_none_of(self, permissions: Iterable[str]) -> bool:
99
+ held = self.all_permissions()
100
+ return not any(str(permission) in held for permission in permissions)
101
+
102
+ def to_dict(self) -> dict[str, Any]:
103
+ """JSON-safe form, for carrying the user into a background job.
104
+
105
+ ``data_user`` is left out: it can be large and jobs only need identity and access.
106
+ """
107
+ return {
108
+ "id": str(self.id),
109
+ "name": self.name,
110
+ "email": self.email,
111
+ "userType": self.user_type,
112
+ "audience": self.audience,
113
+ "businessLineId": _text(self.business_line_id),
114
+ "organizationId": _text(self.organization_id),
115
+ "roles": [
116
+ {"name": role.name, "permissions": list(role.permissions)} for role in self.roles
117
+ ],
118
+ "scopedRoles": [
119
+ {
120
+ "name": role.name,
121
+ "permissions": list(role.permissions),
122
+ "scopes": list(role.scopes),
123
+ }
124
+ for role in self.scoped_roles
125
+ ],
126
+ }
127
+
128
+ @classmethod
129
+ def from_dict(cls, data: Mapping[str, Any]) -> "Principal":
130
+ """Rebuilds a principal from ``to_dict``.
131
+
132
+ Also reads the payloads the backends queued before adopting the SDK, whose roles carry
133
+ ``role_name`` instead of ``name``. Raises ``ValueError`` if an id is not a UUID.
134
+ """
135
+ user_type = data.get("userType")
136
+ return cls(
137
+ id=UUID(str(data["id"])),
138
+ name=data.get("name"),
139
+ email=data.get("email"),
140
+ user_type=user_type if user_type in ("internal", "external") else None,
141
+ audience=data.get("audience"),
142
+ business_line_id=_uuid_or_none(data.get("businessLineId")),
143
+ organization_id=_uuid_or_none(data.get("organizationId")),
144
+ roles=roles_from_claims(_with_current_role_names(data.get("roles"))),
145
+ scoped_roles=scoped_roles_from_claims(
146
+ _with_current_role_names(data.get("scopedRoles"))
147
+ ),
148
+ )
149
+
150
+
151
+ def roles_from_claims(claims: object) -> tuple[Role, ...]:
152
+ if not isinstance(claims, list):
153
+ return ()
154
+ roles = []
155
+ for claim in claims:
156
+ name = _role_name(claim)
157
+ if name is not None:
158
+ roles.append(Role(name=name, permissions=_strings(claim.get("permissions"))))
159
+ return tuple(roles)
160
+
161
+
162
+ def scoped_roles_from_claims(claims: object) -> tuple[ScopedRole, ...]:
163
+ if not isinstance(claims, list):
164
+ return ()
165
+ roles: list[ScopedRole] = []
166
+ seen: set[tuple[str, tuple[str, ...], tuple[str, ...]]] = set()
167
+ for claim in claims:
168
+ name = _role_name(claim)
169
+ if name is None or not isinstance(claim.get("scopes"), list):
170
+ continue
171
+ role = ScopedRole(
172
+ name=name,
173
+ permissions=_strings(claim.get("permissions")),
174
+ scopes=_strings(claim["scopes"]),
175
+ )
176
+ identity = (role.name, tuple(sorted(role.permissions)), tuple(sorted(role.scopes)))
177
+ if identity not in seen:
178
+ seen.add(identity)
179
+ roles.append(role)
180
+ return tuple(roles)
181
+
182
+
183
+ def _role_name(claim: object) -> str | None:
184
+ if not isinstance(claim, dict):
185
+ return None
186
+ name = claim.get("name")
187
+ return name if isinstance(name, str) and name else None
188
+
189
+
190
+ def _strings(values: object) -> tuple[str, ...]:
191
+ if not isinstance(values, list):
192
+ return ()
193
+ return tuple(dict.fromkeys(value for value in values if isinstance(value, str) and value))
194
+
195
+
196
+ def _as_tuple(value: str | Iterable[str] | None) -> tuple[str, ...]:
197
+ if value is None:
198
+ return ()
199
+ if isinstance(value, str):
200
+ return (value,)
201
+ return tuple(value)
202
+
203
+
204
+ def _text(value: UUID | None) -> str | None:
205
+ return None if value is None else str(value)
206
+
207
+
208
+ def _uuid_or_none(value: object) -> UUID | None:
209
+ return None if value is None else UUID(str(value))
210
+
211
+
212
+ def _with_current_role_names(claims: object) -> object:
213
+ if not isinstance(claims, list):
214
+ return claims
215
+ return [
216
+ {**claim, "name": claim.get("name") or claim.get("role_name")}
217
+ if isinstance(claim, dict)
218
+ else claim
219
+ for claim in claims
220
+ ]
gt_auth_sdk/py.typed ADDED
File without changes
gt_auth_sdk/session.py ADDED
@@ -0,0 +1,111 @@
1
+ from collections.abc import Callable, Mapping
2
+ from dataclasses import dataclass, field
3
+ from typing import Any
4
+
5
+ import httpx
6
+
7
+ from gt_auth_sdk.errors import GtAuthError
8
+ from gt_auth_sdk.me import SESSION_REJECTIONS
9
+ from gt_auth_sdk.settings import GtAuthSettings
10
+
11
+ EXCHANGE_PATH = "/api/auth/exchange"
12
+ REFRESH_PATH = "/api/auth/refresh"
13
+ INTERNAL_AUTH_HEADER = "x-internal-auth"
14
+
15
+ ACCESS_COOKIE_MAX_AGE_SECONDS = 60 * 60
16
+ REFRESH_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 7
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class SessionTokens:
21
+ access_token: str = field(repr=False)
22
+ # None when gt-auth did not rotate the refresh token; the caller keeps the one it has.
23
+ refresh_token: str | None = field(default=None, repr=False)
24
+ user: Mapping[str, Any] = field(default_factory=dict)
25
+
26
+
27
+ class SessionClient:
28
+ """Trades auth codes and refresh tokens with gt-auth, without any web framework."""
29
+
30
+ def __init__(
31
+ self, settings: GtAuthSettings, *, transport: httpx.BaseTransport | None = None
32
+ ) -> None:
33
+ if not settings.base_url:
34
+ raise ValueError("base_url is required for session routes (GT_AUTH_BASE_URL)")
35
+ if not settings.internal_key:
36
+ raise ValueError("internal_key is required for session routes (GT_AUTH_INTERNAL_KEY)")
37
+ if not settings.app_name:
38
+ raise ValueError("app_name is required for session routes (GT_AUTH_APP_NAME)")
39
+ self._settings = settings
40
+ self._transport = transport
41
+ self._client: httpx.Client | None = None
42
+
43
+ def exchange(self, *, auth_code: str, state: str, redirect_url: str) -> SessionTokens:
44
+ tokens = self._post(
45
+ EXCHANGE_PATH,
46
+ {
47
+ "authCode": auth_code,
48
+ "state": state,
49
+ "appName": self._settings.app_name,
50
+ "redirectUrl": redirect_url,
51
+ },
52
+ rejection=GtAuthError.sign_in_rejected,
53
+ )
54
+ if tokens.refresh_token is None:
55
+ raise GtAuthError.gt_auth_unavailable()
56
+ return tokens
57
+
58
+ def refresh(self, refresh_token: str) -> SessionTokens:
59
+ return self._post(
60
+ REFRESH_PATH,
61
+ {"refreshToken": refresh_token, "appName": self._settings.app_name},
62
+ rejection=_refresh_rejection,
63
+ )
64
+
65
+ def _post(
66
+ self, path: str, body: dict[str, Any], *, rejection: Callable[[int], GtAuthError]
67
+ ) -> SessionTokens:
68
+ try:
69
+ response = self._http_client().post(path, json=body)
70
+ except httpx.HTTPError as error:
71
+ raise GtAuthError.gt_auth_unavailable() from error
72
+
73
+ if response.is_client_error:
74
+ raise rejection(response.status_code)
75
+ if not response.is_success:
76
+ raise GtAuthError.gt_auth_unavailable()
77
+
78
+ try:
79
+ data = response.json()
80
+ except ValueError as error:
81
+ raise GtAuthError.gt_auth_unavailable() from error
82
+
83
+ access_token = data.get("accessToken") if isinstance(data, dict) else None
84
+ if not isinstance(access_token, str) or not access_token:
85
+ raise GtAuthError.gt_auth_unavailable()
86
+
87
+ refresh_token = data.get("refreshToken")
88
+ user = data.get("user")
89
+ return SessionTokens(
90
+ access_token=access_token,
91
+ refresh_token=refresh_token
92
+ if isinstance(refresh_token, str) and refresh_token
93
+ else None,
94
+ user=user if isinstance(user, dict) else {},
95
+ )
96
+
97
+ def _http_client(self) -> httpx.Client:
98
+ # Created on first use so importing the application never opens a connection pool.
99
+ if self._client is None:
100
+ self._client = httpx.Client(
101
+ base_url=self._settings.base_url.rstrip("/"),
102
+ timeout=self._settings.request_timeout_seconds,
103
+ headers={INTERNAL_AUTH_HEADER: self._settings.internal_key or ""},
104
+ transport=self._transport,
105
+ )
106
+ return self._client
107
+
108
+
109
+ def _refresh_rejection(status_code: int) -> GtAuthError:
110
+ # Any refusal of a refresh token means the session is over; only 403 keeps its own meaning.
111
+ return GtAuthError.session_rejected(status_code if status_code in SESSION_REJECTIONS else 401)
@@ -0,0 +1,91 @@
1
+ import os
2
+ from collections.abc import Mapping
3
+ from dataclasses import dataclass
4
+ from typing import Literal, cast
5
+
6
+ ValidationMode = Literal["local", "remote"]
7
+ SameSite = Literal["lax", "strict", "none"]
8
+
9
+ DEFAULT_ALGORITHM = "HS256"
10
+ DEFAULT_CACHE_TTL_SECONDS = 60.0
11
+ DEFAULT_REQUEST_TIMEOUT_SECONDS = 15.0
12
+ ACCESS_COOKIE_NAME = "app_access_token"
13
+ REFRESH_COOKIE_NAME = "app_refresh_token"
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class GtAuthSettings:
18
+ """Configuration of the SDK.
19
+
20
+ ``local`` validation verifies the token signature with the shared key and only calls gt-auth
21
+ for thin tokens. ``remote`` validation has no key and asks gt-auth about every token.
22
+
23
+ ``internal_key``, ``app_name`` and the cookie fields are only used by the session routes.
24
+ """
25
+
26
+ base_url: str
27
+ secret_key: str | None = None
28
+ algorithm: str = DEFAULT_ALGORITHM
29
+ validation: ValidationMode = "local"
30
+ expected_audiences: tuple[str, ...] = ()
31
+ cache_ttl_seconds: float = DEFAULT_CACHE_TTL_SECONDS
32
+ request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS
33
+ access_cookie_name: str = ACCESS_COOKIE_NAME
34
+ internal_key: str | None = None
35
+ app_name: str | None = None
36
+ refresh_cookie_name: str = REFRESH_COOKIE_NAME
37
+ cookie_secure: bool = True
38
+ cookie_domain: str | None = None
39
+ cookie_samesite: SameSite = "lax"
40
+
41
+ def __post_init__(self) -> None:
42
+ if self.validation not in ("local", "remote"):
43
+ raise ValueError(f"Unknown validation mode: {self.validation!r}")
44
+ # Local validation only calls gt-auth for thin tokens, and the backends that adopted the
45
+ # SDK never required the URL at startup; without it those lookups fail as unavailable.
46
+ if self.validation == "remote" and not self.base_url:
47
+ raise ValueError("base_url is required for remote validation (GT_AUTH_BASE_URL)")
48
+ if self.validation == "local" and not self.secret_key:
49
+ raise ValueError("secret_key is required for local validation (SECRET_KEY)")
50
+ if self.algorithm.lower() == "none":
51
+ raise ValueError("Unsigned tokens are not accepted")
52
+ if self.cookie_samesite not in ("lax", "strict", "none"):
53
+ raise ValueError(f"Unknown SameSite value: {self.cookie_samesite!r}")
54
+ if self.cookie_samesite == "none" and not self.cookie_secure:
55
+ # Browsers drop SameSite=None cookies that are not Secure.
56
+ object.__setattr__(self, "cookie_secure", True)
57
+
58
+ @classmethod
59
+ def from_env(
60
+ cls,
61
+ env: Mapping[str, str] | None = None,
62
+ *,
63
+ validation: ValidationMode = "local",
64
+ ) -> "GtAuthSettings":
65
+ source = os.environ if env is None else env
66
+ ttl_ms = source.get("GT_AUTH_CACHE_TTL_MS")
67
+ cookie_secure = source.get("APP_COOKIE_SECURE")
68
+ return cls(
69
+ # AUTH_BASE_URL is the name some services already use; accepting it avoids a rename.
70
+ base_url=source.get("GT_AUTH_BASE_URL") or source.get("AUTH_BASE_URL") or "",
71
+ secret_key=source.get("SECRET_KEY") or None,
72
+ algorithm=source.get("ALGORITHM") or DEFAULT_ALGORITHM,
73
+ validation=validation,
74
+ expected_audiences=_comma_separated(source.get("GT_AUTH_EXPECTED_AUDIENCES")),
75
+ cache_ttl_seconds=(float(ttl_ms) / 1000 if ttl_ms else DEFAULT_CACHE_TTL_SECONDS),
76
+ internal_key=source.get("GT_AUTH_INTERNAL_KEY") or None,
77
+ app_name=source.get("GT_AUTH_APP_NAME") or None,
78
+ # Secure unless explicitly turned off, so a missing variable never weakens production.
79
+ cookie_secure=cookie_secure.strip().lower() != "false" if cookie_secure else True,
80
+ cookie_domain=source.get("APP_COOKIE_DOMAIN") or None,
81
+ # Checked in __post_init__.
82
+ cookie_samesite=cast(
83
+ SameSite, (source.get("APP_COOKIE_SAMESITE") or "lax").strip().lower()
84
+ ),
85
+ )
86
+
87
+
88
+ def _comma_separated(value: str | None) -> tuple[str, ...]:
89
+ if not value:
90
+ return ()
91
+ return tuple(item.strip() for item in value.split(",") if item.strip())