sudomimus-django 0.2.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.
- sudomimus_django-0.2.0/.gitignore +47 -0
- sudomimus_django-0.2.0/PKG-INFO +63 -0
- sudomimus_django-0.2.0/README.md +48 -0
- sudomimus_django-0.2.0/pyproject.toml +21 -0
- sudomimus_django-0.2.0/src/sudomimus_django/__init__.py +11 -0
- sudomimus_django-0.2.0/src/sudomimus_django/integration.py +205 -0
- sudomimus_django-0.2.0/src/sudomimus_django/store.py +46 -0
- sudomimus_django-0.2.0/tests/test_integration.py +145 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Node / pnpm
|
|
2
|
+
node_modules/
|
|
3
|
+
.pnpm-store/
|
|
4
|
+
.pnp.*
|
|
5
|
+
*.tgz
|
|
6
|
+
|
|
7
|
+
# Build output
|
|
8
|
+
dist/
|
|
9
|
+
build/
|
|
10
|
+
.turbo/
|
|
11
|
+
*.tsbuildinfo
|
|
12
|
+
|
|
13
|
+
# Python
|
|
14
|
+
__pycache__/
|
|
15
|
+
*.py[cod]
|
|
16
|
+
*$py.class
|
|
17
|
+
*.egg-info/
|
|
18
|
+
.venv/
|
|
19
|
+
venv/
|
|
20
|
+
.uv/
|
|
21
|
+
|
|
22
|
+
# Test / coverage
|
|
23
|
+
coverage/
|
|
24
|
+
.nyc_output/
|
|
25
|
+
.pytest_cache/
|
|
26
|
+
.coverage
|
|
27
|
+
htmlcov/
|
|
28
|
+
|
|
29
|
+
# IDE / editor
|
|
30
|
+
.idea/
|
|
31
|
+
*.swp
|
|
32
|
+
*.swo
|
|
33
|
+
|
|
34
|
+
# OS
|
|
35
|
+
.DS_Store
|
|
36
|
+
Thumbs.db
|
|
37
|
+
|
|
38
|
+
# Environment
|
|
39
|
+
.env
|
|
40
|
+
.env.local
|
|
41
|
+
.env.*.local
|
|
42
|
+
|
|
43
|
+
# CSharp
|
|
44
|
+
bin/
|
|
45
|
+
obj/
|
|
46
|
+
*.dll
|
|
47
|
+
*.pdb
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sudomimus-django
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Django integration for Sudomimus Connect browser login
|
|
5
|
+
Project-URL: Homepage, https://sudomimus.com
|
|
6
|
+
Project-URL: Repository, https://github.com/Sudomimus/Sudomimus
|
|
7
|
+
Author: Sudomimus Contributors
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
Keywords: authentication,sdk,sudomimus
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Requires-Dist: django>=4.2
|
|
12
|
+
Requires-Dist: sudomimus-connect==5.0.0
|
|
13
|
+
Requires-Dist: sudomimus-session==5.0.0
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# sudomimus-django
|
|
17
|
+
|
|
18
|
+
Django integration for the ordinary Sudomimus Connect callback flow.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from django.urls import path
|
|
22
|
+
from sudomimus_connect import ConnectClient, ConnectClientAuthWithKey
|
|
23
|
+
from sudomimus_session import SessionClient
|
|
24
|
+
from sudomimus_django import ConnectDjango, DjangoLoginConfig, MemoryDjangoCredentialStore
|
|
25
|
+
|
|
26
|
+
integration = ConnectDjango(
|
|
27
|
+
DjangoLoginConfig(
|
|
28
|
+
application_anchor="my-app",
|
|
29
|
+
callback_url="https://my-app.example/auth/callback",
|
|
30
|
+
after_login_url="/dashboard",
|
|
31
|
+
after_logout_url="/",
|
|
32
|
+
),
|
|
33
|
+
ConnectClient(client_auth=ConnectClientAuthWithKey(
|
|
34
|
+
application_anchor="my-app", private_key_pem=private_key_pem,
|
|
35
|
+
)),
|
|
36
|
+
SessionClient(),
|
|
37
|
+
MemoryDjangoCredentialStore(), # development only
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
urlpatterns = [
|
|
41
|
+
path("auth/start", integration.start),
|
|
42
|
+
path("auth/callback", integration.callback),
|
|
43
|
+
path("auth/logout", integration.logout),
|
|
44
|
+
]
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Call `integration.current(request)` from a server view to obtain the current
|
|
48
|
+
sector subject and access token. It does not create a Django `User`; map the
|
|
49
|
+
pairwise subject to your own user record if needed. Use a server-side Django
|
|
50
|
+
session backend (database or cache), not signed-cookie sessions. For production,
|
|
51
|
+
implement `DjangoCredentialStore` with a shared database or Redis. Its `update`
|
|
52
|
+
method must serialize the callback across all workers for each session ID, so
|
|
53
|
+
concurrent refreshes cannot overwrite the rotated token. Keep Django's CSRF
|
|
54
|
+
middleware enabled for the POST start/logout views. The callback URL must be
|
|
55
|
+
permitted by the application's CALLBACK ReturnRule.
|
|
56
|
+
|
|
57
|
+
When redemption requires Basic Terms or current claim consent, or the
|
|
58
|
+
Inquiry's identity authority is stale, the callback consumes the pending login
|
|
59
|
+
and redirects to `reauthentication_url`. It defaults to `after_logout_url`.
|
|
60
|
+
Serve a sign-in page there with a CSRF-protected POST to `start`. When refresh
|
|
61
|
+
requires Basic Terms, `current` returns `None` and marks the stored session as
|
|
62
|
+
requiring reauthentication. `logout` can still revoke it with the stored
|
|
63
|
+
refresh token.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# sudomimus-django
|
|
2
|
+
|
|
3
|
+
Django integration for the ordinary Sudomimus Connect callback flow.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from django.urls import path
|
|
7
|
+
from sudomimus_connect import ConnectClient, ConnectClientAuthWithKey
|
|
8
|
+
from sudomimus_session import SessionClient
|
|
9
|
+
from sudomimus_django import ConnectDjango, DjangoLoginConfig, MemoryDjangoCredentialStore
|
|
10
|
+
|
|
11
|
+
integration = ConnectDjango(
|
|
12
|
+
DjangoLoginConfig(
|
|
13
|
+
application_anchor="my-app",
|
|
14
|
+
callback_url="https://my-app.example/auth/callback",
|
|
15
|
+
after_login_url="/dashboard",
|
|
16
|
+
after_logout_url="/",
|
|
17
|
+
),
|
|
18
|
+
ConnectClient(client_auth=ConnectClientAuthWithKey(
|
|
19
|
+
application_anchor="my-app", private_key_pem=private_key_pem,
|
|
20
|
+
)),
|
|
21
|
+
SessionClient(),
|
|
22
|
+
MemoryDjangoCredentialStore(), # development only
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
urlpatterns = [
|
|
26
|
+
path("auth/start", integration.start),
|
|
27
|
+
path("auth/callback", integration.callback),
|
|
28
|
+
path("auth/logout", integration.logout),
|
|
29
|
+
]
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Call `integration.current(request)` from a server view to obtain the current
|
|
33
|
+
sector subject and access token. It does not create a Django `User`; map the
|
|
34
|
+
pairwise subject to your own user record if needed. Use a server-side Django
|
|
35
|
+
session backend (database or cache), not signed-cookie sessions. For production,
|
|
36
|
+
implement `DjangoCredentialStore` with a shared database or Redis. Its `update`
|
|
37
|
+
method must serialize the callback across all workers for each session ID, so
|
|
38
|
+
concurrent refreshes cannot overwrite the rotated token. Keep Django's CSRF
|
|
39
|
+
middleware enabled for the POST start/logout views. The callback URL must be
|
|
40
|
+
permitted by the application's CALLBACK ReturnRule.
|
|
41
|
+
|
|
42
|
+
When redemption requires Basic Terms or current claim consent, or the
|
|
43
|
+
Inquiry's identity authority is stale, the callback consumes the pending login
|
|
44
|
+
and redirects to `reauthentication_url`. It defaults to `after_logout_url`.
|
|
45
|
+
Serve a sign-in page there with a CSRF-protected POST to `start`. When refresh
|
|
46
|
+
requires Basic Terms, `current` returns `None` and marks the stored session as
|
|
47
|
+
requiring reauthentication. `logout` can still revoke it with the stored
|
|
48
|
+
refresh token.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sudomimus-django"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Django integration for Sudomimus Connect browser login"
|
|
5
|
+
keywords = ["sudomimus", "authentication", "sdk"]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
requires-python = ">=3.11"
|
|
8
|
+
license = "MIT"
|
|
9
|
+
authors = [{ name = "Sudomimus Contributors" }]
|
|
10
|
+
dependencies = ["Django>=4.2", "sudomimus-connect==5.0.0", "sudomimus-session==5.0.0"]
|
|
11
|
+
|
|
12
|
+
[project.urls]
|
|
13
|
+
Homepage = "https://sudomimus.com"
|
|
14
|
+
Repository = "https://github.com/Sudomimus/Sudomimus"
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["hatchling"]
|
|
18
|
+
build-backend = "hatchling.build"
|
|
19
|
+
|
|
20
|
+
[tool.hatch.build.targets.wheel]
|
|
21
|
+
packages = ["src/sudomimus_django"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Django integration for the ordinary Sudomimus Connect flow."""
|
|
2
|
+
|
|
3
|
+
from .integration import ConnectDjango, DjangoLoginConfig
|
|
4
|
+
from .store import DjangoCredentialStore, MemoryDjangoCredentialStore
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"ConnectDjango",
|
|
8
|
+
"DjangoCredentialStore",
|
|
9
|
+
"DjangoLoginConfig",
|
|
10
|
+
"MemoryDjangoCredentialStore",
|
|
11
|
+
]
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Django views and session helpers for Connect callbacks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
9
|
+
|
|
10
|
+
from django.conf import settings # type: ignore[import-untyped]
|
|
11
|
+
from django.http import ( # type: ignore[import-untyped]
|
|
12
|
+
HttpRequest,
|
|
13
|
+
HttpResponse,
|
|
14
|
+
HttpResponseBadRequest,
|
|
15
|
+
HttpResponseNotAllowed,
|
|
16
|
+
HttpResponseRedirect,
|
|
17
|
+
)
|
|
18
|
+
from sudomimus_connect import ( # type: ignore[import-untyped]
|
|
19
|
+
ConnectApiError,
|
|
20
|
+
ConnectClient,
|
|
21
|
+
EstablishRequest,
|
|
22
|
+
Payload,
|
|
23
|
+
RedeemRequest,
|
|
24
|
+
ReturnMethodCallback,
|
|
25
|
+
ReturnMethodDeclaration,
|
|
26
|
+
)
|
|
27
|
+
from sudomimus_session import ( # type: ignore[import-untyped]
|
|
28
|
+
LogoutRequest,
|
|
29
|
+
RefreshRequest,
|
|
30
|
+
SessionApiError,
|
|
31
|
+
SessionClient,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
from .store import Credential, DjangoCredentialStore
|
|
35
|
+
|
|
36
|
+
_PENDING = "_sudomimus_pending"
|
|
37
|
+
_SESSION = "_sudomimus_session"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _requires_basic_terms(error: ConnectApiError | SessionApiError) -> bool:
|
|
41
|
+
return error.status == 403 and error.reason == "LegalAgreementRequired"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _requires_new_inquiry(error: ConnectApiError) -> bool:
|
|
45
|
+
return (
|
|
46
|
+
_requires_basic_terms(error)
|
|
47
|
+
or (error.status == 403 and error.reason == "ClaimConsentRequired")
|
|
48
|
+
or (error.status == 409 and error.reason == "AuthorizationArtifactStale")
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class DjangoLoginConfig:
|
|
54
|
+
application_anchor: str
|
|
55
|
+
callback_url: str
|
|
56
|
+
after_login_url: str
|
|
57
|
+
after_logout_url: str
|
|
58
|
+
via_url: str = "https://via.sudomimus.com/"
|
|
59
|
+
pending_ttl_seconds: int = 600
|
|
60
|
+
session_ttl_seconds: int = 2592000
|
|
61
|
+
reauthentication_url: str | None = None
|
|
62
|
+
|
|
63
|
+
def __post_init__(self) -> None:
|
|
64
|
+
callback = urlsplit(self.callback_url)
|
|
65
|
+
query = dict(parse_qsl(callback.query))
|
|
66
|
+
if "exposure-key" in query or "confirmation-key" in query:
|
|
67
|
+
raise ValueError("callback_url must not contain Inquiry keys")
|
|
68
|
+
if self.pending_ttl_seconds <= 0 or self.session_ttl_seconds <= 0:
|
|
69
|
+
raise ValueError("session TTLs must be positive")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ConnectDjango:
|
|
73
|
+
"""Use a server-side Django session and an atomic credential store."""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
config: DjangoLoginConfig,
|
|
78
|
+
connect: ConnectClient,
|
|
79
|
+
session: SessionClient,
|
|
80
|
+
store: DjangoCredentialStore,
|
|
81
|
+
) -> None:
|
|
82
|
+
if settings.SESSION_ENGINE == "django.contrib.sessions.backends.signed_cookies":
|
|
83
|
+
raise ValueError("Sudomimus requires a server-side Django session backend")
|
|
84
|
+
self.config = config
|
|
85
|
+
self.connect = connect
|
|
86
|
+
self.session = session
|
|
87
|
+
self.store = store
|
|
88
|
+
|
|
89
|
+
def start(self, request: HttpRequest) -> HttpResponse:
|
|
90
|
+
if request.method != "POST":
|
|
91
|
+
return HttpResponseNotAllowed(["POST"])
|
|
92
|
+
inquiry = self.connect.establish(
|
|
93
|
+
EstablishRequest(
|
|
94
|
+
applicationAnchor=self.config.application_anchor,
|
|
95
|
+
authenticationConstraints=None,
|
|
96
|
+
realizeConstraints=None,
|
|
97
|
+
returnMethods=[
|
|
98
|
+
ReturnMethodDeclaration(
|
|
99
|
+
root=ReturnMethodCallback(
|
|
100
|
+
type="CALLBACK", payload=Payload(callbackUrl=self.config.callback_url)
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
],
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
request.session[_PENDING] = {
|
|
107
|
+
"exposure": inquiry.exposureKey,
|
|
108
|
+
"hidden": inquiry.hiddenKey,
|
|
109
|
+
"expires": time.time() + self.config.pending_ttl_seconds,
|
|
110
|
+
}
|
|
111
|
+
via = urlsplit(self.config.via_url)
|
|
112
|
+
query = dict(parse_qsl(via.query))
|
|
113
|
+
query["exposure-key"] = inquiry.exposureKey
|
|
114
|
+
return HttpResponseRedirect(
|
|
115
|
+
urlunsplit((via.scheme, via.netloc, via.path, urlencode(query), via.fragment))
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def callback(self, request: HttpRequest) -> HttpResponse:
|
|
119
|
+
if request.method != "GET":
|
|
120
|
+
return HttpResponseNotAllowed(["GET"])
|
|
121
|
+
pending = request.session.get(_PENDING)
|
|
122
|
+
exposure = request.GET.get("exposure-key")
|
|
123
|
+
confirmation = request.GET.get("confirmation-key")
|
|
124
|
+
if (
|
|
125
|
+
not isinstance(pending, dict)
|
|
126
|
+
or not exposure
|
|
127
|
+
or not confirmation
|
|
128
|
+
or exposure != pending.get("exposure")
|
|
129
|
+
or time.time() >= pending.get("expires", 0)
|
|
130
|
+
):
|
|
131
|
+
return HttpResponseBadRequest("Invalid or expired login callback")
|
|
132
|
+
del request.session[_PENDING]
|
|
133
|
+
try:
|
|
134
|
+
issued = self.connect.redeem(
|
|
135
|
+
RedeemRequest(
|
|
136
|
+
exposureKey=exposure,
|
|
137
|
+
hiddenKey=pending["hidden"],
|
|
138
|
+
confirmationKey=confirmation,
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
except ConnectApiError as error:
|
|
142
|
+
if _requires_new_inquiry(error):
|
|
143
|
+
return HttpResponseRedirect(
|
|
144
|
+
self.config.reauthentication_url or self.config.after_logout_url
|
|
145
|
+
)
|
|
146
|
+
raise
|
|
147
|
+
verified = self.session.verify_access_token(issued.accessToken)
|
|
148
|
+
request.session.cycle_key()
|
|
149
|
+
session_id = uuid.uuid4().hex
|
|
150
|
+
self.store.put(session_id, {
|
|
151
|
+
"subject": verified.body.sub,
|
|
152
|
+
"access": issued.accessToken,
|
|
153
|
+
"refresh": issued.refreshToken,
|
|
154
|
+
"expires": verified.body.exp,
|
|
155
|
+
}, self.config.session_ttl_seconds)
|
|
156
|
+
request.session[_SESSION] = session_id
|
|
157
|
+
return HttpResponseRedirect(self.config.after_login_url)
|
|
158
|
+
|
|
159
|
+
def current(self, request: HttpRequest) -> dict[str, str] | None:
|
|
160
|
+
"""Return current identity and access token, rotating credentials when needed."""
|
|
161
|
+
session_id = request.session.get(_SESSION)
|
|
162
|
+
if not isinstance(session_id, str):
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
def access(value: Credential | None) -> tuple[Credential | None, dict[str, str] | None]:
|
|
166
|
+
if value is None or value.get("reauthentication_required") is True:
|
|
167
|
+
return value, None
|
|
168
|
+
if int(value["expires"]) <= time.time() + 30:
|
|
169
|
+
try:
|
|
170
|
+
rotated = self.session.refresh(
|
|
171
|
+
RefreshRequest(refreshToken=str(value["refresh"]))
|
|
172
|
+
)
|
|
173
|
+
except SessionApiError as error:
|
|
174
|
+
if error.status == 401:
|
|
175
|
+
return None, None
|
|
176
|
+
if _requires_basic_terms(error):
|
|
177
|
+
value.update(access="", reauthentication_required=True)
|
|
178
|
+
return value, None
|
|
179
|
+
raise
|
|
180
|
+
verified = self.session.verify_access_token(rotated.accessToken)
|
|
181
|
+
if verified.body.sub != value["subject"]:
|
|
182
|
+
return None, None
|
|
183
|
+
value.update(
|
|
184
|
+
access=rotated.accessToken,
|
|
185
|
+
refresh=rotated.refreshToken,
|
|
186
|
+
expires=verified.body.exp,
|
|
187
|
+
)
|
|
188
|
+
return value, {"subject": str(value["subject"]), "access_token": str(value["access"])}
|
|
189
|
+
|
|
190
|
+
return self.store.update(session_id, access)
|
|
191
|
+
|
|
192
|
+
def logout(self, request: HttpRequest) -> HttpResponse:
|
|
193
|
+
if request.method != "POST":
|
|
194
|
+
return HttpResponseNotAllowed(["POST"])
|
|
195
|
+
session_id = request.session.get(_SESSION)
|
|
196
|
+
if isinstance(session_id, str):
|
|
197
|
+
|
|
198
|
+
def revoke(value: Credential | None) -> tuple[None, None]:
|
|
199
|
+
if value is not None:
|
|
200
|
+
self.session.logout(LogoutRequest(refreshToken=str(value["refresh"])))
|
|
201
|
+
return None, None
|
|
202
|
+
|
|
203
|
+
self.store.update(session_id, revoke)
|
|
204
|
+
request.session.flush()
|
|
205
|
+
return HttpResponseRedirect(self.config.after_logout_url)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Server-side credential storage contract for Django integrations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from threading import Lock
|
|
8
|
+
from typing import Protocol, TypeVar
|
|
9
|
+
|
|
10
|
+
_T = TypeVar("_T")
|
|
11
|
+
Credential = dict[str, str | int]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DjangoCredentialStore(Protocol):
|
|
15
|
+
"""Production implementations must serialize updates across all workers."""
|
|
16
|
+
|
|
17
|
+
def put(self, key: str, value: Credential, ttl_seconds: int) -> None: ...
|
|
18
|
+
|
|
19
|
+
def update(
|
|
20
|
+
self, key: str, action: Callable[[Credential | None], tuple[Credential | None, _T]]
|
|
21
|
+
) -> _T: ...
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MemoryDjangoCredentialStore:
|
|
25
|
+
"""Single-process store for development and tests only."""
|
|
26
|
+
|
|
27
|
+
def __init__(self) -> None:
|
|
28
|
+
self._values: dict[str, tuple[Credential, float]] = {}
|
|
29
|
+
self._lock = Lock()
|
|
30
|
+
|
|
31
|
+
def put(self, key: str, value: Credential, ttl_seconds: int) -> None:
|
|
32
|
+
with self._lock:
|
|
33
|
+
self._values[key] = (value, time.time() + ttl_seconds)
|
|
34
|
+
|
|
35
|
+
def update(
|
|
36
|
+
self, key: str, action: Callable[[Credential | None], tuple[Credential | None, _T]]
|
|
37
|
+
) -> _T:
|
|
38
|
+
with self._lock:
|
|
39
|
+
stored = self._values.get(key)
|
|
40
|
+
current = stored[0].copy() if stored and stored[1] > time.time() else None
|
|
41
|
+
value, result = action(current)
|
|
42
|
+
if value is not None and stored and stored[1] > time.time():
|
|
43
|
+
self._values[key] = (value, stored[1])
|
|
44
|
+
else:
|
|
45
|
+
self._values.pop(key, None)
|
|
46
|
+
return result
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
5
|
+
from types import SimpleNamespace
|
|
6
|
+
from unittest.mock import Mock
|
|
7
|
+
|
|
8
|
+
import django
|
|
9
|
+
import pytest
|
|
10
|
+
from django.conf import settings
|
|
11
|
+
|
|
12
|
+
if not settings.configured:
|
|
13
|
+
settings.configure(
|
|
14
|
+
SECRET_KEY="test-secret",
|
|
15
|
+
SESSION_ENGINE="django.contrib.sessions.backends.cache",
|
|
16
|
+
CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}},
|
|
17
|
+
ALLOWED_HOSTS=["example.test"],
|
|
18
|
+
)
|
|
19
|
+
django.setup()
|
|
20
|
+
|
|
21
|
+
from django.contrib.sessions.middleware import SessionMiddleware # noqa: E402
|
|
22
|
+
from django.test import RequestFactory # noqa: E402
|
|
23
|
+
from sudomimus_connect import ConnectApiError # noqa: E402
|
|
24
|
+
from sudomimus_django import ( # noqa: E402
|
|
25
|
+
ConnectDjango,
|
|
26
|
+
DjangoLoginConfig,
|
|
27
|
+
MemoryDjangoCredentialStore,
|
|
28
|
+
)
|
|
29
|
+
from sudomimus_session import SessionApiError # noqa: E402
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _request(method: str, path: str, session=None):
|
|
33
|
+
request = getattr(RequestFactory(), method.lower())(path)
|
|
34
|
+
SessionMiddleware(lambda _: None).process_request(request)
|
|
35
|
+
if session is not None:
|
|
36
|
+
request.session = session
|
|
37
|
+
return request
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_login_refresh_and_logout() -> None:
|
|
41
|
+
connect = Mock()
|
|
42
|
+
connect.establish.return_value = SimpleNamespace(exposureKey="exp_one", hiddenKey="hid_secret")
|
|
43
|
+
connect.redeem.return_value = SimpleNamespace(accessToken="access-1", refreshToken="refresh-1")
|
|
44
|
+
session = Mock()
|
|
45
|
+
session.verify_access_token.side_effect = [
|
|
46
|
+
SimpleNamespace(body=SimpleNamespace(sub="subject", exp=int(time.time()) + 1)),
|
|
47
|
+
SimpleNamespace(body=SimpleNamespace(sub="subject", exp=int(time.time()) + 3600)),
|
|
48
|
+
]
|
|
49
|
+
session.refresh.return_value = SimpleNamespace(accessToken="access-2", refreshToken="refresh-2")
|
|
50
|
+
integration = ConnectDjango(
|
|
51
|
+
DjangoLoginConfig("my-app", "https://example.test/auth/callback", "/home", "/"),
|
|
52
|
+
connect,
|
|
53
|
+
session,
|
|
54
|
+
MemoryDjangoCredentialStore(),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
start = _request("POST", "/auth/start")
|
|
58
|
+
response = integration.start(start)
|
|
59
|
+
assert response.status_code == 302
|
|
60
|
+
assert "exposure-key=exp_one" in response["Location"]
|
|
61
|
+
assert "hid_secret" not in response["Location"]
|
|
62
|
+
|
|
63
|
+
callback = _request(
|
|
64
|
+
"GET", "/auth/callback?exposure-key=exp_one&confirmation-key=cnf_one", start.session
|
|
65
|
+
)
|
|
66
|
+
assert integration.callback(callback).status_code == 302
|
|
67
|
+
assert integration.callback(callback).status_code == 400
|
|
68
|
+
connect.redeem.assert_called_once()
|
|
69
|
+
|
|
70
|
+
with ThreadPoolExecutor(max_workers=2) as pool:
|
|
71
|
+
results = list(pool.map(integration.current, [callback, callback]))
|
|
72
|
+
assert results == [
|
|
73
|
+
{"subject": "subject", "access_token": "access-2"},
|
|
74
|
+
{"subject": "subject", "access_token": "access-2"},
|
|
75
|
+
]
|
|
76
|
+
assert session.refresh.call_count == 1
|
|
77
|
+
logout = _request("POST", "/auth/logout", callback.session)
|
|
78
|
+
assert integration.logout(logout).status_code == 302
|
|
79
|
+
session.logout.assert_called_once()
|
|
80
|
+
assert integration.current(logout) is None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@pytest.mark.parametrize(
|
|
84
|
+
("status", "reason"),
|
|
85
|
+
[
|
|
86
|
+
(403, "LegalAgreementRequired"),
|
|
87
|
+
(403, "ClaimConsentRequired"),
|
|
88
|
+
(409, "AuthorizationArtifactStale"),
|
|
89
|
+
],
|
|
90
|
+
)
|
|
91
|
+
def test_new_sign_in_preserves_logout_authority(status: int, reason: str) -> None:
|
|
92
|
+
connect = Mock()
|
|
93
|
+
connect.establish.side_effect = [
|
|
94
|
+
SimpleNamespace(exposureKey="exp_one", hiddenKey="hid_one"),
|
|
95
|
+
SimpleNamespace(exposureKey="exp_two", hiddenKey="hid_two"),
|
|
96
|
+
]
|
|
97
|
+
connect.redeem.side_effect = [
|
|
98
|
+
ConnectApiError(status, reason, None),
|
|
99
|
+
SimpleNamespace(accessToken="access-1", refreshToken="refresh-1"),
|
|
100
|
+
]
|
|
101
|
+
session = Mock()
|
|
102
|
+
session.verify_access_token.return_value = SimpleNamespace(
|
|
103
|
+
body=SimpleNamespace(sub="subject", exp=1)
|
|
104
|
+
)
|
|
105
|
+
session.refresh.side_effect = [
|
|
106
|
+
SessionApiError(403, "Layer2Denied", None),
|
|
107
|
+
SessionApiError(403, "LegalAgreementRequired", None),
|
|
108
|
+
]
|
|
109
|
+
integration = ConnectDjango(
|
|
110
|
+
DjangoLoginConfig(
|
|
111
|
+
"my-app", "https://example.test/auth/callback", "/home", "/",
|
|
112
|
+
reauthentication_url="/sign-in",
|
|
113
|
+
),
|
|
114
|
+
connect,
|
|
115
|
+
session,
|
|
116
|
+
MemoryDjangoCredentialStore(),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
start = _request("POST", "/auth/start")
|
|
120
|
+
integration.start(start)
|
|
121
|
+
first = _request(
|
|
122
|
+
"GET", "/auth/callback?exposure-key=exp_one&confirmation-key=cnf_one", start.session
|
|
123
|
+
)
|
|
124
|
+
response = integration.callback(first)
|
|
125
|
+
assert response.status_code == 302
|
|
126
|
+
assert response["Location"] == "/sign-in"
|
|
127
|
+
assert integration.callback(first).status_code == 400
|
|
128
|
+
|
|
129
|
+
integration.start(start)
|
|
130
|
+
second = _request(
|
|
131
|
+
"GET", "/auth/callback?exposure-key=exp_two&confirmation-key=cnf_two", start.session
|
|
132
|
+
)
|
|
133
|
+
assert integration.callback(second)["Location"] == "/home"
|
|
134
|
+
with pytest.raises(SessionApiError, match="Layer2Denied"):
|
|
135
|
+
integration.current(second)
|
|
136
|
+
assert integration.current(second) is None
|
|
137
|
+
assert integration.current(second) is None
|
|
138
|
+
assert session.refresh.call_count == 2
|
|
139
|
+
|
|
140
|
+
logout = _request("POST", "/auth/logout", second.session)
|
|
141
|
+
assert integration.logout(logout).status_code == 302
|
|
142
|
+
session.logout.assert_called_once()
|
|
143
|
+
assert session.logout.call_args.args[0].refreshToken == "refresh-1"
|
|
144
|
+
assert integration.logout(logout).status_code == 302
|
|
145
|
+
session.logout.assert_called_once()
|