EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
Forbid api auth
Yuriiddd727b31a42
diff --git a/application/Espo/Core/Api/Auth.php b/application/Espo/Core/Api/Auth.phpindex 642ea119b9..ca0c752d1d 100644--- a/application/Espo/Core/Api/Auth.php+++ b/application/Espo/Core/Api/Auth.php@@ -57,6 +57,7 @@ class Authprivate MethodResolver $methodResolver,private bool $authRequired = true,private bool $isEntryPoint = false,+ private bool $apiAuthForbidden = false,) {}/**@@ -70,6 +71,12 @@ class Auth$authenticationMethod = $this->methodResolver->resolve($request);+ if ($authenticationMethod && $this->apiAuthForbidden) {+ $this->handleUnauthorized($response);++ return AuthResult::createNotResolved();+ }+if (!$authenticationMethod) {[$username, $password] = $this->obtainUsernamePasswordFromRequest($request);}diff --git a/application/Espo/Core/Api/AuthBuilder.php b/application/Espo/Core/Api/AuthBuilder.phpindex 8c04ad0e3c..33d74dfc1b 100644--- a/application/Espo/Core/Api/AuthBuilder.php+++ b/application/Espo/Core/Api/AuthBuilder.php@@ -43,6 +43,7 @@ class AuthBuilder{private bool $authRequired = false;private bool $isEntryPoint = false;+ private bool $apiAuthForbidden = false;private ?Authentication $authentication = null;public function __construct(private InjectableFactory $injectableFactory)@@ -62,6 +63,13 @@ class AuthBuilderreturn $this;}+ public function setApiAuthForbidden(bool $apiAuthForbidden): self+ {+ $this->apiAuthForbidden = $apiAuthForbidden;++ return $this;+ }+public function forEntryPoint(): self{$this->isEntryPoint = true;@@ -83,6 +91,7 @@ class AuthBuilder->inContext(Auth::class, function (ContextualBinder $binder) {$binder->bindValue('$authRequired', $this->authRequired)+ ->bindValue('$apiAuthForbidden', $this->apiAuthForbidden)->bindValue('$isEntryPoint', $this->isEntryPoint);})->build()diff --git a/application/Espo/Core/Api/Route.php b/application/Espo/Core/Api/Route.phpindex 84f9632d3b..e7ebe84637 100644--- a/application/Espo/Core/Api/Route.php+++ b/application/Espo/Core/Api/Route.php@@ -46,6 +46,7 @@ class Routeprivate bool $noAuth,private ?array $consumes,private ?string $actionClassName,+ private bool $apiAuthForbidden,) {$this->method = strtoupper($method);}@@ -102,4 +103,14 @@ class Route{return $this->consumes;}++ /**+ * Forbid API authentication.+ *+ * @since 10.1.0+ */+ public function apiAuthForbidden(): bool+ {+ return $this->apiAuthForbidden;+ }}diff --git a/application/Espo/Core/Api/RouteProcessor.php b/application/Espo/Core/Api/RouteProcessor.phpindex 779e754f2d..b39a65a5a9 100644--- a/application/Espo/Core/Api/RouteProcessor.php+++ b/application/Espo/Core/Api/RouteProcessor.php@@ -106,11 +106,13 @@ class RouteProcessor$this->assertContentTypeAllowed($processData, $request);$authRequired = !$processData->getRoute()->noAuth();+ $apiAuthForbidden = $processData->getRoute()->apiAuthForbidden();$apiAuth = $this->authBuilderFactory->create()->setAuthentication($this->authenticationFactory->create())->setAuthRequired($authRequired)+ ->setApiAuthForbidden($apiAuthForbidden)->build();$authResult = $apiAuth->process($request, $response);diff --git a/application/Espo/Core/EntryPoint/EntryPointManager.php b/application/Espo/Core/EntryPoint/EntryPointManager.phpindex 71d5463567..d6679fe56e 100644--- a/application/Espo/Core/EntryPoint/EntryPointManager.php+++ b/application/Espo/Core/EntryPoint/EntryPointManager.php@@ -118,7 +118,8 @@ class EntryPointManager* notExposed?: bool,* noAuth?: bool,* allowedMethods?: ?string[],- * consumes?: ?string[]+ * consumes?: ?string[],+ * apiAuthForbidden?: bool,* } $params*/$params = $this->metadata->get("app.entryPoints.$name") ?? [];@@ -129,6 +130,7 @@ class EntryPointManagernoAuth: $params['noAuth'] ?? false,allowedMethods: $params['allowedMethods'] ?? null,consumes: $params['consumes'] ?? null,+ apiAuthForbidden: $params['apiAuthForbidden'] ?? false,);}}diff --git a/application/Espo/Core/EntryPoint/MetaParams.php b/application/Espo/Core/EntryPoint/MetaParams.phpindex e4b25f9274..bf505e35cb 100644--- a/application/Espo/Core/EntryPoint/MetaParams.php+++ b/application/Espo/Core/EntryPoint/MetaParams.php@@ -45,5 +45,6 @@ readonly class MetaParamspublic bool $noAuth = false,public ?array $allowedMethods = null,public ?array $consumes = null,+ public bool $apiAuthForbidden = false,) {}}diff --git a/application/Espo/Core/EntryPoint/Starter.php b/application/Espo/Core/EntryPoint/Starter.phpindex 3cfbb3e975..7527f76ec8 100644--- a/application/Espo/Core/EntryPoint/Starter.php+++ b/application/Espo/Core/EntryPoint/Starter.php@@ -123,6 +123,7 @@ class Starterrequest: $request,response: $response,authRequired: $authRequired,+ apiAuthForbidden: $this->entryPointManager->getMetaParams($name)->apiAuthForbidden,);$this->outputEmitter->emit($response);@@ -133,6 +134,7 @@ class StarterRequestWrapper $request,ResponseWrapper $response,bool $authRequired,+ bool $apiAuthForbidden,): void {try {@@ -141,9 +143,9 @@ class Starterrequest: $request,response: $response,authRequired: $authRequired,+ apiAuthForbidden: $apiAuthForbidden,);} catch (Exception $exception) {- print_r($exception->getMessage());$this->errorOutput->processWithBodyPrinting($request, $response, $exception);}}@@ -151,12 +153,14 @@ class Starter/*** @throws NotFound* @throws BadRequest+ * @throws Exception*/private function processRequestInternal(string $entryPoint,RequestWrapper $request,ResponseWrapper $response,bool $authRequired,+ bool $apiAuthForbidden,): void {$authentication = $this->authenticationFactory->create();@@ -164,6 +168,7 @@ class Starter$apiAuth = $this->authBuilderFactory->create()->setAuthentication($authentication)->setAuthRequired($authRequired)+ ->setApiAuthForbidden($apiAuthForbidden)->forEntryPoint()->build();@@ -179,7 +184,13 @@ class Starterob_start();- $this->entryPointManager->run($entryPoint, $request, $response);+ try {+ $this->entryPointManager->run($entryPoint, $request, $response);+ } catch (Exception $e) {+ ob_end_clean();++ throw $e;+ }$contents = ob_get_clean();diff --git a/application/Espo/Core/Portal/Utils/Route.php b/application/Espo/Core/Portal/Utils/Route.phpindex f5c3cf976f..0d172abde7 100644--- a/application/Espo/Core/Portal/Utils/Route.php+++ b/application/Espo/Core/Portal/Utils/Route.php@@ -57,6 +57,7 @@ class Route extends BaseRoutenoAuth: $route->noAuth(),consumes: $route->getConsumes(),actionClassName: $route->getActionClassName(),+ apiAuthForbidden: $route->apiAuthForbidden(),);$newRouteList[] = $newRoute;diff --git a/application/Espo/Core/Utils/Route.php b/application/Espo/Core/Utils/Route.phpindex 015c757529..1be1b09364 100644--- a/application/Espo/Core/Utils/Route.php+++ b/application/Espo/Core/Utils/Route.php@@ -44,7 +44,8 @@ use Espo\Core\Utils\Resource\PathProvider;* noAuth?: bool,* params?: array<string, mixed>,* consumes?: ?string[],- * actionClassName: ?class-string<Action>+ * actionClassName: ?class-string<Action>,+ * apiAuthForbidden?: bool,* }*/class Route@@ -86,6 +87,7 @@ class RoutenoAuth: $item['noAuth'] ?? false,consumes: $item['consumes'] ?? null,actionClassName: $item['actionClassName'] ?? null,+ apiAuthForbidden: $item['apiAuthForbidden'] ?? false,);},$this->datadiff --git a/application/Espo/Resources/metadata/app/entryPoints.json b/application/Espo/Resources/metadata/app/entryPoints.jsonindex 7a70b1239f..c6c39c08e9 100644--- a/application/Espo/Resources/metadata/app/entryPoints.json+++ b/application/Espo/Resources/metadata/app/entryPoints.json@@ -12,7 +12,8 @@},"oAuthAuthorizeComplete": {"className": "Espo\\Tools\\OAuthServer\\EntryPoints\\AuthorizeComplete",- "allowedMethods": ["post"]+ "allowedMethods": ["post"],+ "apiAuthForbidden": true},"oAuthToken": {"className": "Espo\\Tools\\OAuthServer\\EntryPoints\\Token",diff --git a/application/Espo/Resources/routes.json b/application/Espo/Resources/routes.jsonindex 2a6e4cd0fe..66d05cfd74 100644--- a/application/Espo/Resources/routes.json+++ b/application/Espo/Resources/routes.json@@ -86,7 +86,8 @@{"route": "OAuthServer/consentData","method": "get",- "actionClassName": "Espo\\Tools\\OAuthServer\\Api\\GetConsentData"+ "actionClassName": "Espo\\Tools\\OAuthServer\\Api\\GetConsentData",+ "apiAuthForbidden": true},{"route": "/LeadCapture/form/:id",@@ -466,12 +467,14 @@{"route": "/User/:id/connectedApps","method": "get",- "actionClassName": "Espo\\Tools\\UserSecurity\\Api\\GetConnectedApps"+ "actionClassName": "Espo\\Tools\\UserSecurity\\Api\\GetConnectedApps",+ "apiAuthForbidden": true},{"route": "/User/:id/connectedApps/:appId","method": "delete",- "actionClassName": "Espo\\Tools\\UserSecurity\\Api\\DeleteConnectedApp"+ "actionClassName": "Espo\\Tools\\UserSecurity\\Api\\DeleteConnectedApp",+ "apiAuthForbidden": true},{"route": "/UserSecurity/apiKey/generate",diff --git a/schema/metadata/app/entryPoints.json b/schema/metadata/app/entryPoints.jsonindex e7050198de..bde01e2760 100644--- a/schema/metadata/app/entryPoints.json+++ b/schema/metadata/app/entryPoints.json@@ -48,6 +48,10 @@]},"description": "If defined, restricts content types allowed for the entry point. If an empty array, the Content-Type header must be empty."+ },+ "apiAuthForbidden": {+ "type": "boolean",+ "description": "Forbids API authentication, such as the API user, OAuth. Since 10.1."}}}diff --git a/schema/routes.json b/schema/routes.jsonindex c3b3794946..163588f92e 100644--- a/schema/routes.json+++ b/schema/routes.json@@ -28,6 +28,10 @@"type": "boolean","description": "Makes the route not requiring authentication."},+ "apiAuthForbidden": {+ "type": "boolean",+ "description": "Forbids API authentication, such as the API user, OAuth. Since 10.1."+ },"actionClassName": {"type": "string","description": "An action class. Should implement the interface Espo\\Core\\Api\\Action."diff --git a/tests/integration/Espo/Core/EntryPoint/EntryPointTest.php b/tests/integration/Espo/Core/EntryPoint/EntryPointTest.phpindex d1412ef88c..bfb8f42e58 100644--- a/tests/integration/Espo/Core/EntryPoint/EntryPointTest.php+++ b/tests/integration/Espo/Core/EntryPoint/EntryPointTest.php@@ -34,11 +34,14 @@ use Espo\Core\Api\Method;use Espo\Core\Api\RequestWrapper;use Espo\Core\Api\ResponseWrapper;use Espo\Core\ApplicationState;+use Espo\Core\Authentication\Logins\ApiKey;use Espo\Core\Binding\BindingContainerBuilder;use Espo\Core\EntryPoint\OutputEmitter;use Espo\Core\EntryPoint\RequestFactory;use Espo\Core\EntryPoint\ResponseFactory;use Espo\Core\EntryPoint\Starter;+use Espo\Core\Utils\Util;+use Espo\Entities\User;use tests\integration\Core\BaseTestCase;class EntryPointTest extends BaseTestCase@@ -353,6 +356,116 @@ class EntryPointTest extends BaseTestCase$this->assertTrue($applicationState->hasUser());}+ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testApiAuthForbiddenFail(): void+ {+ $em = $this->getEntityManager();++ $user = $em->getRDBRepositoryByClass(User::class)->getNew()+ ->setUserName('api')+ ->setType(User::TYPE_API)+ ->setApiKey(Util::generateApiKey())+ ->setAuthMethod(ApiKey::NAME);++ $em->saveEntity($user);++ $metadata = $this->getMetadata();+ $metadata->set('app', 'entryPoints', [+ 'test' => [+ 'className' => 'Espo\\EntryPoints\\Avatar',+ 'apiAuthForbidden' => true,+ ],+ ]);+ $metadata->save();++ $this->reCreateApplication(reuse: true, noUser: true);++ $outputEmitter = $this->createMock(OutputEmitter::class);+ $errorOutput = $this->createMock(ErrorOutput::class);++ $request = $this->createRequest(+ method: Method::GET,+ queryParams: [+ 'entryPoint' => 'test',+ ],+ headers: [+ 'X-Api-Key' => $user->getApiKey(),+ ],+ );++ $response = $this->createMock(ResponseWrapper::class);++ $starter = $this->createStarter(+ request: $request,+ response: $response,+ outputEmitter: $outputEmitter,+ errorOutput: $errorOutput,+ );++ $starter->start();++ $applicationState = $this->getContainer()->getByClass(ApplicationState::class);++ $this->assertFalse($applicationState->hasUser());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testApiAuthNotForbiddenSuccess(): void+ {+ $em = $this->getEntityManager();++ $user = $em->getRDBRepositoryByClass(User::class)->getNew()+ ->setUserName('api')+ ->setType(User::TYPE_API)+ ->setApiKey(Util::generateApiKey())+ ->setAuthMethod(ApiKey::NAME);++ $em->saveEntity($user);++ $metadata = $this->getMetadata();+ $metadata->set('app', 'entryPoints', [+ 'test' => [+ 'className' => 'Espo\\EntryPoints\\Avatar',+ 'apiAuthForbidden' => false,+ ],+ ]);+ $metadata->save();++ $this->reCreateApplication(reuse: true, noUser: true);++ $outputEmitter = $this->createMock(OutputEmitter::class);+ $errorOutput = $this->createMock(ErrorOutput::class);++ $request = $this->createRequest(+ method: Method::GET,+ queryParams: [+ 'entryPoint' => 'test',+ ],+ headers: [+ 'X-Api-Key' => $user->getApiKey(),+ ],+ );++ $response = $this->createMock(ResponseWrapper::class);++ $starter = $this->createStarter(+ request: $request,+ response: $response,+ outputEmitter: $outputEmitter,+ errorOutput: $errorOutput,+ );++ $starter->start();++ $applicationState = $this->getContainer()->getByClass(ApplicationState::class);++ $this->assertTrue($applicationState->hasUser());+ }+private function createStarter(RequestWrapper $request,ResponseWrapper $response,diff --git a/tests/unit/Espo/Core/Api/RouteProcessorTest.php b/tests/unit/Espo/Core/Api/RouteProcessorTest.phpindex 4ea869cb55..17bcc2f48e 100644--- a/tests/unit/Espo/Core/Api/RouteProcessorTest.php+++ b/tests/unit/Espo/Core/Api/RouteProcessorTest.php@@ -68,6 +68,7 @@ class RouteProcessorTest extends TestCaseContentType::APPLICATION_JSON,],actionClassName: null,+ apiAuthForbidden: false,);$errorOutput = $this->createMock(ErrorOutput::class);diff --git a/tests/unit/Espo/Core/Utils/RouteTest.php b/tests/unit/Espo/Core/Utils/RouteTest.phpindex cfd574b20c..e643f9c621 100644--- a/tests/unit/Espo/Core/Utils/RouteTest.php+++ b/tests/unit/Espo/Core/Utils/RouteTest.php@@ -196,6 +196,7 @@ class RouteTest extends TestCasenoAuth: $item['noAuth'] ?? false,consumes: null,actionClassName: null,+ apiAuthForbidden: false,);},$expected@@ -300,6 +301,7 @@ class RouteTest extends TestCasenoAuth: $item['noAuth'] ?? false,consumes: null,actionClassName: null,+ apiAuthForbidden: false,);},$expected@@ -404,6 +406,7 @@ class RouteTest extends TestCasenoAuth: $item['noAuth'] ?? false,consumes: null,actionClassName: null,+ apiAuthForbidden: false,);},$expected