Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions src/Authenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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
Expand All @@ -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;

Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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(),
Expand Down
9 changes: 9 additions & 0 deletions src/GlobalSessionContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
}
}
}
4 changes: 4 additions & 0 deletions src/SessionRegenerationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace Authwave;

class SessionRegenerationException extends AuthwaveException {}
4 changes: 4 additions & 0 deletions test/phpunit/AuthenticatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ public function testCompleteAuth() {
LoginUri::DEFAULT_BASE_REMOTE_URI,
null,
$redirectHandler,
regenerateSession: static function():void {},
onAuthenticated: function(AuthUser $user) use (&$authenticatedUser):void {
$authenticatedUser = $user;
},
Expand Down Expand Up @@ -423,6 +424,7 @@ public function testAuthenticationCallbackIsAtMostOnceWhenItThrows():void {
$currentUri,
redirectHandler: self::createStub(RedirectHandler::class),
onAuthenticated: $callback,
regenerateSession: static function():void {},
);
self::fail("Expected the application callback to throw");
}
Expand All @@ -439,6 +441,7 @@ public function testAuthenticationCallbackIsAtMostOnceWhenItThrows():void {
$currentUri,
redirectHandler: $redirectHandler,
onAuthenticated: $callback,
regenerateSession: static function():void {},
);

self::assertSame(1, $callbackCount);
Expand Down Expand Up @@ -587,6 +590,7 @@ public function testFakeLoginStoresUserAndRemovesCurrentQuery():void {
"deployment_" . str_repeat("s", 32),
"/current?filter=active",
redirectHandler: $redirectHandler,
regenerateSession: static function():void {},
);

$sut->fakeLogin("user-id", redirectTo: "/destination");
Expand Down
191 changes: 191 additions & 0 deletions test/phpunit/SessionRotationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
<?php
namespace Authwave\Test;

use Authwave\Authenticator;
use Authwave\GlobalSessionContainer;
use Authwave\RedirectHandler;
use Authwave\SessionData;
use Authwave\SessionRegenerationException;
use Authwave\Token;
use GT\Session\SessionArrayWrapper;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\UriInterface;

#[RunTestsInSeparateProcesses]
#[PreserveGlobalState(false)]
class SessionRotationTest extends TestCase {
private string $sessionDirectory;

protected function setUp():void {
$this->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);
}
}
Loading