Skip to content

Commit 3f59932

Browse files
committed
Regenerate session IDs before saving authenticated users
1 parent 9219631 commit 3f59932

12 files changed

Lines changed: 202 additions & 12 deletions

‎PARITY.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ This Python client implements the current PHP identity contract (`id` and `email
4040

4141
## Runtime adaptations
4242

43+
Successful authentication now regenerates the session ID before saving the identity and invalidates the old session. Unrelated data is preserved, and ordinary restoration keeps its ID. Custom session containers must provide regeneration, and custom runtime stores must support deleting the old ID.
44+
4345
There is no implicit global browser session. Callers provide a per-request container or use a framework adapter. JSON serialization restores tokens and response objects. Session records contain secrets and belong exclusively in server-side storage.
4446

4547
Redirects transfer control to adapters, which save before sending a 303. Application callbacks are synchronous. Production stores enforce expiration and should serialize concurrent mutations to the same session, matching the sequential processing assumed by the callback marker.

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ The complete provider-issued key belongs on the server. The final underscore sep
2525

2626
`MemorySessionStore` is for development. Production applications need a shared persistent `SessionStore` and HTTPS; cookies are Secure by default. Authentication data stays in server-side storage; never put serialized tokens in browser cookies. Authentication callbacks are synchronous and run at most once per exchange under sequential session processing.
2727

28+
Successful authentication replaces the session ID before saving the identity and invalidates the old ID. Other session data is preserved. Custom SessionStore implementations must provide delete(id), and custom GlobalSessionContainer mappings must supply a synchronous regeneration callback as the second argument. The callback must replace the ID, invalidate the old session and preserve the mapping; raising an exception stops authentication. Ordinary session restoration does not rotate the ID.
29+
2830
## Development
2931

3032
```bash

‎authwave/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from .errors import (
66
AuthwaveException,
77
SessionNotStartedException,
8+
SessionRegenerationException,
89
NotLoggedInException,
910
InsecureProtocolException,
1011
InvalidUserDataSerializationException,

‎authwave/authenticator.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ def fake_login(
108108
) -> None:
109109
iv = InitVector()
110110
token = Token(self._secret, iv)
111+
self._session.regenerate()
111112
self._session.set(SessionData.STORE_KEY, SessionData(token))
112113
data = UserResponseData(
113114
user_id, email if email is not None else self.FAKE_EMAIL
@@ -167,6 +168,8 @@ def scalar(value):
167168
if not isinstance(data, dict):
168169
raise TypeError("Expected authentication object")
169170
user_data = UserResponseData(scalar(data.get("id")), scalar(data.get("email")))
171+
if not self.is_logged_in():
172+
self._session.regenerate()
170173
self._user = User(user_data.id, user_data.email)
171174
was_invoked = self._session_data.has_invoked_authentication_callback()
172175
next_data = SessionData(token, user_data, return_query)

‎authwave/errors.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,7 @@ def __init__(self, uri: str, code: int = 303):
4343
class RedirectHandler:
4444
def redirect(self, uri: str, code: int = 303) -> None:
4545
raise RedirectSignal(str(uri), code)
46+
47+
48+
class SessionRegenerationException(AuthwaveException):
49+
pass

‎authwave/runtime.py‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
class SessionStore(Protocol):
1717
def load(self, id: str) -> dict | None: ...
1818
def save(self, id: str, data: dict, expires_at: float) -> None: ...
19+
def delete(self, id: str) -> None: ...
1920

2021

2122
class MemorySessionStore:
@@ -35,6 +36,10 @@ def load(self, id: str) -> dict | None:
3536
return None
3637
return copy.deepcopy(entry[1])
3738

39+
def delete(self, id: str) -> None:
40+
with self._lock:
41+
self._entries.pop(id, None)
42+
3843
def save(self, id: str, data: dict, expires_at: float) -> None:
3944
# Reject non-JSON session values before committing anything.
4045
value = json.loads(json.dumps(data))
@@ -69,15 +74,23 @@ def __init__(self, cookie_header: str, options: SessionOptions):
6974
else None
7075
)
7176
self.id = candidate if stored is not None else secrets.token_hex(32)
72-
self.data = stored if stored is not None else {}
73-
self.container = GlobalSessionContainer(self.data)
77+
self.data = copy.deepcopy(stored) if stored is not None else {}
78+
self._previous_ids = []
79+
self.container = GlobalSessionContainer(self.data, self.regenerate)
7480

7581
def authenticator(self, path: str, auth_options: dict) -> Authenticator:
7682
return Authenticator(
7783
current_uri_path=path, session=self.container, **auth_options
7884
)
7985

86+
def regenerate(self) -> None:
87+
new_id = secrets.token_hex(32)
88+
self._previous_ids.append(self.id)
89+
self.id = new_id
90+
8091
def commit(self) -> None:
92+
for old_id in self._previous_ids:
93+
self.options.store.delete(old_id)
8194
self.options.store.save(
8295
self.id, self.data, time.time() + self.options.ttl_seconds
8396
)

‎authwave/session.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
from .errors import NotLoggedInException, SessionNotStartedException
1+
from .errors import (
2+
NotLoggedInException,
3+
SessionNotStartedException,
4+
SessionRegenerationException,
5+
)
26
from .token import Token
37
from .user import UserResponseData, BaseResponseData
48

@@ -62,10 +66,11 @@ def from_dict(cls, value: dict) -> "SessionData":
6266
class GlobalSessionContainer:
6367
"""Wrap an existing request-scoped mapping, never a process global."""
6468

65-
def __init__(self, data=None):
69+
def __init__(self, data=None, regenerate=None):
6670
if data is None:
6771
raise SessionNotStartedException()
6872
self.data = data
73+
self._regenerate = regenerate
6974

7075
def get(self, key: str):
7176
value = self.data.get(key)
@@ -82,5 +87,10 @@ def contains(self, key: str) -> bool:
8287
def remove(self, key: str) -> None:
8388
self.data.pop(key, None)
8489

90+
def regenerate(self) -> None:
91+
if self._regenerate is None:
92+
raise SessionRegenerationException("Supply a session regeneration callback")
93+
self._regenerate()
94+
8595

8696
SessionArrayWrapper = GlobalSessionContainer

‎tests/fixtures/php-oracle.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ class RecordingRedirect extends RedirectHandler {
99
public array $redirects = [];
1010
public function redirect(UriInterface $uri, int $code = 303):void { $this->redirects[] = [(string)$uri, $code]; }
1111
}
12+
// These fixtures use in-memory state rather than a native browser session ID.
13+
class OracleSession extends \Authwave\GlobalSessionContainer {
14+
public function regenerate():void {}
15+
}
1216
$cases = json_decode(stream_get_contents(STDIN), true);
1317
$out = [];
1418
foreach($cases as $index => $case) {
@@ -27,7 +31,7 @@ public function redirect(UriInterface $uri, int $code = 303):void { $this->redir
2731
}
2832
$error = null; $auth = null;
2933
try {
30-
$auth = new Authenticator('deployment_with_underscores_'.$secret, $uri, $case['host'] ?? 'login.authwave.com', redirectHandler:$redirect, onAuthenticated:($case['callback'] ?? false) ? $callback : null);
34+
$auth = new Authenticator('deployment_with_underscores_'.$secret, $uri, $case['host'] ?? 'login.authwave.com', redirectHandler:$redirect, session:new OracleSession(), onAuthenticated:($case['callback'] ?? false) ? $callback : null);
3135
if(isset($case['returnUri'])) $auth->setReturnUri($case['returnUri']);
3236
if(($case['action'] ?? '') === 'login') $auth->login($token);
3337
if(($case['action'] ?? '') === 'logout') $auth->logout($case['redirectTo'] ?? null, $token);

‎tests/test_core.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def test_missing_state():
3333
SessionData().get_token()
3434
with pytest.raises(NotLoggedInException):
3535
SessionData().get_data()
36-
auth = Authenticator(KEY, "/", session=GlobalSessionContainer({}))
36+
auth = Authenticator(KEY, "/", session=GlobalSessionContainer({}, lambda: None))
3737
with pytest.raises(NotLoggedInException):
3838
auth.get_auth_user()
3939
with pytest.warns(DeprecationWarning), pytest.raises(NotLoggedInException):
@@ -75,7 +75,7 @@ def test_tokens_and_decoding():
7575
def test_session_roundtrip_and_callback_failure():
7676
token = Token(SECRET)
7777
session = {}
78-
container = GlobalSessionContainer(session)
78+
container = GlobalSessionContainer(session, lambda: None)
7979
container.set(SessionData.STORE_KEY, SessionData(token, return_query="x=%7e&flag"))
8080
calls = []
8181

@@ -91,7 +91,7 @@ def callback(user):
9191
path = "/?AUTHWAVE_RESPONSE_DATA=" + quote_plus(cipher)
9292
with pytest.raises(RuntimeError):
9393
Authenticator(KEY, path, session=container, on_authenticated=callback)
94-
restored = GlobalSessionContainer(json.loads(json.dumps(session)))
94+
restored = GlobalSessionContainer(json.loads(json.dumps(session)), lambda: None)
9595
assert restored.get(SessionData.STORE_KEY).has_invoked_authentication_callback()
9696
record = Record()
9797
auth = Authenticator(
@@ -113,15 +113,15 @@ def test_fake_login_and_logout():
113113
auth = Authenticator(
114114
KEY,
115115
"/current?old=1",
116-
session=GlobalSessionContainer(session),
116+
session=GlobalSessionContainer(session, lambda: None),
117117
redirect_handler=record,
118118
)
119119
auth.fake_login("dev")
120120
assert not auth.is_logged_in()
121121
next_auth = Authenticator(
122122
KEY,
123123
record.destinations[0][0],
124-
session=GlobalSessionContainer(session),
124+
session=GlobalSessionContainer(session, lambda: None),
125125
redirect_handler=record,
126126
)
127127
assert next_auth.get_auth_user().email == Authenticator.FAKE_EMAIL
@@ -132,7 +132,7 @@ def test_fake_login_and_logout():
132132

133133

134134
def test_default_redirect_and_admin():
135-
auth = Authenticator(KEY, "/", session=GlobalSessionContainer({}))
135+
auth = Authenticator(KEY, "/", session=GlobalSessionContainer({}, lambda: None))
136136
assert str(auth.get_admin_uri()) == "https://login.authwave.com/admin/"
137137
with pytest.raises(RedirectSignal) as result:
138138
auth.login()

‎tests/test_integrations.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,30 @@ def app(environ, start_response):
110110
client = Client(AuthwaveWSGI(app, options, client_key=KEY), Response)
111111
invoke = lambda path: client.get(path)
112112
body = lambda response: response.json
113+
from http.cookies import SimpleCookie
114+
import time
115+
116+
def session_id(response):
117+
if framework == "django":
118+
return response.cookies["authwave.sid"].value
119+
values = SimpleCookie()
120+
values.load(response.headers["Set-Cookie"])
121+
return values["authwave.sid"].value
122+
113123
initial = invoke("/login")
124+
old_id = session_id(initial)
125+
pending = store.load(old_id)
126+
pending["basket"] = ["tea"]
127+
store.save(old_id, pending, time.time() + 86400)
114128
assert initial.status_code == 303
115129
completed = invoke(provider_response(initial.headers["Location"]))
116130
assert completed.status_code == 303
131+
new_id = session_id(completed)
132+
assert new_id != old_id
133+
assert store.load(old_id) is None
134+
assert store.load(new_id)["basket"] == ["tea"]
117135
restored = invoke("/callback")
136+
assert session_id(restored) == new_id
118137
assert body(restored) == {"loggedIn": True, "id": "user-id"}
119138
assert restored.headers["Cache-Control"] == "no-store"
120139
assert invoke("/logout").status_code == 303
@@ -176,6 +195,9 @@ def test_store_failure_prevents_wsgi_output():
176195
from authwave.integrations.wsgi import AuthwaveWSGI
177196

178197
class FailingStore:
198+
def delete(self, id):
199+
pass
200+
179201
def load(self, id):
180202
return None
181203

0 commit comments

Comments
 (0)