diff --git a/README.md b/README.md index 9778c37..81ab060 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/Authenticator.php b/src/Authenticator.php index 482bd81..0769431 100644 --- a/src/Authenticator.php +++ b/src/Authenticator.php @@ -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(); @@ -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; @@ -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(), @@ -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, " ", "+", ); diff --git a/src/InvalidClientKeyException.php b/src/InvalidClientKeyException.php new file mode 100644 index 0000000..2c747a2 --- /dev/null +++ b/src/InvalidClientKeyException.php @@ -0,0 +1,4 @@ +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; } diff --git a/src/Token.php b/src/Token.php index 4c17c9a..bb65afd 100644 --- a/src/Token.php +++ b/src/Token.php @@ -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); } } diff --git a/test/phpunit/AuthenticatorTest.php b/test/phpunit/AuthenticatorTest.php index b24ef18..06c988b 100644 --- a/test/phpunit/AuthenticatorTest.php +++ b/test/phpunit/AuthenticatorTest.php @@ -39,7 +39,7 @@ public function testResponseCipherPreservesRawPlusCharacters():void { public function testConstructWithDefaultSessionNotStarted() { self::expectException(SessionNotStartedException::class); new Authenticator( - "test-key", + "deployment_" . str_repeat("s", 32), "/" ); } @@ -47,7 +47,7 @@ public function testConstructWithDefaultSessionNotStarted() { public function testIsLoggedInFalseByDefault() { $_SESSION = []; $sut = new Authenticator( - "test-key", + "deployment_" . str_repeat("s", 32), "/" ); self::assertFalse($sut->isLoggedIn()); @@ -66,7 +66,7 @@ public function testIsLoggedInTrueWhenSessionDataSet() { ]; $sut = new Authenticator( - "test-key", + "deployment_" . str_repeat("s", 32), "/" ); self::assertTrue($sut->isLoggedIn()); @@ -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"; @@ -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); @@ -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); @@ -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); @@ -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, @@ -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)); @@ -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)); @@ -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 ); @@ -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, @@ -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( @@ -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, @@ -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); @@ -513,7 +513,7 @@ public function testLogoutCallsLogoutUri() { })); $sut = new Authenticator( - "test-key", + "deployment_" . str_repeat("s", 32), "/", LoginUri::DEFAULT_BASE_REMOTE_URI, null, @@ -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, @@ -660,7 +660,7 @@ public function testLoginRedirects() { )); $sut = new Authenticator( - "test-key", + "deployment_" . str_repeat("s", 32), "/", LoginUri::DEFAULT_BASE_REMOTE_URI, null, @@ -694,7 +694,7 @@ public function testLoginRedirectsLocalhost() { )); $sut = new Authenticator( - "test-key", + "deployment_" . str_repeat("s", 32), "/", "http://localhost:8081", null, diff --git a/test/phpunit/InputValidationTest.php b/test/phpunit/InputValidationTest.php new file mode 100644 index 0000000..58c6e9d --- /dev/null +++ b/test/phpunit/InputValidationTest.php @@ -0,0 +1,105 @@ + ["tea"]]; + $before = $_SESSION; + $redirect = self::createMock(RedirectHandler::class); + $redirect->expects(self::never())->method("redirect"); + try { + new Authenticator("deployment_" . str_repeat("s", 32), + "/?AUTHWAVE_RESPONSE_DATA" . $suffix, redirectHandler: $redirect); + self::fail("Expected invalid callback input to fail"); + } + catch(ResponseCipherDecryptionException) {} + self::assertSame($before, $_SESSION); + } + + public static function invalidPayloads():array { + return [["not json"], ["null"], ["[]"], ["{}"], + ['{"id":123,"email":"person@example.com"}'], + ['{"id":"user","email":false}'], + ['{"id":[],"email":"person@example.com"}'], + ['{"id":"user"}'], ['{"email":"person@example.com"}']]; + } + + #[DataProvider("invalidPayloads")] + public function testBothResponsePathsRejectInvalidPayloads(string $json):void { + $key = str_repeat("s", 32); + $iv = new InitVector(); + $token = new Token($key, $iv, $iv); + $cipher = base64_encode(sodium_crypto_secretbox($json, $iv->getBytes(), $key)); + $pending = new SessionData($token, returnQuery: "tab=orders"); + $_SESSION = [SessionData::class => $pending, "basket" => ["tea"]]; + $before = $_SESSION; + $redirect = self::createMock(RedirectHandler::class); + $redirect->expects(self::never())->method("redirect"); + $callback = static function():void { self::fail("Invalid response invoked callback"); }; + try { + new Authenticator("deployment_" . $key, + "/?AUTHWAVE_RESPONSE_DATA=" . urlencode($cipher), + redirectHandler: $redirect, onAuthenticated: $callback); + self::fail("Expected callback validation to fail"); + } + catch(InvalidUserDataSerializationException) {} + self::assertSame($before, $_SESSION); + self::assertFalse($pending->hasInvokedAuthenticationCallback()); + self::expectException(InvalidUserDataSerializationException::class); + $token->decode($cipher); + } + + public function testUuidResponsesWorkInBothPaths():void { + $key = str_repeat("s", 32); + $iv = new InitVector(); + $token = new Token($key, $iv, $iv); + $cipher = base64_encode(sodium_crypto_secretbox( + '{"uuid":"user-id","email":"person@example.com"}', $iv->getBytes(), $key, + )); + $_SESSION = [SessionData::class => new SessionData($token)]; + $auth = new Authenticator("deployment_" . $key, + "/?AUTHWAVE_RESPONSE_DATA=" . urlencode($cipher), + redirectHandler: self::createStub(RedirectHandler::class)); + self::assertSame("user-id", $auth->getAuthUser()->id); + self::assertSame("user-id", $token->decode($cipher)->getId()); + } + + public function testTokenRejectsMalformedCipherEncoding():void { + self::expectException(ResponseCipherDecryptionException::class); + (new Token(str_repeat("s", 32)))->decode("%%%"); + } + + public function testDeploymentIdCanContainUnderscores():void { + $_SESSION = []; + $auth = new Authenticator("my_deployment_" . str_repeat("s", 32), "/"); + self::assertFalse($auth->isLoggedIn()); + } +}