EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
Auth refactoring. Use Sec-Fetch headers
Yuriia30854c711ee
diff --git a/application/Espo/Core/Api/Auth.php b/application/Espo/Core/Api/Auth.phpindex 67f4d6a03a..fea0070f46 100644--- a/application/Espo/Core/Api/Auth.php+++ b/application/Espo/Core/Api/Auth.php@@ -48,6 +48,8 @@ use Exception;*/class Auth{+ private const string SCHEME_BASIC = 'Basic';+public function __construct(private Log $log,private Authentication $authentication,@@ -79,7 +81,7 @@ class Auth$hasAuthData = $username || $authenticationMethod;if (!$hasAuthData) {- $password = $this->obtainTokenFromCookies($request);+ $password = self::obtainTokenFromCookies($request);if ($password) {$authenticationData = AuthenticationData::create()@@ -92,9 +94,9 @@ class Authif (!$this->authRequired && !$this->isEntryPoint && $hasAuthData) {$authResult = $this->processAuthNotRequired(- $authenticationData,- $request,- $response+ data: $authenticationData,+ request: $request,+ response: $response,);if ($authResult) {@@ -110,12 +112,10 @@ class Authreturn $this->processWithAuthData($authenticationData, $request, $response);}- $showDialog =- ($this->isEntryPoint || !$this->isXMLHttpRequest($request)) &&- !$request->getHeader('Referer') &&- $request->getMethod() !== Method::POST;-- $this->handleUnauthorized($response, null, $showDialog);+ $this->handleUnauthorized(+ response: $response,+ showDialog: self::toShowDialog($request),+ );return AuthResult::createNotResolved();}@@ -126,7 +126,7 @@ class Authprivate function processAuthNotRequired(AuthenticationData $data,Request $request,- Response $response+ Response $response,): ?AuthResult {try {@@ -150,7 +150,7 @@ class Authprivate function processWithAuthData(AuthenticationData $data,Request $request,- Response $response+ Response $response,): AuthResult {try {@@ -166,16 +166,15 @@ class Auth}if ($result->isFail()) {- $showDialog =- $this->isEntryPoint &&- !$request->getHeader('Referer') &&- $request->getMethod() !== Method::POST;-- $this->handleUnauthorized($response, $result, $showDialog);+ $this->handleUnauthorized(+ response: $response,+ result: $result,+ showDialog: $this->toShowDialogOnFail($request),+ );}if ($result->isSecondStepRequired()) {- $this->handleSecondStepRequired($response, $result);+ self::handleSecondStepRequired($response, $result);}return AuthResult::createNotResolved();@@ -185,7 +184,7 @@ class Auth* @return array{string, string}* @throws BadRequest*/- private function decodeAuthorizationString(string $string): array+ private static function decodeAuthorizationString(string $string): array{/** @var string $stringDecoded */$stringDecoded = base64_decode($string);@@ -202,7 +201,7 @@ class Authreturn [$username, $password];}- private function handleSecondStepRequired(Response $response, Result $result): void+ private static function handleSecondStepRequired(Response $response, Result $result): void{$response->setStatus(401);$response->setHeader('X-Status-Reason', 'second-step-required');@@ -249,28 +248,19 @@ class Auththrow $e;}- private function handleUnauthorized(Response $response, ?Result $result, bool $showDialog): void+ private function handleUnauthorized(Response $response, ?Result $result = null, bool $showDialog = false): void{if ($showDialog) {- $response->setHeader('WWW-Authenticate', 'Basic realm=""');+ $response->setHeader('WWW-Authenticate', 'Basic realm="api"');}if ($result && $result->getFailReason() === Result\FailReason::ERROR) {- $response = $response->setHeader('X-Status-Reason', 'error');+ $response = $response->setHeader(ErrorOutput::HEADER_STATUS_REASON, 'error');}$response->setStatus(401);}- private function isXMLHttpRequest(Request $request): bool- {- if (strtolower($request->getHeader('X-Requested-With') ?? '') == 'xmlhttprequest') {- return true;- }-- return false;- }-/*** @return array{?string, ?string}* @throws BadRequest@@ -280,7 +270,7 @@ class Authif ($request->hasHeader(HeaderKey::AUTHORIZATION)) {$headerValue = $request->getHeader(HeaderKey::AUTHORIZATION) ?? '';- return $this->decodeAuthorizationString($headerValue);+ return self::decodeAuthorizationString($headerValue);}// Bypass as the Authorization header may be used for OAuth.@@ -295,21 +285,20 @@ class Auth$username = $request->getServerParam('PHP_AUTH_USER');$password = $request->getServerParam('PHP_AUTH_PW');- if (is_string($username)) {- $username = trim($username);+ if (!is_string($username) || !is_string($password)) {+ return [null, null];}- if (is_string($password)) {- $password = trim($password);- }+ $username = trim($username);+ $password = trim($password);return [$username, $password];}- $cgiAuthString = $this->getCgiAuthString($request);+ $cgiAuthString = self::getCgiAuthString($request);if ($cgiAuthString) {- [$username, $password] = $this->decodeAuthorizationString(substr($cgiAuthString, 6));+ [$username, $password] = self::decodeAuthorizationString($cgiAuthString);return [$username, $password];}@@ -317,15 +306,49 @@ class Authreturn [null, null];}- private function obtainTokenFromCookies(Request $request): ?string+ private static function obtainTokenFromCookies(Request $request): ?string{return $request->getCookieParam('auth-token');}- private function getCgiAuthString(Request $request): ?string+ /**+ * Header might be written by a web server's rewrite rule.+ */+ private static function getCgiAuthString(Request $request): ?string{- return- $request->getHeader('Http-Espo-Cgi-Auth') ??+ $value = $request->getHeader('Http-Espo-Cgi-Auth') ??$request->getHeader('Redirect-Http-Espo-Cgi-Auth');++ if (!$value) {+ return null;+ }++ $basicPrefix = self::SCHEME_BASIC . ' ';++ if (!str_starts_with($value, $basicPrefix)) {+ return null;+ }++ return substr($value, strlen($basicPrefix));+ }++ private static function toShowDialog(Request $request): bool+ {+ return+ $request->getMethod() === Method::GET &&+ !$request->getHeader('Referer') &&+ self::isDocumentNavigate($request);+ }++ private function toShowDialogOnFail(Request $request): bool+ {+ return $this->isEntryPoint && $this->toShowDialog($request);+ }++ private static function isDocumentNavigate(Request $request): bool+ {+ return+ $request->getHeader('Sec-Fetch-Mode') === 'navigate' &&+ $request->getHeader('Sec-Fetch-Dest') === 'document';}}diff --git a/tests/unit/Espo/Core/Api/AuthTest.php b/tests/unit/Espo/Core/Api/AuthTest.phpindex 76026ff9e2..3753446c7e 100644--- a/tests/unit/Espo/Core/Api/AuthTest.php+++ b/tests/unit/Espo/Core/Api/AuthTest.php@@ -30,9 +30,11 @@namespace tests\unit\Espo\Core\Api;use Espo\Core\Api\Auth;+use Espo\Core\Api\Method;use Espo\Core\Api\RequestWrapper;use Espo\Core\Api\Response;use Espo\Core\Authentication\Authentication;+use Espo\Core\Authentication\AuthenticationData;use Espo\Core\Authentication\HeaderKey;use Espo\Core\Authentication\Login\MethodResolver;use Espo\Core\Authentication\Result;@@ -104,6 +106,48 @@ class AuthTest extends TestCase$this->assertFalse($result->isResolvedUseNoAuth());}+ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testCgiHeader(): void+ {+ $request = $this->createRequest(+ method: Method::GET,+ headers: [+ 'Http-Espo-Cgi-Auth' => 'Basic ' . base64_encode('test:1'),+ ],+ );++ $response = $this->createMock(Response::class);++ $authentication = $this->createMock(Authentication::class);+ $authentication+ ->expects(self::once())+ ->method('login')+ ->with(+ AuthenticationData::create()+ ->withUsername('test')+ ->withPassword('1')+ )+ ->willReturn(+ Result::success($this->createMock(User::class))+ );++ $auth = new Auth(+ log: $this->createMock(Log::class),+ authentication: $authentication,+ methodResolver: $this->createMock(MethodResolver::class),+ authRequired: true,+ );++ $result = $auth->process($request, $response);++ $this->assertTrue($result->isResolved());+ }++ /**+ * @noinspection PhpSameParameterValueInspection+ */private function createRequest(string $method,array $queryParams = [],