Skip to content

EspoCRM – Open Source CRM Application

Authentication tests, ref

Yuriib780a9c467ba
diff --git a/application/Espo/Classes/RecordHooks/User/BeforeCreate.php b/application/Espo/Classes/RecordHooks/User/BeforeCreate.php
index 25d8cbe2de..e467200058 100644
--- a/application/Espo/Classes/RecordHooks/User/BeforeCreate.php
+++ b/application/Espo/Classes/RecordHooks/User/BeforeCreate.php
@@ -108,12 +108,10 @@ class BeforeCreate implements SaveHook
return;
}
- $entity->set('apiKey', Util::generateApiKey());
+ $entity->setApiKey(Util::generateApiKey());
if ($entity->getAuthMethod() === Hmac::NAME) {
- $secretKey = Util::generateSecretKey();
-
- $entity->set('secretKey', $secretKey);
+ $entity->setSecretKey(Util::generateSecretKey());
}
}
diff --git a/application/Espo/Core/Authentication/Helper/UserFinder.php b/application/Espo/Core/Authentication/Helper/UserFinder.php
index a34e5bfef4..db915bbd2b 100644
--- a/application/Espo/Core/Authentication/Helper/UserFinder.php
+++ b/application/Espo/Core/Authentication/Helper/UserFinder.php
@@ -84,8 +84,8 @@ class UserFinder
->getRDBRepositoryByClass(User::class)
->where([
User::FIELD_TYPE => User::TYPE_API,
- 'apiKey' => $apiKey,
- 'authMethod' => Hmac::NAME,
+ User::FIELD_API_KEY => $apiKey,
+ User::FIELD_AUTH_METHOD => Hmac::NAME,
])
->findOne();
}
@@ -96,8 +96,8 @@ class UserFinder
->getRDBRepositoryByClass(User::class)
->where([
User::FIELD_TYPE => User::TYPE_API,
- 'apiKey' => $apiKey,
- 'authMethod' => ApiKey::NAME,
+ User::FIELD_API_KEY => $apiKey,
+ User::FIELD_AUTH_METHOD => ApiKey::NAME,
])
->findOne();
}
diff --git a/application/Espo/Core/Authentication/Logins/ApiKey.php b/application/Espo/Core/Authentication/Logins/ApiKey.php
index 9bb0f70462..b4b9579fd6 100644
--- a/application/Espo/Core/Authentication/Logins/ApiKey.php
+++ b/application/Espo/Core/Authentication/Logins/ApiKey.php
@@ -38,7 +38,12 @@ use Espo\Core\Authentication\Result\FailReason;
class ApiKey implements Login
{
- public const NAME = 'ApiKey';
+ public const string NAME = 'ApiKey';
+
+ /**
+ * @since 10.1.0
+ */
+ public const string HEADER_API_KEY = 'X-Api-Key';
private UserFinder $userFinder;
@@ -49,7 +54,7 @@ class ApiKey implements Login
public function login(Data $data, Request $request): Result
{
- $apiKey = $request->getHeader('X-Api-Key');
+ $apiKey = $request->getHeader(self::HEADER_API_KEY);
if (!$apiKey) {
return Result::fail(FailReason::WRONG_CREDENTIALS);
diff --git a/application/Espo/Core/Authentication/Logins/Hmac.php b/application/Espo/Core/Authentication/Logins/Hmac.php
index bb25041021..4afcebda96 100644
--- a/application/Espo/Core/Authentication/Logins/Hmac.php
+++ b/application/Espo/Core/Authentication/Logins/Hmac.php
@@ -41,14 +41,19 @@ use RuntimeException;
class Hmac implements Login
{
- public const NAME = 'Hmac';
+ public const string NAME = 'Hmac';
+
+ /**
+ * @since 10.1.0
+ */
+ public const string HEADER_HMAC_AUTHORIZATION = 'X-Hmac-Authorization';
public function __construct(private UserFinder $userFinder, private ApiKey $apiKeyUtil)
{}
public function login(Data $data, Request $request): Result
{
- $authString = base64_decode($request->getHeader('X-Hmac-Authorization') ?? '');
+ $authString = base64_decode($request->getHeader(self::HEADER_HMAC_AUTHORIZATION) ?? '');
[$apiKey, $hash] = explode(':', $authString, 2);
diff --git a/application/Espo/Entities/Portal.php b/application/Espo/Entities/Portal.php
index 99fa59fd1b..da6255cedc 100644
--- a/application/Espo/Entities/Portal.php
+++ b/application/Espo/Entities/Portal.php
@@ -30,6 +30,7 @@
namespace Espo\Entities;
use Espo\Core\Field\Link;
+use Espo\Core\Name\Field;
use Espo\Core\ORM\Entity;
use Espo\Repositories\Portal as PortalRepository;
@@ -67,6 +68,22 @@ class Portal extends Entity
return $this->settingsAttributeList;
}
+ /**
+ * @since 10.1.10
+ */
+ public function setName(string $name): self
+ {
+ return $this->set(Field::NAME, $name);
+ }
+
+ /**
+ * @since 10.1.10
+ */
+ public function getName(): ?string
+ {
+ return $this->get(Field::NAME);
+ }
+
public function getUrl(): ?string
{
if (!$this->has('url') && $this->entityManager) {
diff --git a/application/Espo/Entities/User.php b/application/Espo/Entities/User.php
index 18956be601..a786b7f54f 100644
--- a/application/Espo/Entities/User.php
+++ b/application/Espo/Entities/User.php
@@ -74,6 +74,8 @@ class User extends Person
public const string FIELD_TYPE = 'type';
/** @since 10.0.4 */
public const string FIELD_API_KEY = 'apiKey';
+ /** @since 10.1.0 */
+ public const string FIELD_SECRET_KEY = 'secretKey';
/** @since 10.0.4 */
public const string FIELD_AUTH_METHOD = 'authMethod';
@@ -366,6 +368,46 @@ class User extends Person
return $this->get(self::FIELD_PASSWORD) ?? '';
}
+ /**
+ * @since 10.1.0
+ */
+ public function setAuthMethod(?string $method): self
+ {
+ return $this->set(self::FIELD_AUTH_METHOD, $method);
+ }
+
+ /**
+ * @since 10.1.0
+ */
+ public function getApiKey(): ?string
+ {
+ return $this->get(self::FIELD_API_KEY);
+ }
+
+ /**
+ * @since 10.1.0
+ */
+ public function setApiKey(?string $apiKey): self
+ {
+ return $this->set(self::FIELD_API_KEY, $apiKey);
+ }
+
+ /**
+ * @since 10.1.0
+ */
+ public function getSecretKey(): ?string
+ {
+ return $this->get(self::FIELD_SECRET_KEY);
+ }
+
+ /**
+ * @since 10.1.0
+ */
+ public function setSecretKey(?string $secretKey): self
+ {
+ return $this->set(self::FIELD_SECRET_KEY, $secretKey);
+ }
+
private function getNameInternal(): ?string
{
if (!$this->hasInContainer(Field::NAME) || !$this->getFromContainer(Field::NAME)) {
diff --git a/application/Espo/Tools/UserSecurity/ApiService.php b/application/Espo/Tools/UserSecurity/ApiService.php
index 70b9e4d64f..91f4160066 100644
--- a/application/Espo/Tools/UserSecurity/ApiService.php
+++ b/application/Espo/Tools/UserSecurity/ApiService.php
@@ -63,9 +63,8 @@ class ApiService
throw new Forbidden();
}
- $service = $this->serviceContainer->get(User::ENTITY_TYPE);
+ $service = $this->serviceContainer->getByClass(User::class);
- /** @var ?User $entity */
$entity = $service->getEntity($id);
if (!$entity) {
@@ -76,14 +75,10 @@ class ApiService
throw new Forbidden();
}
- $apiKey = Util::generateApiKey();
-
- $entity->set('apiKey', $apiKey);
+ $entity->setApiKey(Util::generateApiKey());
if ($entity->getAuthMethod() === Hmac::NAME) {
- $secretKey = Util::generateSecretKey();
-
- $entity->set('secretKey', $secretKey);
+ $entity->setSecretKey(Util::generateSecretKey());
}
$this->entityManager->saveEntity($entity);
diff --git a/tests/integration/Core/BaseTestCase.php b/tests/integration/Core/BaseTestCase.php
index a628b15123..f69f01e597 100644
--- a/tests/integration/Core/BaseTestCase.php
+++ b/tests/integration/Core/BaseTestCase.php
@@ -328,10 +328,15 @@ abstract class BaseTestCase extends TestCase
?string $body = null,
array $routeParams = [],
array $cookieParams = [],
+ string $resourcePath = '',
): RequestWrapper {
+ if (!str_starts_with($resourcePath, '/')) {
+ $resourcePath = '/' . $resourcePath;
+ }
+
$request = (new RequestFactory())
- ->createRequest($method, 'http://localhost/?' . http_build_query($queryParams));
+ ->createRequest($method, "http://localhost$resourcePath?" . http_build_query($queryParams));
if (!$request instanceof ServerRequestInterface) {
throw new RuntimeException();
diff --git a/tests/integration/Espo/Core/Authentication/AuthenticationTest.php b/tests/integration/Espo/Core/Authentication/AuthenticationTest.php
index b5bf747a8b..bc07a54066 100644
--- a/tests/integration/Espo/Core/Authentication/AuthenticationTest.php
+++ b/tests/integration/Espo/Core/Authentication/AuthenticationTest.php
@@ -32,17 +32,22 @@ namespace integration\Espo\Core\Authentication;
use Espo\Core\Api\Method;
use Espo\Core\Api\RequestWrapper;
use Espo\Core\Api\Response;
+use Espo\Core\ApplicationState;
use Espo\Core\ApplicationUser;
use Espo\Core\Authentication\Authentication;
use Espo\Core\Authentication\AuthenticationData;
use Espo\Core\Authentication\AuthToken\Manager;
use Espo\Core\Authentication\HeaderKey;
+use Espo\Core\Authentication\Logins\ApiKey;
+use Espo\Core\Authentication\Logins\Hmac;
use Espo\Core\Authentication\Result;
use Espo\Core\Authentication\TwoFactor\Login;
use Espo\Core\Authentication\TwoFactor\LoginFactory as TwoFactorLoginFactory;
use Espo\Core\Authentication\TwoFactor\MethodProvider as TwoFactorMethodProvider;
use Espo\Core\Binding\BindingContainerBuilder;
+use Espo\Core\Utils\Util;
use Espo\Entities\AuthToken;
+use Espo\Entities\Portal;
use Espo\Entities\User;
use tests\integration\Core\BaseTestCase;
@@ -55,7 +60,7 @@ class AuthenticationTest extends BaseTestCase
*/
public function testLoginBasicSuccess(): void
{
- [$username, $password] = $this->prepareTestUser();
+ [$username, $password, $user] = $this->prepareTestUser();
$applicationUser = $this->createMock(ApplicationUser::class);
@@ -78,6 +83,7 @@ class AuthenticationTest extends BaseTestCase
$this->assertTrue($result->isSuccess());
$this->assertFalse($result->isFail());
+ $this->assertEquals($user->getId(), $result->getUser()->getId());
}
/**
@@ -498,11 +504,352 @@ class AuthenticationTest extends BaseTestCase
$this->assertFalse($result->isSecondStepRequired());
}
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testPortalBasicSuccess(): void
+ {
+ $em = $this->getEntityManager();
+
+ $portal = $em->getRDBRepositoryByClass(Portal::class)->getNew();
+ $portal->setName('Test');
+ $em->saveEntity($portal);
+
+ [$username, $password] = $this->prepareTestUser(
+ isPortal: true,
+ portalIds: [$portal->getId()],
+ );
+
+ $applicationUser = $this->createMock(ApplicationUser::class);
+
+ $applicationUser
+ ->expects(self::once())
+ ->method('setUser')
+ ->with(
+ $this->callback(function (User $user) use ($username) {
+ return $user->getUserName() === $username;
+ })
+ );
+
+ $authentication = $this->createAuthentication($applicationUser, portal: $portal);
+
+ $result = $authentication->login(
+ data: AuthenticationData::create()
+ ->withUsername($username)
+ ->withPassword($password),
+ request: $this->createSimpleGetRequest(),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertTrue($result->isSuccess());
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testPortalFailNonPortalUser(): void
+ {
+ $em = $this->getEntityManager();
+
+ $portal = $em->getRDBRepositoryByClass(Portal::class)->getNew();
+ $portal->setName('Test');
+ $em->saveEntity($portal);
+
+ [$username, $password] = $this->prepareTestUser();
+
+ $authentication = $this->createAuthentication(portal: $portal);
+
+ $result = $authentication->login(
+ data: AuthenticationData::create()
+ ->withUsername($username)
+ ->withPassword($password),
+ request: $this->createSimpleGetRequest(),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertFalse($result->isSuccess());
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testPortalFailWrongPortal(): void
+ {
+ $em = $this->getEntityManager();
+
+ $portal = $em->getRDBRepositoryByClass(Portal::class)->getNew();
+ $portal->setName('Test');
+ $em->saveEntity($portal);
+
+ $portalAnother = $em->getRDBRepositoryByClass(Portal::class)->getNew();
+ $portalAnother->setName('Test Another');
+ $em->saveEntity($portalAnother);
+
+ [$username, $password] = $this->prepareTestUser(
+ isPortal: true,
+ portalIds: [$portal->getId()],
+ );
+
+ $authentication = $this->createAuthentication(portal: $portalAnother);
+
+ $result = $authentication->login(
+ data: AuthenticationData::create()
+ ->withUsername($username)
+ ->withPassword($password),
+ request: $this->createSimpleGetRequest(),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertFalse($result->isSuccess());
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testApiKeySuccess(): void
+ {
+ $username = 'test';
+
+ $em = $this->getEntityManager();
+
+ $apiKey = Util::generateApiKey();
+
+ $user = $em->getRDBRepositoryByClass(User::class)->getNew();
+ $user
+ ->setType(User::TYPE_API)
+ ->setUserName($username)
+ ->setApiKey($apiKey)
+ ->setAuthMethod(ApiKey::NAME);
+ $em->saveEntity($user);
+
+ $applicationUser = $this->createMock(ApplicationUser::class);
+
+ $applicationUser
+ ->expects(self::once())
+ ->method('setUser')
+ ->with(
+ $this->callback(function (User $user) use ($username) {
+ return $user->getUserName() === $username;
+ })
+ );
+
+ $result = $this->createAuthentication($applicationUser)->login(
+ data: AuthenticationData::create()
+ ->withMethod(ApiKey::NAME),
+ request: $this->createSimpleGetRequest(
+ headers: [
+ ApiKey::HEADER_API_KEY => $apiKey,
+ ],
+ ),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertTrue($result->isSuccess());
+
+ $this->assertNull(
+ $em->getRDBRepositoryByClass(AuthToken::class)
+ ->where([
+ AuthToken::ATTR_USER_ID => $user->getId(),
+ ])
+ ->findOne()
+ );
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testApiKeyFailWrongApiKey(): void
+ {
+ $username = 'test';
+
+ $em = $this->getEntityManager();
+
+ $apiKey = Util::generateApiKey();
+
+ $user = $em->getRDBRepositoryByClass(User::class)->getNew();
+ $user
+ ->setType(User::TYPE_API)
+ ->setUserName($username)
+ ->setApiKey($apiKey)
+ ->setAuthMethod(ApiKey::NAME);
+ $em->saveEntity($user);
+
+ $result = $this->createAuthentication()->login(
+ data: AuthenticationData::create()
+ ->withMethod(ApiKey::NAME),
+ request: $this->createSimpleGetRequest(
+ headers: [
+ ApiKey::HEADER_API_KEY => 'wrong',
+ ],
+ ),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertFalse($result->isSuccess());
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testApiKeyFailWrongMethod(): void
+ {
+ $username = 'test';
+
+ $em = $this->getEntityManager();
+
+ $apiKey = Util::generateApiKey();
+
+ $user = $em->getRDBRepositoryByClass(User::class)->getNew();
+ $user
+ ->setType(User::TYPE_API)
+ ->setUserName($username)
+ ->setApiKey($apiKey)
+ ->setSecretKey(Util::generateApiKey())
+ ->setAuthMethod(Hmac::NAME);
+ $em->saveEntity($user);
+
+ $result = $this->createAuthentication()->login(
+ data: AuthenticationData::create()
+ ->withMethod(ApiKey::NAME),
+ request: $this->createSimpleGetRequest(
+ headers: [
+ ApiKey::HEADER_API_KEY => $apiKey,
+ ],
+ ),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertFalse($result->isSuccess());
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testHmacSuccess(): void
+ {
+ $username = 'test';
+
+ $em = $this->getEntityManager();
+
+ $apiKey = Util::generateApiKey();
+ $secretKey = Util::generateSecretKey();
+
+ $user = $em->getRDBRepositoryByClass(User::class)->getNew();
+ $user
+ ->setType(User::TYPE_API)
+ ->setUserName($username)
+ ->setApiKey($apiKey)
+ ->setSecretKey($secretKey)
+ ->setAuthMethod(Hmac::NAME);
+ $em->saveEntity($user);
+
+ $resourcePath = '/api/v1/Test';
+
+ $string = Method::GET . ' ' . $resourcePath;
+ $authorizationHeader = base64_encode($apiKey . ':' . hash_hmac('sha256', $string, $secretKey));
+
+ $result = $this->createAuthentication()->login(
+ data: AuthenticationData::create()
+ ->withMethod(Hmac::NAME),
+ request: $this->createSimpleGetRequest(
+ headers: [
+ Hmac::HEADER_HMAC_AUTHORIZATION => $authorizationHeader,
+ ],
+ resourcePath: $resourcePath,
+ ),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertTrue($result->isSuccess());
+ $this->assertEquals($user->getId(), $result->getUser()->getId());
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testHmacFailWrongSecret(): void
+ {
+ $username = 'test';
+
+ $em = $this->getEntityManager();
+
+ $apiKey = Util::generateApiKey();
+ $secretKey = Util::generateSecretKey();
+
+ $user = $em->getRDBRepositoryByClass(User::class)->getNew();
+ $user
+ ->setType(User::TYPE_API)
+ ->setUserName($username)
+ ->setApiKey($apiKey)
+ ->setSecretKey($secretKey)
+ ->setAuthMethod(Hmac::NAME);
+ $em->saveEntity($user);
+
+ $resourcePath = '/api/v1/Test';
+
+ $string = Method::GET . ' ' . $resourcePath;
+ $authorizationHeader = base64_encode($apiKey . ':' . hash_hmac('sha256', $string, 'wrong'));
+
+ $result = $this->createAuthentication()->login(
+ data: AuthenticationData::create()
+ ->withMethod(Hmac::NAME),
+ request: $this->createSimpleGetRequest(
+ headers: [
+ Hmac::HEADER_HMAC_AUTHORIZATION => $authorizationHeader,
+ ],
+ resourcePath: $resourcePath,
+ ),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertFalse($result->isSuccess());
+ }
+
+ /**
+ * @noinspection PhpUnhandledExceptionInspection
+ */
+ public function testHmacFailWrongResourcePath(): void
+ {
+ $username = 'test';
+
+ $em = $this->getEntityManager();
+
+ $apiKey = Util::generateApiKey();
+ $secretKey = Util::generateSecretKey();
+
+ $user = $em->getRDBRepositoryByClass(User::class)->getNew();
+ $user
+ ->setType(User::TYPE_API)
+ ->setUserName($username)
+ ->setApiKey($apiKey)
+ ->setSecretKey($secretKey)
+ ->setAuthMethod(Hmac::NAME);
+ $em->saveEntity($user);
+
+ $string = Method::GET . ' ' . '/Wrong';
+ $authorizationHeader = base64_encode($apiKey . ':' . hash_hmac('sha256', $string, $secretKey));
+
+ $result = $this->createAuthentication()->login(
+ data: AuthenticationData::create()
+ ->withMethod(Hmac::NAME),
+ request: $this->createSimpleGetRequest(
+ headers: [
+ Hmac::HEADER_HMAC_AUTHORIZATION => $authorizationHeader,
+ ],
+ resourcePath: '/api/v1',
+ ),
+ response: $this->createMock(Response::class)
+ );
+
+ $this->assertFalse($result->isSuccess());
+ }
+
private function createAuthentication(
?ApplicationUser $applicationUser = null,
?Login $twoFactorLogin = null,
?string $twoFactorMethod = null,
?string $userId = null,
+ ?Portal $portal = null,
): Authentication {
$applicationUser ??= $this->createMock(ApplicationUser::class);
@@ -534,6 +881,22 @@ class AuthenticationTest extends BaseTestCase
$builder->bindInstance(TwoFactorMethodProvider::class, $twoFactorMethodProvider);
}
+ if ($portal) {
+ $applicationState = $this->createMock(ApplicationState::class);
+
+ $applicationState
+ ->expects(self::any())
+ ->method('isPortal')
+ ->willReturn(true);
+
+ $applicationState
+ ->expects(self::any())
+ ->method('getPortal')
+ ->willReturn($portal);
+
+ $builder->bindInstance(ApplicationState::class, $applicationState);
+ }
+
return $this->getInjectableFactory()->createWithBinding(Authentication::class, $builder->build());
}
@@ -543,6 +906,7 @@ class AuthenticationTest extends BaseTestCase
private function createSimpleGetRequest(
array $headers = [],
array $cookieParams = [],
+ string $resourcePath = '',
): RequestWrapper {
return $this->createRequest(
@@ -552,6 +916,7 @@ class AuthenticationTest extends BaseTestCase
...$headers,
],
cookieParams: $cookieParams,
+ resourcePath: $resourcePath,
);
}
@@ -607,7 +972,6 @@ class AuthenticationTest extends BaseTestCase
return [$username, $password];
}
-
private function getAuthTokenManager(): Manager
{
return $this->getContainer()->getByClass(Manager::class);
@@ -616,15 +980,23 @@ class AuthenticationTest extends BaseTestCase
/**
* @return array{string, string, User}
*/
- private function prepareTestUser(bool $isActive = true): array
- {
+ private function prepareTestUser(
+ bool $isActive = true,
+ bool $isPortal = false,
+ array $portalIds = [],
+ ): array {
+
[$username, $password] = $this->prepareUsernamePassword();
- $user = $this->createUser([
- User::FIELD_USER_NAME => $username,
- User::FIELD_PASSWORD => $password,
- User::FIELD_IS_ACTIVE => $isActive,
- ]);
+ $user = $this->createUser(
+ [
+ User::FIELD_USER_NAME => $username,
+ User::FIELD_PASSWORD => $password,
+ User::FIELD_IS_ACTIVE => $isActive,
+ User::LINK_PORTALS . 'Ids' => $portalIds,
+ ],
+ isPortal: $isPortal,
+ );
return [$username, $password, $user];
}