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 @@ -104,3 +104,5 @@ composer test
```

The test script runs PHPUnit, PHPStan, PHP_CodeSniffer and PHPMD. To run the unit tests alone, use `composer phpunit`.

Client keys must contain a non-empty deployment ID, an underscore and a 32-byte secret. Invalid keys throw `InvalidClientKeyException` when constructing the authenticator. Callback response parameters must be non-empty strings containing base64-encoded ciphertext. Invalid parameter shapes or encoding throw `ResponseCipherDecryptionException`; invalid decrypted JSON or identity field types throw `InvalidUserDataSerializationException`. Both callback completion and `Token::decode()` require a string identity (`uuid` or `id`) and a string `email`. Invalid responses leave the pending session unchanged and do not invoke the authentication callback.
30 changes: 20 additions & 10 deletions src/Authenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,13 @@ public function __construct(
$this->onAuthenticated = is_null($onAuthenticated)
? null
: Closure::fromCallable($onAuthenticated);
$this->deploymentId = substr($clientKey, 0, strrpos($clientKey, "_"));
$this->secret = substr(strrchr($clientKey, "_"), 1);
$separator = strrpos($clientKey, "_");
if($separator === false || $separator === 0
|| strlen(substr($clientKey, $separator + 1)) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
throw new InvalidClientKeyException("Expected a deployment ID and a 32-byte secret separated by an underscore.");
}
$this->deploymentId = substr($clientKey, 0, $separator);
$this->secret = substr($clientKey, $separator + 1);

$this->session = $this->session ?? new GlobalSessionContainer();
$this->redirectHandler = $redirectHandler ?? new RedirectHandler();
Expand Down Expand Up @@ -218,10 +223,14 @@ public function getAdminUri():UriInterface {
private function completeAuth():void {
$queryData = $this->getQueryData();

if(!$queryData) {
if(is_null($queryData)) {
return;
}

if(base64_decode($queryData, true) === false) {
throw new ResponseCipherDecryptionException("Invalid response cipher encoding.");
}

if(!isset($this->sessionData)) {
$this->tidyResponseData();
return;
Expand All @@ -233,11 +242,7 @@ private function completeAuth():void {
$encrypted = new EncryptedMessage($queryData, $secretSessionIv);
$key = new Key($this->secret);
$decrypted = $encrypted->decrypt($key);
$data = json_decode($decrypted);
$userData = new UserResponseData(
$data->{"id"},
$data->{"email"},
);
$userData = UserResponseData::fromJson((string)$decrypted);
$this->user = new User(
$userData->getId(),
$userData->getEmail(),
Expand Down Expand Up @@ -277,12 +282,17 @@ private function getQueryData():?string {

$queryParts = [];
parse_str($queryString, $queryParts);
if(empty($queryParts[self::RESPONSE_QUERY_PARAMETER])) {
if(!array_key_exists(self::RESPONSE_QUERY_PARAMETER, $queryParts)) {
return null;
}

$value = $queryParts[self::RESPONSE_QUERY_PARAMETER];
if(!is_string($value) || $value === "") {
throw new ResponseCipherDecryptionException("Expected a non-empty response cipher string.");
}

return strtr(
$queryParts[self::RESPONSE_QUERY_PARAMETER],
$value,
" ",
"+",
);
Expand Down
4 changes: 4 additions & 0 deletions src/InvalidClientKeyException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace Authwave;

class InvalidClientKeyException extends AuthwaveException {}
14 changes: 14 additions & 0 deletions src/ResponseData/UserResponseData.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php
namespace Authwave\ResponseData;

use Authwave\InvalidUserDataSerializationException;

class UserResponseData extends BaseResponseData {
public function __construct(
private readonly string $uuid,
Expand All @@ -10,6 +12,18 @@ public function __construct(
parent::__construct($message);
}

public static function fromJson(string $json):self {
$data = json_decode($json);
if(!is_object($data) || !isset($data->email) || !is_string($data->email)) {
throw new InvalidUserDataSerializationException();
}
$id = $data->uuid ?? $data->id ?? null;
if(!is_string($id)) {
throw new InvalidUserDataSerializationException();
}
return new self($id, $data->email);
}

public function getId():string {
return $this->uuid;
}
Expand Down
21 changes: 4 additions & 17 deletions src/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,28 +51,15 @@ public function generateRequestCipher(string $message = ""):CipherText {
// encrypting the original request cipher.

public function decode(string $base64cipher):BaseResponseData {
if($base64cipher === "" || base64_decode($base64cipher, true) === false) {
throw new ResponseCipherDecryptionException("Invalid response cipher encoding.");
}
$encryptedMessage = new EncryptedMessage(
$base64cipher,
$this->iv,
);
$decrypted = $encryptedMessage->decrypt($this->key);

$data = json_decode((string)$decrypted);
if(!is_object($data)
|| !isset($data->email)
|| !is_string($data->email)
|| (!isset($data->uuid) && !isset($data->id))) {
throw new InvalidUserDataSerializationException();
}

$id = $data->uuid ?? $data->id;
if(!is_string($id)) {
throw new InvalidUserDataSerializationException();
}

return new UserResponseData(
$id,
$data->email,
);
return UserResponseData::fromJson((string)$decrypted);
}
}
38 changes: 19 additions & 19 deletions test/phpunit/AuthenticatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ public function testResponseCipherPreservesRawPlusCharacters():void {
public function testConstructWithDefaultSessionNotStarted() {
self::expectException(SessionNotStartedException::class);
new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/"
);
}

public function testIsLoggedInFalseByDefault() {
$_SESSION = [];
$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/"
);
self::assertFalse($sut->isLoggedIn());
Expand All @@ -66,7 +66,7 @@ public function testIsLoggedInTrueWhenSessionDataSet() {
];

$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/"
);
self::assertTrue($sut->isLoggedIn());
Expand Down Expand Up @@ -100,7 +100,7 @@ public function testLoginRedirectsWithCorrectQueryString() {
$_SESSION = [];

$deploymentId = uniqid("deployment-");
$key = $deploymentId . "_secret";
$key = $deploymentId . "_" . str_repeat("s", 32);
$currentPath = uniqid("/path/") . "?signup=free";

$cipherString = "example-cipher";
Expand Down Expand Up @@ -158,7 +158,7 @@ public function testGetUuid() {
SessionData::class => $sessionData,
];
$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/"
);
self::assertEquals($exampleId, $sut->getAuthUser()->id);
Expand All @@ -167,7 +167,7 @@ public function testGetUuid() {
public function testGetEmailThrowsExceptionWhenNotLoggedIn() {
$_SESSION = [];
$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/"
);
self::expectException(NotLoggedInException::class);
Expand All @@ -188,7 +188,7 @@ public function testGetEmail() {
SessionData::class => $sessionData,
];
$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/"
);
self::assertEquals($expectedEmail, $sut->getAuthUser()->email);
Expand Down Expand Up @@ -246,7 +246,7 @@ public function testCompleteAuthNotAffectedByQueryString() {
$_SESSION = [];

new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/example-path/?filter=something",
LoginUri::DEFAULT_BASE_REMOTE_URI,
null,
Expand All @@ -259,7 +259,7 @@ public function testAcceptsPsrUriInterfaceForCurrentUriPath():void {
$currentUriPath = self::createStub(UriInterface::class);
$currentUriPath->method("__toString")->willReturn("/psr-path");
$currentUriPath->method("getQuery")->willReturn("");
$sut = new Authenticator("deployment_secret", $currentUriPath);
$sut = new Authenticator("deployment_" . str_repeat("s", 32), $currentUriPath);
$token = self::createStub(Token::class);
$token->method("generateRequestCipher")->willReturn(self::createStub(CipherText::class));
$token->method("getIv")->willReturn(self::createStub(InitVector::class));
Expand All @@ -274,7 +274,7 @@ public function testAcceptsPsrUriInterfaceForCurrentUriPath():void {

public function testSetReturnUriOverridesLoginReturnLocation():void {
$_SESSION = [];
$sut = new Authenticator("deployment_secret", "/current-path");
$sut = new Authenticator("deployment_" . str_repeat("s", 32), "/current-path");
$sut->setReturnUri("/after-login?source=authwave");
$token = self::createStub(Token::class);
$token->method("generateRequestCipher")->willReturn(self::createStub(CipherText::class));
Expand All @@ -291,7 +291,7 @@ public function testSetReturnUriOverridesLoginReturnLocation():void {
public function testGetAdminUri() {
$_SESSION = [];
$auth = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/example-path",
BaseProviderUri::DEFAULT_BASE_REMOTE_URI
);
Expand All @@ -311,7 +311,7 @@ public function testCompleteAuthNotLoggedIn() {
$redirectHandler = self::createStub(RedirectHandler::class);
self::expectException(NotLoggedInException::class);
$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
$currentUri,
LoginUri::DEFAULT_BASE_REMOTE_URI,
null,
Expand All @@ -329,7 +329,7 @@ public function testCompleteAuth() {
$keyBytes = str_repeat("0", SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$ivBytes = str_repeat("1", SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plainTextMessage = json_encode([
"id" => 123,
"id" => "123",
"email" => "person@example.com",
]);
$encryptedMessage = sodium_crypto_secretbox(
Expand Down Expand Up @@ -458,7 +458,7 @@ public function testLoginDoesNothingWhenAlreadyLoggedIn() {
->method("redirect");

$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/",
LoginUri::DEFAULT_BASE_REMOTE_URI,
null,
Expand All @@ -483,7 +483,7 @@ public function testLoginDoesNothingWhenAlreadyLoggedIn() {
public function testGetUuidThrowsExceptionWhenNotLoggedIn() {
$_SESSION = [];
$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/"
);
self::expectException(NotLoggedInException::class);
Expand Down Expand Up @@ -513,7 +513,7 @@ public function testLogoutCallsLogoutUri() {
}));

$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/",
LoginUri::DEFAULT_BASE_REMOTE_URI,
null,
Expand Down Expand Up @@ -608,7 +608,7 @@ public function testLogoutUsesRequestedRedirect(
->with(self::isInstanceOf(UriInterface::class));

$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"https://example.com/current/path?old=value",
LoginUri::DEFAULT_BASE_REMOTE_URI,
null,
Expand Down Expand Up @@ -660,7 +660,7 @@ public function testLoginRedirects() {
));

$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/",
LoginUri::DEFAULT_BASE_REMOTE_URI,
null,
Expand Down Expand Up @@ -694,7 +694,7 @@ public function testLoginRedirectsLocalhost() {
));

$sut = new Authenticator(
"test-key",
"deployment_" . str_repeat("s", 32),
"/",
"http://localhost:8081",
null,
Expand Down
Loading
Loading