Skip to content
Merged
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 @@ -75,6 +75,8 @@ Without an override, login requests the current URI. The provider accepts root-r

The `authwaveHost` constructor argument selects the provider and defaults to `login.authwave.com`. For a self-hosted provider, supply its scheme, host and optional port, such as `https://login.example.com`.

A token can encrypt only its first complete request. Repeating the same request is allowed; a different payload raises TokenReuseException. Create a fresh token for a different action or return query, and do not copy tokens or reuse supplied IVs. Session serialisation retains the binding. Tokens restored from older sessions without a binding can still decrypt responses, but require a fresh token to start another request.

Logging out
-----------

Expand Down
3 changes: 2 additions & 1 deletion src/Authenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,14 @@ public function login(?Token $token = null):void {
$token = new Token($this->secret);
}

$loginUri = $this->getLoginUri($token);
$this->sessionData = new SessionData(
$token,
null,
($this->returnUri ?? $this->currentUriPath)->getQuery(),
);
$this->session->set(SessionData::class, $this->sessionData);
$this->redirectHandler->redirect($this->getLoginUri($token));
$this->redirectHandler->redirect($loginUri);
}

public function logout(
Expand Down
19 changes: 16 additions & 3 deletions src/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,26 @@ class Token {
private Key $key;
private InitVector $secretSessionIv;
private InitVector $iv;
private ?string $requestPlaintext;

public function __construct(
string $secret,
?InitVector $sessionIv = null,
?InitVector $iv = null,
) {
$this->key = new Key($secret);
$this->requestPlaintext = null;
$this->secretSessionIv = $sessionIv ?? new InitVector();
$this->iv = $iv ?? new InitVector();
}

public function __wakeup():void {
// Older sessions cannot tell us which plaintext has already used this nonce.
if(!array_key_exists("requestPlaintext", get_object_vars($this))) {
$this->requestPlaintext = "";
}
}

public function getIv():InitVector {
return $this->iv;
}
Expand All @@ -41,9 +50,13 @@ public function getSecretIv():InitVector {
* the client application in the querystring.
*/
public function generateRequestCipher(string $message = ""):CipherText {
// TODO: $message should probably always be a KVP, so we can build up the querystring message here without concatenating.
$plainTextMessage = new PlainTextMessage($message . "&secretIv=" . $this->getSecretIv(), $this->getIv());
return $plainTextMessage->encrypt($this->key);
$plaintext = $message . "&secretIv=" . $this->getSecretIv();
if(!is_null($this->requestPlaintext) && $this->requestPlaintext !== $plaintext) {
throw new TokenReuseException("Create a new token for a different request.");
}
$cipher = (new PlainTextMessage($plaintext, $this->getIv()))->encrypt($this->key);
$this->requestPlaintext = $plaintext;
return $cipher;
}
// The response cipher is send from the remote provider back to the client
// application after a successful authentication and includes a serialised
Expand Down
4 changes: 4 additions & 0 deletions src/TokenReuseException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace Authwave;

class TokenReuseException extends AuthwaveException {}
116 changes: 116 additions & 0 deletions test/phpunit/TokenNonceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<?php
namespace Authwave\Test;

use Authwave\Authenticator;
use Authwave\GlobalSessionContainer;
use Authwave\RedirectHandler;
use Authwave\SessionData;
use Authwave\Token;
use Authwave\TokenReuseException;
use Authwave\ProviderUri\LoginUri;
use Authwave\ProviderUri\LogoutUri;
use GT\Cipher\EncryptionFailureException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

class TokenNonceTest extends TestCase {
/** @return array<string, array{string, string}> */
public static function changedRequests():array {
return [
"changed action" => ["action=login", "action=logout"],
"changed return query" => ["action=login&returnQuery=page%3D1", "action=login&returnQuery=page%3D2"],
"empty first message" => ["", "action=login"],
"empty second message" => ["action=login", ""],
];
}

#[DataProvider("changedRequests")]
public function testDifferentRequestsCannotShareToken(string $first, string $second):void {
$token = new Token(str_repeat("s", 32));
$iv = $token->getIv()->getBytes();
$cipher = (string)$token->generateRequestCipher($first);
try {
$token->generateRequestCipher($second);
self::fail("Expected token reuse to be rejected");
}
catch(TokenReuseException) {}
self::assertSame($iv, $token->getIv()->getBytes());
self::assertSame($cipher, (string)$token->generateRequestCipher($first));
}

public function testSessionSerialisationPreservesTheRequestBinding():void {
$token = new Token(str_repeat("s", 32));
$cipher = (string)$token->generateRequestCipher("action=login");
/** @var SessionData $restored */
$restored = unserialize(serialize(new SessionData($token)));
self::assertSame($cipher, (string)$restored->getToken()->generateRequestCipher("action=login"));
self::expectException(TokenReuseException::class);
$restored->getToken()->generateRequestCipher("action=logout");
}

public function testUnusedTokenCanBeRestoredBeforeFirstEncryption():void {
/** @var Token $token */
$token = unserialize(serialize(new Token(str_repeat("s", 32))));
self::assertNotSame("", (string)$token->generateRequestCipher("action=login"));
}

public function testLegacySessionCanDecryptButCannotReuseUnknownRequestNonce():void {
$secret = str_repeat("s", 32);
$token = new Token($secret);
$fields = "";
foreach(["key", "secretSessionIv", "iv"] as $name) {
$value = (new \ReflectionProperty(Token::class, $name))->getValue($token);
$fields .= serialize("\0" . Token::class . "\0" . $name) . serialize($value);
}
/** @var Token $legacy */
$legacy = unserialize('O:' . strlen(Token::class) . ':"' . Token::class . '":3:{' . $fields . '}');
$cipher = sodium_crypto_secretbox(
'{"id":"user-id","email":"person@example.com"}',
$token->getIv()->getBytes(), $secret,
);
self::assertSame("user-id", $legacy->decode(base64_encode($cipher))->getId());
self::expectException(TokenReuseException::class);
$legacy->generateRequestCipher("action=login");
}

public function testFailedEncryptionDoesNotBindTheToken():void {
$token = new Token("");
$failures = 0;
foreach(["action=login", "action=logout"] as $message) {
try {
$token->generateRequestCipher($message);
self::fail("Expected invalid key to fail encryption");
}
catch(EncryptionFailureException) { $failures++; }
}
self::assertSame(2, $failures);
}

public function testLoginAndLogoutBuildersRequireSeparateTokens():void {
$token = new Token(str_repeat("s", 32));
$uri = new LoginUri($token, "/callback", "deployment");
self::assertSame((string)$uri, (string)new LoginUri($token, "/callback", "deployment"));
self::expectException(TokenReuseException::class);
new LogoutUri($token, "/callback", "deployment");
}

public function testRejectedLoginLeavesExistingExchangeUntouched():void {
$secret = str_repeat("s", 32);
$pending = new SessionData(new Token($secret));
$_SESSION = [SessionData::class => $pending, "basket" => ["tea"]];
$auth = new Authenticator(
"deployment_" . $secret, "/callback",
session: new GlobalSessionContainer(),
redirectHandler: self::createStub(RedirectHandler::class),
);
$used = new Token($secret);
$used->generateRequestCipher("action=logout");
try {
$auth->login($used);
self::fail("Expected token reuse to be rejected");
}
catch(TokenReuseException) {}
self::assertSame($pending, $_SESSION[SessionData::class]);
self::assertSame(["tea"], $_SESSION["basket"]);
}
}
Loading