diff --git a/.env b/.env index a09c1da12d..86d469ccfc 100644 --- a/.env +++ b/.env @@ -28,6 +28,7 @@ _APP_OPTIONS_ROUTER_PROTECTION=disabled _APP_OPTIONS_ABUSE=disabled _APP_OPTIONS_ABUSE_INCREASED_LIMIT_PROJECTS=increased-limit-project _APP_CONSOLE_DOMAIN=localhost +_APP_CONSOLE_URL= _APP_CONSOLE_HOSTNAMES=localhost,appwrite.io,*.appwrite.io _APP_CONSOLE_SCHEMA=appwriteio _APP_CONSOLE_SESSION_ALERTS=enabled diff --git a/app/config/platform.php b/app/config/platform.php index 21aedaad98..d815cc2ad0 100644 --- a/app/config/platform.php +++ b/app/config/platform.php @@ -18,7 +18,10 @@ if (\str_contains($functionsDomain, ',')) { */ return [ 'apiHostname' => System::getEnv('_APP_DOMAIN', 'localhost'), + // Also serves the API (VCS OAuth callbacks, avatars, images); never point it at the console web origin 'consoleHostname' => System::getEnv('_APP_CONSOLE_DOMAIN', System::getEnv('_APP_DOMAIN', 'localhost')), + // Console web app origin for links; it can live apart from the API host above + 'consoleUrl' => \rtrim(System::getEnv('_APP_CONSOLE_URL', (System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https') . '://' . System::getEnv('_APP_CONSOLE_DOMAIN', System::getEnv('_APP_DOMAIN', 'localhost'))), '/'), 'hostnames' => array_filter(array_unique([ System::getEnv('_APP_DOMAIN', 'localhost'), System::getEnv('_APP_CONSOLE_DOMAIN', 'localhost'), diff --git a/app/config/variables.php b/app/config/variables.php index 4421d51ba0..2299dcfe5c 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -242,10 +242,10 @@ return [ 'filter' => '' ], [ - 'name' => '_APP_CONSOLE_URL_SCHEME', - 'description' => 'Console URL scheme used when the backend generates links to the console (OAuth callbacks, emails, error page CTAs, VCS comments). Set to \'root\' for the new console served at the root path (appwrite/new), or \'legacy\' for the older console served under the /console path prefix. The default value is \'legacy\'.', - 'introduction' => '2.0.0', - 'default' => 'legacy', + 'name' => '_APP_CONSOLE_URL', + 'description' => 'Origin of the Appwrite console web app, such as https://console.example.com, used when the backend generates links to the console (OAuth callbacks, emails, error page CTAs, VCS comments and commit statuses). Set it when the console is served on a different host than the API. When empty, links use _APP_CONSOLE_DOMAIN (or _APP_DOMAIN) over https, or over http when _APP_OPTIONS_FORCE_HTTPS is disabled.', + 'introduction' => '2.2.1', + 'default' => '', 'required' => false, 'question' => '', 'filter' => '' diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 4bad06ca4e..5fede6a7fd 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -77,10 +77,8 @@ use Utopia\Validator\Range; use Utopia\Validator\Text; use Utopia\Validator\WhiteList; -$legacyConsolePaths = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root'; - -$oauthDefaultSuccess = $legacyConsolePaths ? '/console/auth/oauth2/success' : '/auth/oauth2/success'; -$oauthDefaultFailure = $legacyConsolePaths ? '/console/auth/oauth2/failure' : '/auth/oauth2/failure'; +$oauthDefaultSuccess = '/auth/oauth2/success'; +$oauthDefaultFailure = '/auth/oauth2/failure'; $createSession = function (string $userId, string $secret, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Geo $geo, Event $queueForEvents, Bus $bus, Store $store, ProofsToken $proofForToken, ProofsCode $proofForCode, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) { @@ -1378,11 +1376,9 @@ Http::get('/v1/account/sessions/oauth2/:provider') throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED); } - $host = $platform['consoleHostname'] ?? ''; - $redirectBase = $protocol . '://' . $host; - if ($protocol === 'https' && $port !== '443') { - $redirectBase .= ':' . $port; - } elseif ($protocol === 'http' && $port !== '80') { + $redirectBase = $platform['consoleUrl'] ?? ''; + // Only the derived console URL follows the request port; an explicit one carries its own + if (empty(System::getEnv('_APP_CONSOLE_URL')) && $port !== ($protocol === 'https' ? '443' : '80')) { $redirectBase .= ':' . $port; } @@ -1512,7 +1508,8 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect') ->inject('domainVerification') ->inject('cookieDomain') ->inject('authorization') - ->action(function (string $provider, string $code, string $state, string $error, string $error_description, Request $request, Response $response, Document $project, Validator $redirectValidator, Document $devKey, User $user, Database $dbForProject, Geo $geo, Database $dbForPlatform, Event $queueForEvents, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, array $plan, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) use ($oauthDefaultSuccess, $oauthDefaultFailure) { + ->inject('platform') + ->action(function (string $provider, string $code, string $state, string $error, string $error_description, Request $request, Response $response, Document $project, Validator $redirectValidator, Document $devKey, User $user, Database $dbForProject, Geo $geo, Database $dbForPlatform, Event $queueForEvents, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, array $plan, bool $domainVerification, ?string $cookieDomain, Authorization $authorization, array $platform) use ($oauthDefaultSuccess, $oauthDefaultFailure) { $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; $port = $request->getPort(); $callbackBase = $protocol . '://' . $request->getHostname(); @@ -1580,12 +1577,15 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect') if ($devKey->isEmpty() && !empty($state['failure']) && !$redirectValidator->isValid($state['failure'])) { throw new Exception(Exception::PROJECT_INVALID_FAILURE_URL); } + // The default relays live on the console host; the same path on any other allowed host is a customer page + $consoleHostname = \parse_url($platform['consoleUrl'] ?? '', PHP_URL_HOST); + $failure = []; if (!empty($state['failure'])) { $failure = URLParser::parse($state['failure']); } - $failureRedirect = (function (string $type, ?string $message = null, ?int $code = null, ?\Throwable $previous = null, array $params = []) use ($failure, $response, $project, $oauthDefaultFailure) { + $failureRedirect = (function (string $type, ?string $message = null, ?int $code = null, ?\Throwable $previous = null, array $params = []) use ($failure, $response, $project, $oauthDefaultFailure, $consoleHostname) { $exception = new Exception($type, $message, $code, $previous, params: $params); if (!empty($failure)) { $query = URLParser::parseQuery($failure['query']); @@ -1596,7 +1596,7 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect') ]); // Mirror success path: default OAuth failure relay needs project to deep-link // back into the native app via appwrite-callback-{project}:// - if (($failure['path'] ?? '') === $oauthDefaultFailure) { + if ($failure['host'] === $consoleHostname && $failure['path'] === $oauthDefaultFailure) { $query['project'] = $project->getId(); } $failure['query'] = URLParser::unparseQuery($query); @@ -2179,7 +2179,7 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect') ; // TODO: Remove this deprecated workaround - support only token - if ($state['success']['path'] == $oauthDefaultSuccess) { + if ($state['success']['host'] === $consoleHostname && $state['success']['path'] === $oauthDefaultSuccess) { $query['project'] = $project->getId(); $query['domain'] = $cookieDomain; $query['key'] = $store->getKey(); @@ -2285,13 +2285,11 @@ Http::get('/v1/account/tokens/oauth2/:provider') throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED); } - $host = $platform['consoleHostname'] ?? ''; $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; $port = $request->getPort(); - $redirectBase = $protocol . '://' . $host; - if ($protocol === 'https' && $port !== '443') { - $redirectBase .= ':' . $port; - } elseif ($protocol === 'http' && $port !== '80') { + $redirectBase = $platform['consoleUrl'] ?? ''; + // Only the derived console URL follows the request port; an explicit one carries its own + if (empty(System::getEnv('_APP_CONSOLE_URL')) && $port !== ($protocol === 'https' ? '443' : '80')) { $redirectBase .= ':' . $port; } @@ -2358,7 +2356,7 @@ Http::post('/v1/account/tokens/magic-url') ->inject('proofForPassword') ->inject('platform') ->inject('authorization') - ->action(function (string $userId, string $email, string $url, bool $phrase, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Locale $locale, Event $queueForEvents, MailPublisher $publisherForMails, array $plan, ProofsPassword $proofForPassword, array $platform, Authorization $authorization) use ($legacyConsolePaths) { + ->action(function (string $userId, string $email, string $url, bool $phrase, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Locale $locale, Event $queueForEvents, MailPublisher $publisherForMails, array $plan, ProofsPassword $proofForPassword, array $platform, Authorization $authorization) { if (empty(System::getEnv('_APP_SMTP_HOST'))) { throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP disabled'); } @@ -2496,17 +2494,13 @@ Http::post('/v1/account/tokens/magic-url') if (empty($url)) { $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; - $host = $platform['consoleHostname'] ?? ''; $port = $request->getPort(); - $callbackBase = $protocol . '://' . $host; - if ($protocol === 'https' && $port !== '443') { - $callbackBase .= ':' . $port; - } elseif ($protocol === 'http' && $port !== '80') { + $callbackBase = $platform['consoleUrl'] ?? ''; + // Only the derived console URL follows the request port; an explicit one carries its own + if (empty(System::getEnv('_APP_CONSOLE_URL')) && $port !== ($protocol === 'https' ? '443' : '80')) { $callbackBase .= ':' . $port; } - $url = $legacyConsolePaths - ? "{$callbackBase}/console/auth/magic-url" - : "{$callbackBase}/auth/magic-url"; + $url = "{$callbackBase}/auth/magic-url"; } $url = Template::parseURL($url); diff --git a/app/controllers/general.php b/app/controllers/general.php index 40a0751174..7d7b6204f2 100644 --- a/app/controllers/general.php +++ b/app/controllers/general.php @@ -98,8 +98,7 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S } $errorView = __DIR__ . '/../views/general/error.phtml'; - $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') == 'disabled' ? 'http' : 'https'; - $url = $protocol . '://' . $platform['consoleHostname']; + $url = $platform['consoleUrl'] ?? ''; $platformHostnames = $platform['hostnames'] ?? []; if ($rule->isEmpty()) { @@ -126,7 +125,7 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S if (\str_ends_with($host, $denyDomain)) { $exception = new AppwriteException(AppwriteException::RULE_NOT_FOUND, 'This domain is not connected to any Appwrite resources. Visit domains tab under function/site settings to configure it.', view: $errorView); - $exception->addCTA('Start with this domain', System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' ? "{$url}/console" : $url); + $exception->addCTA('Start with this domain', $url); throw $exception; } } @@ -205,11 +204,7 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S $resourceId = $rule->getAttribute('deploymentResourceId', ''); $type = ($resourceType === 'site') ? 'sites' : 'functions'; $exception = new AppwriteException(AppwriteException::DEPLOYMENT_NOT_FOUND, view: $errorView); - $region = $project->getAttribute('region', 'default'); - $ctaUrl = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? "/console/project-{$region}-{$projectId}/{$type}/{$resourceType}-{$resourceId}" - : "/projects/{$projectId}/{$type}/{$resourceId}"; - $exception->addCTA('View deployments', $url . $ctaUrl); + $exception->addCTA('View deployments', $url . "/projects/{$projectId}/{$type}/{$resourceId}"); throw $exception; } @@ -294,11 +289,10 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S } if (!$authorized) { - $url = $protocol . "://" . $platform['consoleHostname']; $response ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') ->addHeader('Pragma', 'no-cache') - ->redirect($url . (System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' ? '/console/auth/preview?' : '/auth/preview?') + ->redirect($url . '/auth/preview?' . \http_build_query([ 'projectId' => $projectId, 'origin' => $protocol . '://' . $host, @@ -355,14 +349,11 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S $allowAnyStatus = !\is_null($apiKey) && $apiKey->isDeploymentStatusIgnored(); if (!$allowAnyStatus && $deployment->getAttribute('status') !== 'ready') { $status = $deployment->getAttribute('status'); - $region = $project->getAttribute('region', 'default'); - $legacyConsolePaths = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root'; - $siteUrl = $legacyConsolePaths - ? "/console/project-{$region}-{$project->getId()}/sites/site-{$resource->getId()}" - : "/projects/{$project->getId()}/sites/{$resource->getId()}"; - $deploymentUrl = $legacyConsolePaths - ? "{$siteUrl}/deployments/deployment-{$deployment->getId()}" - : "{$siteUrl}/deployments/{$deployment->getId()}"; + $collection = $type === 'function' ? 'functions' : 'sites'; + $resourceUrl = "/projects/{$project->getId()}/{$collection}/{$resource->getId()}"; + // Function deployments are listed on the function page itself + $deploymentsUrl = $type === 'function' ? $resourceUrl : "{$resourceUrl}/deployments"; + $deploymentUrl = "{$resourceUrl}/deployments/{$deployment->getId()}"; switch ($status) { case 'failed': @@ -371,7 +362,7 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S break; case 'canceled': $exception = new AppwriteException(AppwriteException::BUILD_CANCELED, view: $errorView); - $exception->addCTA('View deployments', $url . $siteUrl . '/deployments'); + $exception->addCTA('View deployments', $url . $deploymentsUrl); break; default: $exception = new AppwriteException(AppwriteException::BUILD_NOT_READY, view: $errorView); @@ -386,11 +377,7 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S $permissions = $resource->getAttribute('execute'); if (!(\in_array('any', $permissions)) && !(\in_array('guests', $permissions))) { $exception = new AppwriteException(AppwriteException::FUNCTION_EXECUTE_PERMISSION_MISSING, view: $errorView); - $region = $project->getAttribute('region', 'default'); - $ctaUrl = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? "/console/project-{$region}-{$project->getId()}/functions/function-{$resource->getId()}/settings" - : "/projects/{$project->getId()}/functions/{$resource->getId()}/settings"; - $exception->addCTA('View settings', $url . $ctaUrl); + $exception->addCTA('View settings', $url . "/projects/{$project->getId()}/functions/{$resource->getId()}/settings"); throw $exception; } } diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 7f4d949e77..3453c7e5a6 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -251,6 +251,12 @@ return function (Container $context): void { $context->set('allowedHostnames', function (array $platform, Document $project, Document $rule, Document $devKey, Request $request) { $allowed = [...($platform['hostnames'] ?? [])]; + /* Add the console host, the default OAuth2 redirects land on it even when _APP_CONSOLE_URL points elsewhere */ + $consoleHostname = \parse_url($platform['consoleUrl'] ?? '', PHP_URL_HOST); + if (! empty($consoleHostname)) { + $allowed[] = $consoleHostname; + } + /* Add platform configured hostnames */ if (! $project->isEmpty() && $project->getId() !== 'console') { $platforms = $project->getAttribute('platforms', []); diff --git a/docker-compose.yml b/docker-compose.yml index 333bcd9e61..af48453b59 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -124,7 +124,7 @@ services: - _APP_NOTIFICATIONS_TRACKING_SECRET - _APP_DOMAIN - _APP_CONSOLE_DOMAIN - - _APP_CONSOLE_URL_SCHEME=root + - _APP_CONSOLE_URL - _APP_CONSOLE_TRUSTED_PROJECTS - _APP_DOMAIN_TARGET_CNAME - _APP_DOMAIN_TARGET_AAAA @@ -427,8 +427,8 @@ services: - _APP_LOGGING_FORMAT - _APP_QUEUE_NAME - _APP_DATABASE_SHARED_TABLES - - _APP_CONSOLE_URL_SCHEME=root - _APP_CONSOLE_DOMAIN + - _APP_CONSOLE_URL - _APP_CONSOLE_TRUSTED_PROJECTS - _APP_DOMAIN - _APP_DOMAIN_TARGET_CNAME @@ -634,7 +634,10 @@ services: - _APP_LOGGING_FORMAT - _APP_WEBHOOK_MAX_FAILED_ATTEMPTS - _APP_DATABASE_SHARED_TABLES - - _APP_CONSOLE_URL_SCHEME=root + - _APP_OPTIONS_FORCE_HTTPS + - _APP_DOMAIN + - _APP_CONSOLE_DOMAIN + - _APP_CONSOLE_URL appwrite-worker-deletes: profiles: - separate @@ -847,7 +850,7 @@ services: - _APP_OPTIONS_ROUTER_FORCE_HTTPS - _APP_DOMAIN - _APP_CONSOLE_DOMAIN - - _APP_CONSOLE_URL_SCHEME=root + - _APP_CONSOLE_URL - _APP_CONSOLE_TRUSTED_PROJECTS - _APP_STORAGE_DEVICE - _APP_STORAGE_S3_ACCESS_KEY @@ -942,6 +945,10 @@ services: - _APP_LOGGING_CONFIG - _APP_LOGGING_FORMAT - _APP_DATABASE_SHARED_TABLES + - _APP_OPTIONS_FORCE_HTTPS + - _APP_DOMAIN + - _APP_CONSOLE_DOMAIN + - _APP_CONSOLE_URL extra_hosts: - host.docker.internal:host-gateway diff --git a/src/Appwrite/Deployment/GitAction.php b/src/Appwrite/Deployment/GitAction.php index 0d5d4103d6..c668029e49 100644 --- a/src/Appwrite/Deployment/GitAction.php +++ b/src/Appwrite/Deployment/GitAction.php @@ -50,13 +50,8 @@ final class GitAction default => $status }; - $hostname = $platform['consoleHostname'] ?? ''; - $region = $project->getAttribute('region', 'default'); $collection = $isSite ? 'sites' : 'functions'; - $type = $isSite ? 'site' : 'function'; - $targetUrl = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? "{$protocol}://{$hostname}/console/project-{$region}-{$project->getId()}/{$collection}/{$type}-{$resource->getId()}" - : "{$protocol}://{$hostname}/projects/{$project->getId()}/{$collection}/{$resource->getId()}"; + $targetUrl = ($platform['consoleUrl'] ?? '') . "/projects/{$project->getId()}/{$collection}/{$resource->getId()}"; $name = $resource->getAttribute('name') . ' (' . $project->getAttribute('name') . ')'; $vcs->updateCommitStatus($repositoryName, $commitHash, $owner, $state, $message, $targetUrl, $name); diff --git a/src/Appwrite/Platform/Modules/Console/Http/Redirects/Base.php b/src/Appwrite/Platform/Modules/Console/Http/Redirects/Base.php index 4b36319255..888bf711f8 100644 --- a/src/Appwrite/Platform/Modules/Console/Http/Redirects/Base.php +++ b/src/Appwrite/Platform/Modules/Console/Http/Redirects/Base.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\Console\Http\Redirects; +use Appwrite\Extend\Exception; use Appwrite\Utopia\Request; use Appwrite\Utopia\Response; use Utopia\Platform\Action; @@ -21,6 +22,14 @@ abstract class Base extends Action */ abstract protected function getPath(): string; + /** + * Console route to land on, the request path unless the console names it differently. + */ + protected function getTarget(string $path, array $params): string + { + return $path; + } + public function __construct() { $this @@ -31,14 +40,22 @@ abstract class Base extends Action ->label('scope', 'home') ->inject('request') ->inject('response') + ->inject('platform') ->callback($this->action(...)); } - public function action(Request $request, Response $response): void + public function action(Request $request, Response $response, array $platform): void { + $consoleUrl = $platform['consoleUrl'] ?? ''; + + // On the console's own host the proxy serves these paths, so redirecting would loop + if ($request->getHostname() === \parse_url($consoleUrl, PHP_URL_HOST)) { + throw new Exception(Exception::GENERAL_ROUTE_NOT_FOUND); + } + $url = parse_url($request->getURI()); - $target = "/console" . ($url['path'] ?? ''); $params = $request->getParams(); + $target = $consoleUrl . $this->getTarget($url['path'] ?? '', $params); if (!empty($params)) { $target .= "?" . \http_build_query($params); } diff --git a/src/Appwrite/Platform/Modules/Console/Http/Redirects/Card/Get.php b/src/Appwrite/Platform/Modules/Console/Http/Redirects/Card/Get.php deleted file mode 100644 index c98c125f4e..0000000000 --- a/src/Appwrite/Platform/Modules/Console/Http/Redirects/Card/Get.php +++ /dev/null @@ -1,18 +0,0 @@ -addAction(CreateAssistantQuery::getName(), new CreateAssistantQuery()); $this->addAction(GetResourceAvailability::getName(), new GetResourceAvailability()); - // web redirects to /console + // web redirects to the console $this->addAction(RedirectRoot::getName(), new RedirectRoot()); $this->addAction(RedirectAuth::getName(), new RedirectAuth()); $this->addAction(RedirectInvite::getName(), new RedirectInvite()); $this->addAction(RedirectLogin::getName(), new RedirectLogin()); $this->addAction(RedirectMFA::getName(), new RedirectMFA()); - $this->addAction(RedirectCard::getName(), new RedirectCard()); $this->addAction(RedirectRecover::getName(), new RedirectRecover()); $this->addAction(RedirectRegister::getName(), new RedirectRegister()); } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php b/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php index 55f9ee1d2f..1b5d697c1d 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php @@ -101,13 +101,12 @@ abstract class Base extends Action return; } - $region = $project->getAttribute('region', 'default'); $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; $hostname = $platform['consoleHostname'] ?? ''; $defaultState = [ - 'success' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", - 'failure' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", + 'success' => ($platform['consoleUrl'] ?? '') . "/projects/$projectId/settings", + 'failure' => ($platform['consoleUrl'] ?? '') . "/projects/$projectId/settings", ]; $redirectSuccess = empty($state['success']) ? $defaultState['success'] : $state['success']; diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php index eb53da9857..2b17642924 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php @@ -98,13 +98,9 @@ class Get extends Action throw new Exception(Exception::PROJECT_NOT_FOUND, $error); } - $region = $project->getAttribute('region', 'default'); - $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; - $hostname = $platform['consoleHostname'] ?? ''; - $defaultState = [ - 'success' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", - 'failure' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", + 'success' => ($platform['consoleUrl'] ?? '') . "/projects/$projectId/settings", + 'failure' => ($platform['consoleUrl'] ?? '') . "/projects/$projectId/settings", ]; $redirectSuccess = empty($state['success']) ? $defaultState['success'] : $state['success']; diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php index d5ea712b6c..1f26df9b1b 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php @@ -164,11 +164,9 @@ trait Deployment Span::add("{$logBase}.authorized", $isAuthorized); $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; - $hostname = $platform['consoleHostname'] ?? ''; + $consoleUrl = $platform['consoleUrl'] ?? ''; - $authorizeUrl = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? $protocol . '://' . $hostname . "/console/git/authorize-contributor?projectId={$projectId}&installationId={$installationId}&repositoryId={$repositoryId}&providerPullRequestId={$providerPullRequestId}" - : $protocol . '://' . $hostname . "/git/authorize-contributor?projectId={$projectId}&installationId={$installationId}&repositoryId={$repositoryId}&providerPullRequestId={$providerPullRequestId}"; + $authorizeUrl = $consoleUrl . "/git/authorize-contributor?projectId={$projectId}&installationId={$installationId}&repositoryId={$repositoryId}&providerPullRequestId={$providerPullRequestId}"; $action = $isAuthorized ? ['type' => 'logs'] : ['type' => 'authorize', 'url' => $authorizeUrl]; @@ -557,7 +555,6 @@ trait Deployment if (!empty($providerCommitHash) && $resource->getAttribute('providerSilentMode', false) === false) { $resourceName = $resource->getAttribute('name'); $projectName = $project->getAttribute('name'); - $region = $project->getAttribute('region', 'default'); $name = "{$resourceName} ({$projectName})"; $message = 'Starting...'; @@ -569,9 +566,7 @@ trait Deployment } $owner = $vcs->getOwnerName($providerInstallationId, (int) $providerRepositoryId); - $providerTargetUrl = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? $protocol . '://' . $hostname . "/console/project-$region-$projectId/$resourceCollection/$resourceType-$resourceId" - : $protocol . '://' . $hostname . "/projects/$projectId/$resourceCollection/$resourceId"; + $providerTargetUrl = $consoleUrl . "/projects/$projectId/$resourceCollection/$resourceId"; $vcs->updateCommitStatus($repositoryName, $providerCommitHash, $owner, 'pending', $message, $providerTargetUrl, $name); } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php index 9488a34343..5ed3364133 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php @@ -104,13 +104,9 @@ class Get extends Action return; } - $region = $project->getAttribute('region', 'default'); - $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; - $hostname = $platform['consoleHostname'] ?? ''; - $defaultState = [ - 'success' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", - 'failure' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", + 'success' => ($platform['consoleUrl'] ?? '') . "/projects/$projectId/settings", + 'failure' => ($platform['consoleUrl'] ?? '') . "/projects/$projectId/settings", ]; $state = \array_merge($defaultState, \array_filter($state)); diff --git a/src/Appwrite/Platform/Workers/Notifications.php b/src/Appwrite/Platform/Workers/Notifications.php index caca7bb060..a5de91224b 100644 --- a/src/Appwrite/Platform/Workers/Notifications.php +++ b/src/Appwrite/Platform/Workers/Notifications.php @@ -52,10 +52,11 @@ class Notifications extends Action ->inject('project') ->inject('register') ->inject('dbForPlatform') + ->inject('platform') ->callback($this->action(...)); } - public function action(Message $message, Document $project, Registry $register, Database $dbForPlatform): void + public function action(Message $message, Document $project, Registry $register, Database $dbForPlatform, array $platform): void { $payload = $message->getPayload(); @@ -90,7 +91,7 @@ class Notifications extends Action } try { - $alertId = $this->dispatch($recipient, $messageId, $payload, $project, $register, $dbForPlatform); + $alertId = $this->dispatch($recipient, $messageId, $payload, $project, $register, $dbForPlatform, $platform); if ($messageId !== '' && $channel === NOTIFICATION_TYPE_WEBHOOK && $alertId === null) { $this->persistAlert($dbForPlatform, $messageId, $recipient, $payload, $project); } @@ -173,11 +174,12 @@ class Notifications extends Action Document $project, Registry $register, Database $dbForPlatform, + array $platform, ): ?string { $channel = $recipient['channel']; return match ($channel) { - NOTIFICATION_TYPE_EMAIL => $this->dispatchEmail($recipient, $messageId, $payload, $project, $register, $dbForPlatform), + NOTIFICATION_TYPE_EMAIL => $this->dispatchEmail($recipient, $messageId, $payload, $project, $register, $dbForPlatform, $platform), NOTIFICATION_TYPE_CONSOLE => $this->dispatchConsole($recipient, $messageId, $payload, $project, $dbForPlatform), NOTIFICATION_TYPE_WEBHOOK => $this->dispatchWebhook($recipient, $payload), default => throw new Exception('Unsupported notification channel: ' . $channel), @@ -194,6 +196,7 @@ class Notifications extends Action Document $project, Registry $register, Database $dbForPlatform, + array $platform, ): ?string { $address = $recipient['address']; $smtp = $this->resolveSmtpConfig($project, $payload); @@ -206,13 +209,10 @@ class Notifications extends Action $type = empty($smtp) ? 'cloud' : 'smtp'; Span::add('type', $type); - $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'disabled' ? 'http' : 'https'; - $consoleHostname = System::getEnv('_APP_CONSOLE_DOMAIN', System::getEnv('_APP_DOMAIN', 'localhost')); - $subject = $payload['subject'] ?? ''; $variables = $payload['variables'] ?? []; $variables = \array_merge($variables, $payload['templateParams'] ?? []); - $variables['host'] = $protocol . '://' . $consoleHostname; + $variables['host'] = $platform['consoleUrl'] ?? ''; $name = $payload['name'] ?? ''; $body = $payload['body'] ?? ''; $preview = $payload['preview'] ?? ''; diff --git a/src/Appwrite/Platform/Workers/Webhooks.php b/src/Appwrite/Platform/Workers/Webhooks.php index 76667cc350..297529630c 100644 --- a/src/Appwrite/Platform/Workers/Webhooks.php +++ b/src/Appwrite/Platform/Workers/Webhooks.php @@ -45,6 +45,7 @@ class Webhooks extends Action ->inject('dbForPlatform') ->inject('publisherForNotifications') ->inject('publisherForUsage') + ->inject('platform') ->inject('plan') ->callback($this->action(...)); } @@ -55,11 +56,12 @@ class Webhooks extends Action * @param Database $dbForPlatform * @param NotificationPublisher $publisherForNotifications * @param UsagePublisher $publisherForUsage + * @param array $platform * @param array $plan * @return void * @throws Exception */ - public function action(Message $message, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, UsagePublisher $publisherForUsage, array $plan): void + public function action(Message $message, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, UsagePublisher $publisherForUsage, array $platform, array $plan): void { $payload = $message->getPayload(); @@ -76,7 +78,7 @@ class Webhooks extends Action $errors = []; foreach ($project->getAttribute('webhooks', []) as $webhook) { if (array_intersect($webhook->getAttribute('events', []), $events)) { - $error = $this->execute($events, $webhookPayload, $webhook, $user, $project, $dbForPlatform, $publisherForNotifications, $publisherForUsage, $plan); + $error = $this->execute($events, $webhookPayload, $webhook, $user, $project, $dbForPlatform, $publisherForNotifications, $publisherForUsage, $platform, $plan); if ($error !== null) { $errors[] = $error; } @@ -97,10 +99,11 @@ class Webhooks extends Action * @param Database $dbForPlatform * @param NotificationPublisher $publisherForNotifications * @param UsagePublisher $publisherForUsage + * @param array $platform * @param array $plan * @return string|null The error log if the delivery failed, otherwise null */ - private function execute(array $events, string $payload, Document $webhook, Document $user, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, UsagePublisher $publisherForUsage, array $plan): ?string + private function execute(array $events, string $payload, Document $webhook, Document $user, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, UsagePublisher $publisherForUsage, array $platform, array $plan): ?string { if ($webhook->getAttribute('enabled') !== true) { return null; @@ -196,7 +199,7 @@ class Webhooks extends Action if ($attempts >= \intval(System::getEnv('_APP_WEBHOOK_MAX_FAILED_ATTEMPTS', '10'))) { $webhook->setAttribute('enabled', false); $updatePayload['enabled'] = false; - $this->sendAlert($attempts, $statusCode, $webhook, $project, $dbForPlatform, $publisherForNotifications, $plan); + $this->sendAlert($attempts, $statusCode, $webhook, $project, $dbForPlatform, $publisherForNotifications, $platform, $plan); } $dbForPlatform->updateDocument('webhooks', $webhook->getId(), new Document($updatePayload)); @@ -237,10 +240,11 @@ class Webhooks extends Action * @param Document $project * @param Database $dbForPlatform * @param NotificationPublisher $publisherForNotifications + * @param array $platform * @param array $plan * @return void */ - public function sendAlert(int $attempts, mixed $statusCode, Document $webhook, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, array $plan): void + public function sendAlert(int $attempts, mixed $statusCode, Document $webhook, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, array $platform, array $plan): void { $memberships = $dbForPlatform->find('memberships', [ Query::equal('teamInternalId', [$project->getAttribute('teamInternalId')]), @@ -276,11 +280,6 @@ class Webhooks extends Action $projectId = $project->getId(); $projectInternalId = $project->getSequence(); - $region = $project->getAttribute('region', 'default'); - $webhookId = $webhook->getId(); - - $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'disabled' ? 'http' : 'https'; - $consoleHostname = System::getEnv('_APP_CONSOLE_DOMAIN', System::getEnv('_APP_DOMAIN', 'localhost')); $subject = 'Webhook deliveries have been paused'; $preview = 'Webhook "' . $webhook->getAttribute('name') . '" has been paused after ' . $attempts . ' failed delivery attempts.'; @@ -320,10 +319,8 @@ class Webhooks extends Action $template->setParam('{{project}}', $project->getAttribute('name')); $template->setParam('{{url}}', $webhook->getAttribute('url')); $template->setParam('{{error}}', 'The server returned ' . $statusCode . ' status code'); - $template->setParam('{{host}}', $protocol . '://' . $consoleHostname); - $template->setParam('{{path}}', System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? "/console/project-{$region}-{$projectId}/settings/webhooks/{$webhookId}" - : "/projects/{$projectId}/settings/webhooks"); + $template->setParam('{{host}}', $platform['consoleUrl'] ?? ''); + $template->setParam('{{path}}', "/projects/{$projectId}/settings/webhooks"); $template->setParam('{{attempts}}', $attempts); $publisherForNotifications->enqueue(new NotificationMessage( diff --git a/src/Appwrite/Vcs/Comment.php b/src/Appwrite/Vcs/Comment.php index 328dcaa19a..700f37b5e1 100644 --- a/src/Appwrite/Vcs/Comment.php +++ b/src/Appwrite/Vcs/Comment.php @@ -162,9 +162,7 @@ class Comment }; if ($site['action']['type'] === 'logs') { - $logsUrl = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? "{$protocol}://{$hostname}/console/project-{$site['region']}-{$projectId}/sites/site-{$siteId}/deployments/deployment-{$site['deploymentId']}" - : "{$protocol}://{$hostname}/projects/{$projectId}/sites/{$siteId}/deployments/{$site['deploymentId']}"; + $logsUrl = ($this->platform['consoleUrl'] ?? '') . "/projects/{$projectId}/sites/{$siteId}/deployments/{$site['deploymentId']}"; $action = "[View Logs]({$logsUrl})"; } else { $action = '[Authorize](' . $site['action']['url'] . ')'; @@ -173,10 +171,10 @@ class Comment $qrImagePathLight = '/images/vcs/qr-light.svg'; $qrImagePathDark = '/images/vcs/qr-dark.svg'; - $consoleUrl = $protocol . '://' . $hostname . '/v1/avatars/qr?text=' . \urlencode($site['previewUrl']); + $qrUrl = $protocol . '://' . $hostname . '/v1/avatars/qr?text=' . \urlencode($site['previewUrl']); $qr = $this->withImages - ? '[' . $this->generatImage($qrImagePathLight, $qrImagePathDark, 'QR Code', 28) . '](' . $consoleUrl . ')' - : '[QR Code](' . $consoleUrl . ')'; + ? '[' . $this->generatImage($qrImagePathLight, $qrImagePathDark, 'QR Code', 28) . '](' . $qrUrl . ')' + : '[QR Code](' . $qrUrl . ')'; $preview = '[Preview URL](' . $site['previewUrl'] . ')'; @@ -215,9 +213,7 @@ class Comment }; if ($function['action']['type'] === 'logs') { - $logsUrl = System::getEnv('_APP_CONSOLE_URL_SCHEME', 'legacy') !== 'root' - ? "{$protocol}://{$hostname}/console/project-{$function['region']}-{$projectId}/functions/function-{$functionId}/deployment-{$function['deploymentId']}" - : "{$protocol}://{$hostname}/projects/{$projectId}/functions/{$functionId}/deployments/{$function['deploymentId']}"; + $logsUrl = ($this->platform['consoleUrl'] ?? '') . "/projects/{$projectId}/functions/{$functionId}/deployments/{$function['deploymentId']}"; $action = "[View Logs]({$logsUrl})"; } else { $action = '[Authorize](' . $function['action']['url'] . ')'; diff --git a/tests/e2e/General/HTTPTest.php b/tests/e2e/General/HTTPTest.php index 42d49bbabc..d9e9d2c9e5 100644 --- a/tests/e2e/General/HTTPTest.php +++ b/tests/e2e/General/HTTPTest.php @@ -120,11 +120,11 @@ final class HTTPTest extends Scope public function testDefaultOAuth2() { - $response = $this->client->call(Client::METHOD_GET, '/console/auth/oauth2/success', $this->getHeaders()); + $response = $this->client->call(Client::METHOD_GET, '/auth/oauth2/success', $this->getHeaders()); $this->assertEquals(200, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_GET, '/console/auth/oauth2/failure', $this->getHeaders()); + $response = $this->client->call(Client::METHOD_GET, '/auth/oauth2/failure', $this->getHeaders()); $this->assertEquals(200, $response['headers']['status-code']); } @@ -239,9 +239,10 @@ final class HTTPTest extends Scope $endpoint = '/invite?membershipId=123&userId=asdf'; - $response = $this->client->call(Client::METHOD_GET, $endpoint, [], [], true, false); + // Requests on the console's own host are left to the proxy, so arrive on the API host + $response = $this->client->call(Client::METHOD_GET, $endpoint, ['host' => 'appwrite.test'], [], true, false); - $this->assertEquals('/console' . $endpoint, $response['headers']['location']); + $this->assertEquals('http://localhost/join?membershipId=123&userId=asdf', $response['headers']['location']); } public function testConsoleServed() diff --git a/tests/e2e/Services/Account/AccountCustomClientTest.php b/tests/e2e/Services/Account/AccountCustomClientTest.php index c7fd0eb5a6..a67eca11e6 100644 --- a/tests/e2e/Services/Account/AccountCustomClientTest.php +++ b/tests/e2e/Services/Account/AccountCustomClientTest.php @@ -3440,7 +3440,7 @@ final class AccountCustomClientTest extends Scope $this->assertEquals(200, $response['headers']['status-code']); - // Omit failure so Appwrite uses the default relay URL (/auth/oauth2/failure or legacy /console/...) + // Omit failure so Appwrite uses the default relay URL (/auth/oauth2/failure) $response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/' . $provider, [ 'origin' => 'http://localhost', 'content-type' => 'application/json', @@ -3481,7 +3481,7 @@ final class AccountCustomClientTest extends Scope $query = []; \parse_str((string) \parse_url($location, PHP_URL_QUERY), $query); - $this->assertContains($path, ['/auth/oauth2/failure', '/console/auth/oauth2/failure']); + $this->assertEquals('/auth/oauth2/failure', $path); $this->assertEquals($projectId, $query['project'] ?? null); $this->assertNotEmpty($query['error'] ?? null); diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index baa2805529..8db0756915 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -238,7 +238,7 @@ final class VCSGiteaConsoleClientTest extends Scope /** @var array $cookies */ $cookies = []; $this->giteaCookies = $cookies; - $consoleUrl = $this->gitInstallationsUrl($projectId); + $consoleUrl = $this->settingsUrl($projectId); $authorize = $this->client->call(Client::METHOD_GET, '/vcs/gitea/authorize', \array_merge([ 'x-appwrite-project' => $projectId, @@ -490,7 +490,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithTamperedState(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = $this->gitInstallationsUrl($projectId); + $consoleUrl = $this->settingsUrl($projectId); $state = \json_decode($this->buildGiteaState($projectId, $consoleUrl, $consoleUrl), true); $state['projectId'] = 'victim-project'; @@ -506,7 +506,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithoutCode(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = $this->gitInstallationsUrl($projectId); + $consoleUrl = $this->settingsUrl($projectId); // Signed state, no code: the failure redirect carries the error as a query string $response = $this->callGiteaCallbackHelper([ @@ -529,7 +529,7 @@ final class VCSGiteaConsoleClientTest extends Scope ]); $this->assertEquals(301, $response['headers']['status-code']); - $this->assertStringStartsWith($this->gitInstallationsUrl($projectId) . '?error=', (string) $response['headers']['location']); + $this->assertStringStartsWith($this->settingsUrl($projectId) . '?error=', (string) $response['headers']['location']); } public function testCreateInstallationWithInvalidState(): void @@ -541,7 +541,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithUnknownProject(): void { - $consoleUrl = $this->gitInstallationsUrl('missing'); + $consoleUrl = $this->settingsUrl('missing'); $response = $this->callGiteaCallbackHelper([ 'code' => 'unused', @@ -555,7 +555,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithLongState(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = $this->gitInstallationsUrl($projectId); + $consoleUrl = $this->settingsUrl($projectId); // Past the old 2048 cap: redirect URLs are not length-limited, so the // authorize endpoint can produce a state this size itself. @@ -579,16 +579,9 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertNotEmpty($installation['$id']); } - /** - * The callback builds its fallback redirect from the project's region, so the - * expected URL follows the region the scope's project was created in: Cloud - * CI creates projects in a region other than default. - */ - private function gitInstallationsUrl(string $projectId): string + private function settingsUrl(string $projectId): string { - $region = $this->getProject()['region']; - - return "http://localhost/console/project-{$region}-{$projectId}/settings/git-installations"; + return "http://localhost/projects/{$projectId}/settings"; } /** @@ -834,7 +827,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithUnsignedState(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = 'http://localhost/console/project-default-' . $projectId . '/settings/git-installations'; + $consoleUrl = 'http://localhost/projects/' . $projectId . '/settings'; $state = \json_decode($this->buildGiteaState($projectId, $consoleUrl, $consoleUrl), true); unset($state['signature']); @@ -847,7 +840,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithTamperedRedirects(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = 'http://localhost/console/project-default-' . $projectId . '/settings/git-installations'; + $consoleUrl = 'http://localhost/projects/' . $projectId . '/settings'; foreach (['success', 'failure'] as $field) { $state = \json_decode($this->buildGiteaState($projectId, $consoleUrl, $consoleUrl), true); @@ -862,7 +855,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithReplayedSignature(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = 'http://localhost/console/project-default-' . $projectId . '/settings/git-installations'; + $consoleUrl = 'http://localhost/projects/' . $projectId . '/settings'; $state = \json_decode($this->buildGiteaState($projectId, $consoleUrl, $consoleUrl), true); $state['signature'] = \json_decode($this->buildGiteaState('victim-project', $consoleUrl, $consoleUrl), true)['signature']; @@ -875,7 +868,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithNonStringSignature(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = 'http://localhost/console/project-default-' . $projectId . '/settings/git-installations'; + $consoleUrl = 'http://localhost/projects/' . $projectId . '/settings'; $state = \json_decode($this->buildGiteaState($projectId, $consoleUrl, $consoleUrl), true); $state['signature'] = 1234; @@ -890,7 +883,7 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateInstallationWithOversizedRedirects(): void { $projectId = $this->getProject()['$id']; - $consoleUrl = 'http://localhost/console/project-default-' . $projectId . '/settings/git-installations'; + $consoleUrl = 'http://localhost/projects/' . $projectId . '/settings'; // Authorize must refuse rather than mint a state its own callback would reject. $authorize = $this->client->call(Client::METHOD_GET, '/vcs/gitea/authorize', \array_merge([ diff --git a/tests/unit/Platform/Workers/NotificationsTest.php b/tests/unit/Platform/Workers/NotificationsTest.php index dc04a34bcd..93be857969 100644 --- a/tests/unit/Platform/Workers/NotificationsTest.php +++ b/tests/unit/Platform/Workers/NotificationsTest.php @@ -45,6 +45,7 @@ final class SpyNotifications extends Notifications Document $project, Registry $register, Database $dbForPlatform, + array $platform, ): ?string { $channel = $recipient['channel']; $this->dispatched[] = [ @@ -157,6 +158,7 @@ final class NotificationsTest extends TestCase private Authorization $authorization; private Registry $registry; private Document $project; + private array $platform = ['consoleUrl' => 'https://console.example.test']; private Span $span; protected function setUp(): void @@ -291,7 +293,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'event-1', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertCount(3, $worker->dispatched); $channels = \array_map(static fn ($d) => $d['channel'], $worker->dispatched); @@ -313,7 +315,7 @@ final class NotificationsTest extends TestCase 'permissions' => [Permission::read(Role::any())], ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $rows = $this->database->find('notifications'); $this->assertCount(2, $rows); @@ -345,11 +347,11 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'dup-key', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertCount(1, $worker->dispatched); $worker->dispatched = []; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertCount(0, $worker->dispatched, 'second invocation must short-circuit on dedup hit'); } @@ -363,7 +365,8 @@ final class NotificationsTest extends TestCase $this->buildMessage(['project' => ['$id' => 'project-x'], 'subject' => '', 'body' => '']), $this->project, $this->registry, - $this->database + $this->database, + $this->platform ); } @@ -377,7 +380,7 @@ final class NotificationsTest extends TestCase 'body' => 'Y', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertCount(1, $worker->dispatched); $this->assertSame('legacy@example.test', $worker->dispatched[0]['address']); @@ -409,7 +412,7 @@ final class NotificationsTest extends TestCase ], ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } finally { \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); } @@ -443,7 +446,7 @@ final class NotificationsTest extends TestCase $this->expectException(\Exception::class); $this->expectExceptionMessage('Skipped mail processing. No SMTP configuration has been set.'); - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } finally { \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); } @@ -469,7 +472,7 @@ final class NotificationsTest extends TestCase 'body' => 'b', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertCount(2, $worker->dispatched); $this->assertSame('tenant-secret', $worker->dispatched[0]['signatureKey']); @@ -490,7 +493,7 @@ final class NotificationsTest extends TestCase ]; try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->fail('expected exception to propagate'); } catch (\Throwable $error) { $this->assertSame('boom', $error->getMessage()); @@ -521,7 +524,7 @@ final class NotificationsTest extends TestCase ]; try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->fail('expected webhook failure to propagate'); } catch (\RuntimeException $error) { $this->assertSame('webhook down', $error->getMessage()); @@ -534,7 +537,7 @@ final class NotificationsTest extends TestCase $this->assertSame(NOTIFICATION_TYPE_CONSOLE, $rows[0]->getAttribute('channel')); $retry = new SpyNotifications(); - $retry->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $retry->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertCount(1, $retry->dispatched, 'retry should dispatch only the previously undelivered webhook'); $this->assertSame(NOTIFICATION_TYPE_WEBHOOK, $retry->dispatched[0]['channel']); @@ -559,7 +562,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'console-skip', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); // The Console adapter wrote exactly one alert; the action loop // must NOT have called persistAlert (otherwise we'd see 2 rows or @@ -586,7 +589,7 @@ final class NotificationsTest extends TestCase ]; try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->fail('expected console zero-delivery to throw'); } catch (\Throwable $error) { $this->assertStringContainsString('Console alert delivery failed', $error->getMessage()); @@ -610,7 +613,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'fanout', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $rows = $this->database->find('notifications'); $this->assertCount(2, $rows, 'two recipients must produce two distinct alert rows'); @@ -647,7 +650,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'roundtrip', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $rows = $this->database->find('notifications'); $this->assertCount(1, $rows); @@ -688,7 +691,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'logo-key', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } finally { \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); \putenv($previousTrackingSecret === false ? '_APP_NOTIFICATIONS_TRACKING_SECRET' : '_APP_NOTIFICATIONS_TRACKING_SECRET=' . $previousTrackingSecret); @@ -760,7 +763,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'logo-key-no-tracking-secret', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } finally { \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); \putenv($previousTrackingSecret === false ? '_APP_NOTIFICATIONS_TRACKING_SECRET' : '_APP_NOTIFICATIONS_TRACKING_SECRET=' . $previousTrackingSecret); @@ -792,7 +795,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'persist-email', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } finally { \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); } @@ -845,7 +848,7 @@ final class NotificationsTest extends TestCase $threw = false; try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } catch (\Throwable $error) { $threw = true; $this->assertStringContainsString('SMTP unavailable', $error->getMessage()); @@ -866,7 +869,7 @@ final class NotificationsTest extends TestCase $this->registry->set('smtp', static fn () => $working); $retryWorker = new Notifications(); - $retryWorker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $retryWorker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertSame(1, $working->sendCount, 'retry must invoke the working adapter'); @@ -908,7 +911,7 @@ final class NotificationsTest extends TestCase $threw = false; try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } catch (\Throwable $error) { $threw = true; $this->assertStringContainsString('SMTP unavailable', $error->getMessage()); @@ -933,7 +936,7 @@ final class NotificationsTest extends TestCase $this->registry->set('smtp', static fn () => $working); $retryWorker = new Notifications(); - $retryWorker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $retryWorker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertSame(1, $working->sendCount, 'retry must still deliver the email recipient'); $rows = $this->database->find('notifications', [ @@ -976,7 +979,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'happy-email', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } finally { \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); \putenv($previousTrackingSecret === false ? '_APP_NOTIFICATIONS_TRACKING_SECRET' : '_APP_NOTIFICATIONS_TRACKING_SECRET=' . $previousTrackingSecret); @@ -1045,7 +1048,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'happy-console', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $rows = $this->database->find('notifications', [ Query::equal('channel', ['console']), @@ -1088,7 +1091,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'console-preview', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $rows = $this->database->find('notifications'); $this->assertCount(1, $rows); @@ -1116,7 +1119,7 @@ final class NotificationsTest extends TestCase ]; try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } catch (\Exception $error) { $this->assertStringContainsString('No SMTP configuration has been set', $error->getMessage()); $threw = true; @@ -1148,7 +1151,7 @@ final class NotificationsTest extends TestCase $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid console alert resourceId'); - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); } /** @@ -1220,7 +1223,7 @@ final class NotificationsTest extends TestCase 'deduplicationKey' => 'happy-webhook', ]; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database); + $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->platform); $this->assertCount(1, $worker->captured, 'adapter must POST exactly once'); $request = $worker->captured[0]; diff --git a/tests/unit/Platform/Workers/WebhooksTest.php b/tests/unit/Platform/Workers/WebhooksTest.php index e846531633..47e898d9af 100644 --- a/tests/unit/Platform/Workers/WebhooksTest.php +++ b/tests/unit/Platform/Workers/WebhooksTest.php @@ -31,7 +31,7 @@ final class WebhooksTest extends TestCase $publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications')); $worker = new Webhooks(); - $this->withConsoleUrlScheme('legacy', fn () => $worker->sendAlert( + $worker->sendAlert( attempts: 10, statusCode: 500, webhook: new Document([ @@ -49,8 +49,9 @@ final class WebhooksTest extends TestCase ]), dbForPlatform: $database, publisherForNotifications: $publisherForNotifications, + platform: ['consoleUrl' => 'https://console.example.test'], plan: [] - )); + ); $events = $publisher->getEvents('v1-notifications'); @@ -68,7 +69,7 @@ final class WebhooksTest extends TestCase ); $this->assertStringContainsString('Payments', (string) $payload['body']); $this->assertStringContainsString('Ada Lovelace', (string) $payload['body']); - $this->assertStringContainsString('/console/project-fra-project-1/settings/webhooks/webhook-1', (string) $payload['body']); + $this->assertStringContainsString('https://console.example.test/projects/project-1/settings/webhooks', (string) $payload['body']); $this->assertStringNotContainsString('{{', (string) $payload['body']); $this->assertSame(APP_NAME, $payload['variables']['platform']); $this->assertSame(APP_EMAIL_LOGO_URL, $payload['variables']['logoUrl']); @@ -95,43 +96,6 @@ final class WebhooksTest extends TestCase ], $payload['recipients'][1]); } - public function testSendAlertUsesRootConsolePathsWhenConfigured(): void - { - $database = $this->createPlatformDatabase(); - $this->seedOwnerUser($database); - - $publisher = new MockPublisher(); - $publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications')); - $worker = new Webhooks(); - - $this->withConsoleUrlScheme('root', fn () => $worker->sendAlert( - attempts: 10, - statusCode: 500, - webhook: new Document([ - '$id' => 'webhook-1', - '$updatedAt' => '2026-01-01T00:00:00.000+00:00', - 'name' => 'Payments', - 'url' => 'https://example.test/webhook', - ]), - project: new Document([ - '$id' => 'project-1', - '$sequence' => 'project-internal-1', - 'name' => 'Production', - 'teamInternalId' => 'team-internal-1', - 'region' => 'fra', - ]), - dbForPlatform: $database, - publisherForNotifications: $publisherForNotifications, - plan: [] - )); - - $events = $publisher->getEvents('v1-notifications'); - - $this->assertCount(1, $events); - $this->assertStringContainsString('/projects/project-1/settings/webhooks', (string) $events[0]['body']); - $this->assertStringNotContainsString('/console/', (string) $events[0]['body']); - } - public function testSendAlertPersonalizesBodyPerOwner(): void { $database = $this->createPlatformDatabase(); @@ -171,6 +135,7 @@ final class WebhooksTest extends TestCase ]), dbForPlatform: $database, publisherForNotifications: $publisherForNotifications, + platform: ['consoleUrl' => 'https://console.example.test'], plan: [] ); @@ -223,6 +188,7 @@ final class WebhooksTest extends TestCase project: $project, dbForPlatform: $database, publisherForNotifications: $publisherForNotifications, + platform: ['consoleUrl' => 'https://console.example.test'], plan: [] ); } @@ -234,18 +200,6 @@ final class WebhooksTest extends TestCase $this->assertSame('webhook:webhook-1:paused:2026-01-02T00:00:00.000+00:00', $events[1]['deduplicationKey']); } - private function withConsoleUrlScheme(string $scheme, callable $callback): void - { - $original = \getenv('_APP_CONSOLE_URL_SCHEME'); - \putenv("_APP_CONSOLE_URL_SCHEME={$scheme}"); - - try { - $callback(); - } finally { - \putenv($original === false ? '_APP_CONSOLE_URL_SCHEME' : "_APP_CONSOLE_URL_SCHEME={$original}"); - } - } - private function createPlatformDatabase(): Database { $authorization = new Authorization();