From 1c573c3de59436c9d7c6191b99d0fdc6f445d49d Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Thu, 5 Nov 2026 15:23:31 +0000 Subject: [PATCH] Regenerate session IDs before saving authenticated users --- README.md | 2 + src/Authenticator.php | 16 +++ src/GlobalSessionContainer.php | 9 ++ src/SessionRegenerationException.php | 4 + test/phpunit/AuthenticatorTest.php | 4 + test/phpunit/SessionRotationTest.php | 191 +++++++++++++++++++++++++++ 6 files changed, 226 insertions(+) create mode 100644 src/SessionRegenerationException.php create mode 100644 test/phpunit/SessionRotationTest.php diff --git a/README.md b/README.md index 9778c37..9843287 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,8 @@ else { Load the autoloader before starting the session, and construct `Authenticator` before sending output. Its constructor processes returning authentication responses and can redirect immediately. Run the same setup on every route that can receive a login response. +Successful authentication regenerates the native session ID before storing the user and removes the old session. Unrelated session data is preserved. With a custom session container, pass a `regenerateSession` callback which replaces the ID, invalidates the old session and preserves the current data. If rotation fails, throw an exception so authentication stops. Ordinary session restoration does not rotate the ID. + `getAuthUser()` provides the read-only `id` and `email` properties. Use the user ID to associate local records with an account, and keep permission checks in the application. The `onAuthenticated` callback runs when a new authentication completes, before the client removes the response parameter with a redirect. It does not run when a user is restored from the session. The callback is marked before invocation and is not retried automatically if it throws. diff --git a/src/Authenticator.php b/src/Authenticator.php index 482bd81..24d3e23 100644 --- a/src/Authenticator.php +++ b/src/Authenticator.php @@ -26,6 +26,7 @@ class Authenticator { private UriInterface $currentUriPath; private ?UriInterface $returnUri = null; private readonly ?Closure $onAuthenticated; + private readonly Closure $regenerateSession; private readonly string $deploymentId; private readonly string $secret; @@ -36,6 +37,7 @@ public function __construct( private ?SessionContainer $session = null, private ?RedirectHandler $redirectHandler = null, ?callable $onAuthenticated = null, + ?callable $regenerateSession = null, ) { $this->onAuthenticated = is_null($onAuthenticated) ? null @@ -45,6 +47,16 @@ public function __construct( $this->session = $this->session ?? new GlobalSessionContainer(); $this->redirectHandler = $redirectHandler ?? new RedirectHandler(); + $this->regenerateSession = is_null($regenerateSession) + ? function():void { + if(!$this->session instanceof GlobalSessionContainer) { + throw new SessionRegenerationException( + "Provide regenerateSession for a custom session container." + ); + } + $this->session->regenerate(); + } + : Closure::fromCallable($regenerateSession); if($sessionData = $this->session->get(SessionData::class)) { $this->sessionData = $sessionData; @@ -122,6 +134,7 @@ public function logout( public function fakeLogin(string $userId, ?string $email = null, string $redirectTo = "/"):void { $secretIv = new InitVector(); $token = new Token($this->secret, $secretIv); + ($this->regenerateSession)(); $sessionData = new SessionData($token); $this->session->set(SessionData::class, $sessionData); @@ -238,6 +251,9 @@ private function completeAuth():void { $data->{"id"}, $data->{"email"}, ); + if(!$this->isLoggedIn()) { + ($this->regenerateSession)(); + } $this->user = new User( $userData->getId(), $userData->getEmail(), diff --git a/src/GlobalSessionContainer.php b/src/GlobalSessionContainer.php index 2e3320b..9ab8f2f 100644 --- a/src/GlobalSessionContainer.php +++ b/src/GlobalSessionContainer.php @@ -11,4 +11,13 @@ public function __construct() { } parent::__construct($_SESSION); } + + public function regenerate():void { + if(session_status() !== PHP_SESSION_ACTIVE || headers_sent()) { + throw new SessionRegenerationException("An active session before output is required."); + } + if(!session_regenerate_id(true)) { + throw new SessionRegenerationException("Could not regenerate the session ID."); + } + } } diff --git a/src/SessionRegenerationException.php b/src/SessionRegenerationException.php new file mode 100644 index 0000000..08ca59d --- /dev/null +++ b/src/SessionRegenerationException.php @@ -0,0 +1,4 @@ +fakeLogin("user-id", redirectTo: "/destination"); diff --git a/test/phpunit/SessionRotationTest.php b/test/phpunit/SessionRotationTest.php new file mode 100644 index 0000000..f02768d --- /dev/null +++ b/test/phpunit/SessionRotationTest.php @@ -0,0 +1,191 @@ +sessionDirectory = sys_get_temp_dir() . "/authwave-rotation-" . bin2hex(random_bytes(8)); + mkdir($this->sessionDirectory); + session_id("known-anonymous-session"); + session_start([ + "save_path" => $this->sessionDirectory, + "use_cookies" => false, + "cache_limiter" => "", + ]); + } + + protected function tearDown():void { + if(session_status() === PHP_SESSION_ACTIVE) { + session_destroy(); + } + foreach(glob($this->sessionDirectory . "/*") as $file) { + unlink($file); + } + rmdir($this->sessionDirectory); + } + + private function responseUri(Token $token):string { + $cipher = sodium_crypto_secretbox( + '{"id":"user-id","email":"person@example.com"}', + $token->getSecretIv()->getBytes(), + str_repeat("s", 32), + ); + return "/callback?AUTHWAVE_RESPONSE_DATA=" . urlencode(base64_encode($cipher)); + } + + private function redirect():RedirectHandler { + return new class extends RedirectHandler { + public function redirect(UriInterface $uri, int $code = 303):void {} + }; + } + + public function testAuthenticationRotatesBeforeCallbackAndInvalidatesOldSession():void { + $token = new Token(str_repeat("s", 32)); + $_SESSION[SessionData::class] = new SessionData($token); + $_SESSION["basket"] = ["tea"]; + $oldId = session_id(); + $callbackId = null; + $uri = $this->responseUri($token); + + new Authenticator( + "deployment_" . str_repeat("s", 32), + $uri, + redirectHandler: $this->redirect(), + onAuthenticated: function() use (&$callbackId):void { + $callbackId = session_id(); + }, + ); + $newId = session_id(); + self::assertNotSame($oldId, $newId); + self::assertSame($newId, $callbackId); + self::assertSame(["tea"], $_SESSION["basket"]); + self::assertSame("user-id", $_SESSION[SessionData::class]->getData()->getId()); + session_write_close(); + + session_id($oldId); + session_start(); + $oldSession = new Authenticator( + "deployment_" . str_repeat("s", 32), $uri, redirectHandler: $this->redirect(), + ); + self::assertFalse($oldSession->isLoggedIn()); + self::assertArrayNotHasKey(SessionData::class, $_SESSION); + session_write_close(); + + session_id($newId); + session_start(); + $restored = new Authenticator("deployment_" . str_repeat("s", 32), "/"); + self::assertTrue($restored->isLoggedIn()); + self::assertSame($newId, session_id()); + } + + public function testInvalidCipherDoesNotRotate():void { + $_SESSION[SessionData::class] = new SessionData(new Token(str_repeat("s", 32))); + $id = session_id(); + try { + new Authenticator( + "deployment_" . str_repeat("s", 32), "/?AUTHWAVE_RESPONSE_DATA=invalid", + redirectHandler: $this->redirect(), + ); + self::fail("Expected decryption to fail"); + } + catch(\GT\Cipher\Message\DecryptionFailureException) {} + self::assertSame($id, session_id()); + } + + public function testFakeLoginRotatesBeforeStoringItsIdentity():void { + $id = session_id(); + $_SESSION["basket"] = ["tea"]; + $auth = new Authenticator( + "deployment_" . str_repeat("s", 32), "/", redirectHandler: $this->redirect(), + ); + $auth->fakeLogin("developer"); + self::assertNotSame($id, session_id()); + self::assertSame("developer", $_SESSION[SessionData::class]->getData()->getId()); + self::assertSame(["tea"], $_SESSION["basket"]); + } + + public function testCustomSessionMustSupplyRegeneration():void { + $token = new Token(str_repeat("s", 32)); + $data = [SessionData::class => new SessionData($token)]; + try { + new Authenticator( + "deployment_" . str_repeat("s", 32), $this->responseUri($token), + session: new SessionArrayWrapper($data), redirectHandler: $this->redirect(), + ); + self::fail("Expected a regeneration callback to be required"); + } + catch(SessionRegenerationException) {} + self::expectException(\Authwave\NotLoggedInException::class); + $data[SessionData::class]->getData(); + } + + public function testRotationFailureDoesNotStoreUserOrInvokeCallback():void { + $token = new Token(str_repeat("s", 32)); + $_SESSION[SessionData::class] = new SessionData($token); + $called = false; + try { + new Authenticator( + "deployment_" . str_repeat("s", 32), $this->responseUri($token), + redirectHandler: $this->redirect(), + onAuthenticated: function() use (&$called):void { $called = true; }, + regenerateSession: static function():void { throw new SessionRegenerationException(); }, + ); + self::fail("Expected rotation to fail"); + } + catch(SessionRegenerationException) {} + self::assertFalse($called); + self::expectException(\Authwave\NotLoggedInException::class); + $_SESSION[SessionData::class]->getData(); + } + + public function testDefaultContainerRequiresActiveNativeSessionForRotation():void { + $container = new GlobalSessionContainer(); + session_write_close(); + self::expectException(SessionRegenerationException::class); + $container->regenerate(); + } + + public function testCallbackFailureDoesNotRepeatRotationOrInvocation():void { + $token = new Token(str_repeat("s", 32)); + $_SESSION[SessionData::class] = new SessionData($token); + $uri = $this->responseUri($token); + $oldId = session_id(); + $calls = 0; + $callback = function() use (&$calls):void { + $calls++; + throw new \RuntimeException("Application failed"); + }; + try { + new Authenticator( + "deployment_" . str_repeat("s", 32), $uri, + redirectHandler: $this->redirect(), onAuthenticated: $callback, + ); + } + catch(\RuntimeException $exception) { + self::assertSame("Application failed", $exception->getMessage()); + } + $newId = session_id(); + self::assertNotSame($oldId, $newId); + new Authenticator( + "deployment_" . str_repeat("s", 32), $uri, + redirectHandler: $this->redirect(), onAuthenticated: $callback, + ); + self::assertSame($newId, session_id()); + self::assertSame(1, $calls); + } +}