Merge remote-tracking branch 'origin/main' into chore/remove-dev-keys

# Conflicts:
#	app/controllers/api/account.php
This commit is contained in:
harsh mahajan committed 2026-09-15 18:23:48 +05:30
commit d1e3a78efc
40 files changed
+674 -627

No files matched your search

+1
View File
@@ -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
+3 -1
View File
@@ -15,7 +15,9 @@ on:
push:
branches:
- main
- 1.9.x
# Every release branch, so the nightly channel always has green commits to
# resolve on the active line without anyone remembering to add it here.
- '*.x'
workflow_dispatch:
inputs:
response_format:
+79 -41
View File
@@ -1,51 +1,89 @@
name: Nightly Security Scan
name: "Nightly"
# One build a day of the active release branch, for self-hosters who want to
# track it. Unsupported, and never publishes to appwrite/ce -- Cloud builds from
# cl-* tags through publish.yml.
#
# Tags on appwrite/appwrite: X.Y-nightly.<date> to pin or roll back to,
# X.Y-nightly to follow the line, nightly to follow whatever line is active.
on:
schedule:
- cron: '0 0 * * *' # 12am UTC daily runtime
- cron: '0 0 * * *' # 12am UTC daily
workflow_dispatch:
jobs:
scan-image:
name: Scan Docker Image
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
submodules: recursive
- name: Build the Docker image
run: DOCKER_BUILDKIT=1 docker build . --target production -t appwrite_image:latest
- name: Run Trivy vulnerability scanner on image
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: 'appwrite_image:latest'
format: 'sarif'
output: 'trivy-image-results.sarif'
ignore-unfixed: 'false'
severity: 'CRITICAL,HIGH'
- name: Upload Docker Image Scan Results
uses: github/codeql-action/upload-sarif@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
if: always() && hashFiles('trivy-image-results.sarif') != ''
with:
sarif_file: 'trivy-image-results.sarif'
category: 'trivy-image'
concurrency:
group: nightly
cancel-in-progress: false
scan-code:
name: Scan Code
permissions:
contents: read
jobs:
nightly:
name: Build and publish
runs-on: ubuntu-latest
timeout-minutes: 120
steps:
- name: Check out code
- name: Resolve the build
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
REMOTE: ${{ github.server_url }}/${{ github.repository }}
run: |
set -euo pipefail
branch=$(git ls-remote --heads "$REMOTE" \
| sed -n 's#.*refs/heads/##p' \
| grep -E '^[0-9]+\.[0-9]+\.x$' \
| sort -V \
| tail -1)
[ -n "$branch" ] || { echo '::error::No X.Y.x release branch on origin.'; exit 1; }
# The newest CI-green commit rather than the tip, so a red branch
# delays the channel instead of shipping through it.
sha=$(gh run list --workflow=ci.yml --branch="$branch" --event=push \
--status=success --limit=1 --json headSha --jq '.[0].headSha // empty')
[ -n "$sha" ] || { echo "::error::No green CI run on ${branch}."; exit 1; }
line="${branch%.x}"
version="${line}-nightly.$(date -u +%Y%m%d)"
{
echo "SHA=${sha}"
echo "VERSION=${version}"
echo "TAGS=appwrite/appwrite:${version},appwrite/appwrite:${line}-nightly,appwrite/appwrite:nightly"
} >> "$GITHUB_ENV"
echo "Publishing ${version} from ${branch} (${sha})." >> "$GITHUB_STEP_SUMMARY"
- name: Check out the resolved commit
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Run Trivy vulnerability scanner on filesystem
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
scan-type: 'fs'
format: 'sarif'
output: 'trivy-fs-results.sarif'
severity: 'CRITICAL,HIGH'
- name: Upload Code Scan Results
uses: github/codeql-action/upload-sarif@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
if: always() && hashFiles('trivy-fs-results.sarif') != ''
ref: ${{ env.SHA }}
submodules: recursive
- name: Set up QEMU
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
- name: Login to Docker Hub
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
sarif_file: 'trivy-fs-results.sarif'
category: 'trivy-source'
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0
with:
context: .
platforms: linux/amd64,linux/arm64
target: production
build-args: VERSION=${{ env.VERSION }}
push: true
tags: ${{ env.TAGS }}
labels: org.opencontainers.image.revision=${{ env.SHA }}
+51
View File
@@ -0,0 +1,51 @@
name: Security Scan
on:
schedule:
- cron: '30 1 * * *' # 1:30am UTC, after the nightly build has taken 00:00
workflow_dispatch:
jobs:
scan-image:
name: Scan Docker Image
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
submodules: recursive
- name: Build the Docker image
run: DOCKER_BUILDKIT=1 docker build . --target production -t appwrite_image:latest
- name: Run Trivy vulnerability scanner on image
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: 'appwrite_image:latest'
format: 'sarif'
output: 'trivy-image-results.sarif'
ignore-unfixed: 'false'
severity: 'CRITICAL,HIGH'
- name: Upload Docker Image Scan Results
uses: github/codeql-action/upload-sarif@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
if: always() && hashFiles('trivy-image-results.sarif') != ''
with:
sarif_file: 'trivy-image-results.sarif'
category: 'trivy-image'
scan-code:
name: Scan Code
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Run Trivy vulnerability scanner on filesystem
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
scan-type: 'fs'
format: 'sarif'
output: 'trivy-fs-results.sarif'
severity: 'CRITICAL,HIGH'
- name: Upload Code Scan Results
uses: github/codeql-action/upload-sarif@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
if: always() && hashFiles('trivy-fs-results.sarif') != ''
with:
sarif_file: 'trivy-fs-results.sarif'
category: 'trivy-source'
+34 -1
View File
@@ -299,6 +299,39 @@ Preview builds set the flag on **both** the `specs` and `sdks` steps in `.github
## Releases
Self-hosted ships on two channels. Cloud is separate: it builds from `cl-*` tags to `appwrite/ce` via [`publish.yml`](.github/workflows/publish.yml) and nothing below applies to it.
| Channel | Source | Trigger | Tags on `appwrite/appwrite` |
|---------|--------|---------|------------------------------|
| stable | active release branch (`2.0.x`) | GitHub Release, published by a human | `X.Y.Z` (immutable), `X.Y`, `X`, `latest` |
| nightly | newest CI-green commit on that branch | daily at 00:00 UTC, or `workflow_dispatch` | `X.Y-nightly.<date>` (one a day), `X.Y-nightly`, `nightly` |
[`nightly.yml`](.github/workflows/nightly.yml) builds the channel; [`security-scan.yml`](.github/workflows/security-scan.yml) is the Trivy scan that used to own that file name. `X.Y` comes from the branch name and `<date>` is `YYYYMMDD`, so `2.0.x` publishes `2.0-nightly.20260915`. The tag is a label, not a version the product reads: `migrate` keys off `APP_VERSION_STABLE` compiled into the image, and the `VERSION` build arg only sets `_APP_VERSION`. The branch is rebuilt daily whether or not it moved, so the channel carries base image security fixes. Only the newest release branch is built, so an `X.Y-nightly` tag stops moving once a newer line opens.
Four rules keep the channel safe. They are requirements, not preferences:
1. **A patch never adds a migration.** Map a new patch to the previous version's class in `Migration::$versions`. A fix that needs a schema change is a minor. This is what lets a nightly user roll back to yesterday's build, and `1.9.6` (which introduced V25) is the exception not to repeat.
2. **Nightly publishes only a CI-green commit** rather than the tip, so a red branch delays the channel instead of breaking it.
3. **The release branch stays releasable.** Backports land as complete cherry-picks, behind a flag when the fix is not finished.
4. **Nightly publishes to `appwrite/appwrite` only.** It must never be able to push to `appwrite/ce`.
Self-hosters opt in through `_APP_VERSION`, which every service in `docker-compose.yml` already resolves (`${_APP_IMAGE:-appwrite/appwrite}:${_APP_VERSION:-latest}`), or with `--channel` on [`install`](src/Appwrite/Platform/Tasks/Install.php) and [`upgrade`](src/Appwrite/Platform/Tasks/Upgrade.php):
```
_APP_VERSION=2.0-nightly # then: docker compose pull && docker compose up -d && docker compose exec appwrite migrate
```
Nightly is unsupported, has no SLA, and only ever moves within one patch line. `X.Y-nightly` is the form to recommend; the bare `nightly` tag follows the newest line and will jump minors.
### Patch train
Patches leave on a schedule so that "is this worth a release?" stops being a per-fix decision:
- **Weekly**, on the active release branch, if at least one user-visible fix landed since the last tag. Nothing landed, no release — silently.
- **Security and data-loss fixes ship out of band**, same day.
- **Backports are labelled, not remembered.** Fixes land on `main`; a `backport X.Y.x` label opens the cherry-pick PR.
- **A console publish is a release trigger.** The console is pinned (`appwrite/new:X.Y.Z`) in `docker-compose.yml`, so a console-only fix reaches self-hosters only through an `appwrite/appwrite` patch. Bump the pin, let CI pass, and let it ride the next train.
### Patch version
When bumping a patch (e.g. `1.9.0` → `1.9.1`):
@@ -320,6 +353,6 @@ A release is not ready until a **fresh install** and an **upgrade from the previ
**Upgrade:** install the previous stable image, seed broad data (empty values, long strings, relationships, mixed permissions), keep volumes, switch to the target image, run migrate. Migration must complete, be idempotent, and preserve seeded data through public API reads/writes.
**Metadata:** `APP_VERSION_STABLE`; Appwrite and console tags in `docker-compose.yml` and [`app/views/install/compose.phtml`](app/views/install/compose.phtml); README install snippets; `Migration.php` `$versions`; [changelog](https://appwrite.io/changelog). For public API breaks: request filters in `src/Appwrite/Utopia/Request/Filters/V*.php`, response filters in `src/Appwrite/Utopia/Response/Filters/V*.php`, registered in [`app/controllers/general.php`](app/controllers/general.php) for `x-appwrite-response-format`. Unit-test filters under `tests/unit/Utopia/{Request,Response}/Filters`; add e2e with that header when routing, auth, or persistence is involved.
**Metadata:** `APP_VERSION_STABLE`; Appwrite and console tags in `docker-compose.yml`; README install snippets; `Migration.php` `$versions`; [changelog](https://appwrite.io/changelog). For public API breaks: request filters in `src/Appwrite/Utopia/Request/Filters/V*.php`, response filters in `src/Appwrite/Utopia/Response/Filters/V*.php`, registered in [`app/controllers/general.php`](app/controllers/general.php) for `x-appwrite-response-format`. Unit-test filters under `tests/unit/Utopia/{Request,Response}/Filters`; add e2e with that header when routing, auth, or persistence is involved.
Do not approve an RC/final until both gates pass, metadata matches the target, and unintended public breaks have filters (or the owner documents the break on the changelog).
-271
View File
@@ -2012,277 +2012,6 @@ return [
],
],
'executions' => [
'$collection' => ID::custom(Database::METADATA),
'$id' => ID::custom('executions'),
'name' => 'Executions',
'attributes' => [
[
'$id' => ID::custom('resourceInternalId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('resourceId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('resourceType'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('deploymentInternalId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('deploymentId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'array' => false,
'$id' => ID::custom('trigger'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 128,
'signed' => true,
'required' => false,
'default' => null,
'filters' => [],
],
[
'$id' => ID::custom('status'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 128,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('duration'),
'type' => Database::VAR_FLOAT,
'format' => '',
'size' => 0,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('errors'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => APP_FUNCTION_ERROR_LENGTH_LIMIT,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('logs'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => APP_FUNCTION_LOG_LENGTH_LIMIT,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'array' => false,
'$id' => ID::custom('requestMethod'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 128,
'signed' => true,
'required' => false,
'default' => null,
'filters' => [],
],
[
'array' => false,
'$id' => ID::custom('requestPath'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 2048,
'signed' => true,
'required' => false,
'default' => null,
'filters' => [],
],
[
'$id' => ID::custom('requestHeaders'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 16384,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => ['json'],
],
[
'$id' => ID::custom('responseStatusCode'),
'type' => Database::VAR_INTEGER,
'format' => '',
'size' => 0,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('responseHeaders'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 16384,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => ['json'],
],
[
'$id' => ID::custom('scheduledAt'),
'type' => Database::VAR_DATETIME,
'format' => '',
'size' => 0,
'signed' => false,
'required' => false,
'default' => null,
'array' => false,
'filters' => ['datetime'],
],
[
'$id' => ID::custom('scheduleInternalId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('scheduleId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
],
'indexes' => [
[
'$id' => ID::custom('_key_resource'),
'type' => Database::INDEX_KEY,
'attributes' => ['resourceInternalId', 'resourceType', 'resourceId'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_trigger'),
'type' => Database::INDEX_KEY,
'attributes' => ['trigger'],
'lengths' => [32],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_status'),
'type' => Database::INDEX_KEY,
'attributes' => ['status'],
'lengths' => [32],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_requestMethod'),
'type' => Database::INDEX_KEY,
'attributes' => ['requestMethod'],
'lengths' => [128],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_requestPath'),
'type' => Database::INDEX_KEY,
'attributes' => ['requestPath'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_deployment'),
'type' => Database::INDEX_KEY,
'attributes' => ['deploymentId'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_responseStatusCode'),
'type' => Database::INDEX_KEY,
'attributes' => ['responseStatusCode'],
'lengths' => [],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_duration'),
'type' => Database::INDEX_KEY,
'attributes' => ['duration'],
'lengths' => [],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_resourceType'),
'type' => Database::INDEX_KEY,
'attributes' => ['resourceType'],
'lengths' => [],
'orders' => [Database::ORDER_ASC],
],
],
],
'variables' => [
'$collection' => Database::METADATA,
'$id' => 'variables',
+3
View File
@@ -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'),
+5 -5
View File
@@ -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' => ''
@@ -1866,7 +1866,7 @@ return [
],
[
'name' => '_APP_STATS_RESOURCES_INTERVAL',
'description' => 'Interval in seconds between full resource-count snapshots.',
'description' => 'Interval in seconds between resource-count snapshots. Each active project is counted once per interval, at a slot spread across it.',
'introduction' => '',
'default' => '3600',
'required' => false,
+21 -27
View File
@@ -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;
}
@@ -1511,7 +1507,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, 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, 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();
@@ -1579,12 +1576,15 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
if (!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']);
@@ -1595,7 +1595,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);
@@ -2178,7 +2178,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();
@@ -2284,13 +2284,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;
}
@@ -2357,7 +2355,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');
}
@@ -2495,17 +2493,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);
+11 -24
View File
@@ -99,8 +99,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()) {
@@ -127,7 +126,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;
}
}
@@ -206,11 +205,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;
}
@@ -295,11 +290,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,
@@ -356,14 +350,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':
@@ -372,7 +363,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);
@@ -387,11 +378,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;
}
}
+6
View File
@@ -249,6 +249,12 @@ return function (Container $context): void {
$context->set('allowedHostnames', function (array $platform, Document $project, Document $rule, 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', []);
+11 -4
View File
@@ -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
+1 -6
View File
@@ -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);
@@ -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);
}
@@ -1,18 +0,0 @@
<?php
namespace Appwrite\Platform\Modules\Console\Http\Redirects\Card;
use Appwrite\Platform\Modules\Console\Http\Redirects\Base;
class Get extends Base
{
public static function getName(): string
{
return 'consoleRedirectCard';
}
protected function getPath(): string
{
return '/card/*';
}
}
@@ -15,4 +15,9 @@ class Get extends Base
{
return '/invite';
}
protected function getTarget(string $path, array $params): string
{
return '/join';
}
}
@@ -15,4 +15,9 @@ class Get extends Base
{
return '/login';
}
protected function getTarget(string $path, array $params): string
{
return '/sign-in';
}
}
@@ -15,4 +15,14 @@ class Get extends Base
{
return '/recover';
}
protected function getTarget(string $path, array $params): string
{
// The reset page requires the emailed userId and secret, without them only the request form is usable
if (empty($params['userId']) || empty($params['secret'])) {
return '/recovery';
}
return '/reset';
}
}
@@ -15,4 +15,9 @@ class Get extends Base
{
return '/register/*';
}
protected function getTarget(string $path, array $params): string
{
return '/sign-up';
}
}
@@ -7,7 +7,6 @@ use Appwrite\Platform\Modules\Console\Http\Init\API;
use Appwrite\Platform\Modules\Console\Http\Init\Web;
use Appwrite\Platform\Modules\Console\Http\OAuth2Providers\XList as ListOAuth2Providers;
use Appwrite\Platform\Modules\Console\Http\Redirects\Auth\Get as RedirectAuth;
use Appwrite\Platform\Modules\Console\Http\Redirects\Card\Get as RedirectCard;
use Appwrite\Platform\Modules\Console\Http\Redirects\Invite\Get as RedirectInvite;
use Appwrite\Platform\Modules\Console\Http\Redirects\Login\Get as RedirectLogin;
use Appwrite\Platform\Modules\Console\Http\Redirects\MFA\Get as RedirectMFA;
@@ -39,13 +38,12 @@ class Http extends Service
$this->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());
}
@@ -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'];
@@ -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'];
@@ -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);
}
@@ -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));
+56 -2
View File
@@ -36,6 +36,9 @@ class Install extends Action
private const string PATTERN_DB_PASSWORD_VAR = '/^_APP_DB_.*_PASS$/';
private const string PATTERN_SESSION_COOKIE = '/a_session_console=([^;]+)/';
public const string CHANNEL_STABLE = 'stable';
public const string CHANNEL_NIGHTLY = 'nightly';
private const string APPWRITE_API_URL = 'http://appwrite';
private const string GROWTH_API_URL = 'https://growth.appwrite.io/v1';
@@ -46,6 +49,7 @@ class Install extends Action
protected ?array $installerConfig = null;
protected string $path = '/usr/src/code/appwrite';
protected string $topology = 'combined';
protected string $channel = self::CHANNEL_STABLE;
public static function getName(): string
{
@@ -64,6 +68,7 @@ class Install extends Action
->param('no-start', false, new Boolean(true), 'Run an interactive session', true)
->param('database', 'postgresql', new WhiteList(['postgresql', 'mariadb', 'mongodb']), 'Database to use (postgresql|mariadb|mongodb)', true)
->param('topology', 'combined', new WhiteList(['combined', 'separate']), 'Worker and scheduler topology (combined|separate)', true)
->param('channel', self::CHANNEL_STABLE, new WhiteList([self::CHANNEL_STABLE, self::CHANNEL_NIGHTLY]), 'Release channel to track (stable|nightly). Nightly is unsupported and moves daily.', true)
->callback($this->action(...));
}
@@ -75,8 +80,10 @@ class Install extends Action
string $interactive,
bool $noStart,
string $database,
string $topology
string $topology,
string $channel = self::CHANNEL_STABLE
): void {
$this->channel = $channel;
$isUpgrade = $this->isUpgrade;
$defaultHttpPort = '80';
$defaultHttpsPort = '443';
@@ -561,7 +568,25 @@ class Install extends Action
$database = $input['_APP_DB_ADAPTER'] ?? 'postgresql';
$version = \getenv('_APP_VERSION') ?: (\defined('APP_VERSION_STABLE') ? APP_VERSION_STABLE : 'latest');
$stableVersion = \defined('APP_VERSION_STABLE') ? APP_VERSION_STABLE : 'latest';
$version = \getenv('_APP_VERSION') ?: $stableVersion;
// A nightly image reports the tag it was pulled under -- 2.0-nightly.<date> --
// which names a channel rather than a release, and so cannot be carried forward:
// there is no X.Y to re-derive a nightly tag from, and writing it back would keep
// an install asking for the stable channel on nightly. The release the image was
// built from is compiled in, and both channels take their tag from it.
if ($this->isNightlyTag($version)) {
$version = $stableVersion;
}
// The nightly channel tracks the minor line rather than one release, so the
// tag has to stay rolling -- pinning X.Y.Z would freeze the install on a
// single build. See the Releases section of AGENTS.md.
if ($this->channel === self::CHANNEL_NIGHTLY) {
$version = $this->nightlyTag($version);
}
if ($isLocalInstall) {
$version = 'local';
}
@@ -823,6 +848,35 @@ class Install extends Action
}
}
/**
* The tags nightly.yml publishes: `nightly`, `X.Y-nightly` and
* `X.Y-nightly.<date>`. A self-hoster's own tag that happens to mention the
* word is theirs, not this channel's, and is carried forward untouched.
*/
private function isNightlyTag(string $version): bool
{
return $version === 'nightly'
|| \str_ends_with($version, '-nightly')
|| \str_contains($version, '-nightly.');
}
/**
* The rolling nightly tag for the minor line a stable version belongs to,
* e.g. 2.0.1 -> 2.0-nightly.
*/
private function nightlyTag(string $version): string
{
[$major, $minor] = \array_pad(\explode('.', $version), 2, '');
if (!\ctype_digit($major) || !\ctype_digit($minor)) {
Console::warning("Cannot derive a nightly tag from '{$version}'; using the bare nightly tag.");
return 'nightly';
}
return "{$major}.{$minor}-nightly";
}
private function createInitialAdminAccount(array $account, ?callable $progress, string $apiUrl, string $domain): void
{
$name = $account['name'] ?? 'Admin';
+1 -1
View File
@@ -95,7 +95,7 @@ class Schedule extends Action
$this->loop(fn () => (new ScheduleMessages())->action($publisherForMessaging, $getIsResourceBlocked, $dbForPlatform, $getProjectDB, $telemetry, $locks));
if ($publisherForStatsResources !== null && $usageConnection !== null) {
$this->loop(fn () => (new StatsResources())->action($dbForPlatform, $publisherForStatsResources, $usageConnection));
$this->loop(fn () => (new StatsResources())->action($dbForPlatform, $publisherForStatsResources, $usageConnection, $telemetry));
}
while (true) {
+74 -55
View File
@@ -4,15 +4,17 @@ namespace Appwrite\Platform\Tasks;
use Appwrite\Event\Message\StatsResources as StatsResourcesMessage;
use Appwrite\Event\Publisher\StatsResources as StatsResourcesPublisher;
use Appwrite\Platform\Action;
use Appwrite\Schedule\Source;
use Appwrite\Usage\Concurrency;
use Appwrite\Usage\Connection;
use Utopia\Console;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Query;
use Utopia\Platform\Action;
use Utopia\Schedule\Occurrence;
use Utopia\Schedule\Scheduler;
use Utopia\Span\Span;
use Utopia\System\System;
use Utopia\Telemetry\Adapter as Telemetry;
class StatsResources extends Action
{
@@ -32,77 +34,94 @@ class StatsResources extends Action
->inject('dbForPlatform')
->inject('publisherForStatsResources')
->inject('usageConnection')
->inject('telemetry')
->callback($this->action(...));
}
public function action(Database $dbForPlatform, StatsResourcesPublisher $publisherForStatsResources, Connection $usageConnection): void
public function action(Database $dbForPlatform, StatsResourcesPublisher $publisherForStatsResources, Connection $usageConnection, Telemetry $telemetry): void
{
if (!$usageConnection->isEnabled()) {
Console::info('Usage statistics are disabled');
return;
}
$this->disableSubqueries();
// Floor of 1 guards against a zero/negative interval spinning the loop;
// test stacks legitimately run short intervals (Cloud CI uses 2s).
// Floor of 1 guards against a zero/negative interval; test stacks
// legitimately run short intervals (Cloud CI uses 2s).
$interval = max(1, (int) System::getEnv('_APP_STATS_RESOURCES_INTERVAL', 3600));
Console::loop(function () use ($dbForPlatform, $publisherForStatsResources, $usageConnection): void {
Span::init('stats_resources_task');
$projectsQueued = 0;
$projectsFailed = 0;
$source = new Source\Stats($dbForPlatform, $interval, $this->subqueries());
$scheduler = new Scheduler(
source: $source,
syncSeconds: min($interval, 60),
snapshotSeconds: $interval,
telemetry: $telemetry,
onError: function (\Throwable $error): void {
Span::init('schedule.stats.reconcile');
Span::current()?->finish(error: $error);
},
);
$scheduler->run(fn (array $occurrences): null => $this->dispatch($occurrences, $publisherForStatsResources, $usageConnection));
Span::init('schedule.stats.stopped');
Span::current()?->finish(error: new \RuntimeException('Scheduler loop returned'));
}
/**
* Project decode filters the listing skips. Editions that register more
* subqueries on projects extend this.
*
* @return list<string>
*/
protected function subqueries(): array
{
return APP_PROJECTS_SUBQUERIES;
}
/**
* Nothing here may throw: an exception ends the scheduler loop, and the
* process then stays alive and idle with nothing observing that
* scheduling has stopped. A failure costs one occurrence, not the loop.
*
* @param list<Occurrence> $occurrences
*/
private function dispatch(array $occurrences, StatsResourcesPublisher $publisherForStatsResources, Connection $usageConnection): null
{
if (!$usageConnection->isReady()) {
Console::error('stats resources: usage schema is not ready, skipping ' . \count($occurrences) . ' occurrences');
return null;
}
$batch = \count($occurrences);
foreach (\array_values($occurrences) as $index => $occurrence) {
Span::init('schedule.stats.enqueue');
$error = null;
// Nothing here may end the loop. An exception escaping this closure
// ends Console::loop, and the process then stays alive and idle: it
// never exits, so restartPolicy never fires, and with no liveness
// probe nothing observes that scheduling has stopped. A single
// transient ClickHouse timeout on one tick silently ended gauge
// collection for a whole region, and the task went on reporting
// Ready for weeks while queueing nothing.
try {
if (!$usageConnection->isReady()) {
Span::add('stats_resources_task.skipped', 'usage_schema_not_ready');
Console::error('stats resources: usage schema is not ready, skipping cycle');
return;
}
Span::add('occurrence.due', $occurrence->due->format('c'));
Span::add('occurrence.late', \round(\microtime(true) - (float) $occurrence->due->format('U.u'), 3));
Span::add('occurrence.batch', $batch);
Span::add('occurrence.index', $index);
// Concurrency sampling reads the usage store; project scheduling
// reads the platform DB. They share no data, so a failure in the
// first must not cost the second -- that coupling is what turned
// one bad read into no scheduling at all.
try {
if ($occurrence->id === Source\Stats::CONCURRENCY) {
$this->concurrency->sample($usageConnection->getUsage());
} catch (\Throwable $th) {
Console::error('stats resources: concurrency sample failed, continuing: ' . $th->getMessage());
continue;
}
$last24Hours = (new \DateTime())->sub(new \DateInterval('P1D'));
$this->foreachDocument($dbForPlatform, 'projects', [
Query::greaterThanEqual('accessedAt', DateTime::format($last24Hours)),
Query::equal('region', [System::getEnv('_APP_REGION', 'default')]),
Query::orderAsc('$sequence'), // accessedAt Can be updated during iteration
], function ($project) use ($publisherForStatsResources, &$projectsQueued, &$projectsFailed): void {
// enqueue() swallows a publish failure, reporting it only to
// Console and returning false — as it does when stats are off.
if ($publisherForStatsResources->enqueue(new StatsResourcesMessage(project: $project)) === false) {
$projectsFailed++;
return;
}
$projectsQueued++;
});
Span::add('project.id', $occurrence->id);
if ($publisherForStatsResources->enqueue(new StatsResourcesMessage(project: $occurrence->payload)) === false) {
$error = new \RuntimeException('Failed to enqueue');
}
} catch (\Throwable $th) {
// Cost a cycle, not the process: the next tick retries in full.
Span::add('stats_resources_task.error', $th->getMessage());
Console::error('stats resources: cycle failed, retrying next interval: ' . $th->getMessage());
$error = $th;
Console::error('stats resources: ' . $occurrence->id . ' failed: ' . $th->getMessage());
} finally {
// An unfinished span exports nothing, including the early return.
Span::add('stats_resources_task.projects_queued', $projectsQueued);
Span::add('stats_resources_task.projects_failed', $projectsFailed);
Span::current()?->finish();
Span::current()?->finish(error: $error);
}
}, $interval, 0, function (\Throwable $th) {
Span::current()?->finish(error: $th);
});
}
return null;
}
}
+3 -1
View File
@@ -32,6 +32,7 @@ class Upgrade extends Install
->param('no-start', false, new Boolean(true), 'Run an interactive session', true)
->param('database', '', new Text(length: 0, min: 0), 'Ignored: an upgrade always keeps the database the installation already uses', true)
->param('topology', 'combined', new WhiteList(['combined', 'separate']), 'Worker and scheduler topology (combined|separate)', true)
->param('channel', Install::CHANNEL_STABLE, new WhiteList([Install::CHANNEL_STABLE, Install::CHANNEL_NIGHTLY]), 'Release channel to track (stable|nightly). Nightly is unsupported and moves daily.', true)
->param('migrate', false, new Boolean(true), 'Run database migration after upgrade', true)
->callback($this->action(...));
}
@@ -45,6 +46,7 @@ class Upgrade extends Install
bool $noStart,
string $database,
string $topology = 'combined',
string $channel = Install::CHANNEL_STABLE,
bool $migrate = false,
): void {
$this->isUpgrade = true;
@@ -101,7 +103,7 @@ class Upgrade extends Install
$this->lockedDatabase = $database;
parent::action($httpPort, $httpsPort, $organization, $image, $interactive, $noStart, $database, $topology);
parent::action($httpPort, $httpsPort, $organization, $image, $interactive, $noStart, $database, $topology, $channel);
}
protected function startWebServer(
@@ -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'] ?? '';
+11 -14
View File
@@ -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(
+99
View File
@@ -0,0 +1,99 @@
<?php
namespace Appwrite\Schedule\Source;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Schedule\Changes;
use Utopia\Schedule\Source;
use Utopia\Schedule\Source\Entry;
use Utopia\Schedule\Source\Row;
use Utopia\Schedule\Trigger\Interval;
use Utopia\Schedule\Trigger\Shifted;
use Utopia\System\System;
/**
* What the stats-resources task samples: the region's realtime concurrency,
* and the resource counts of every project accessed in the last day.
*
* Each project takes a slot derived from its id inside the interval, so a
* region's counts spread across the hour instead of bursting at the top of it.
*/
final class Stats implements Source, Changes
{
public const string CONCURRENCY = 'concurrency';
/**
* @param list<string> $subqueries project decode filters to skip; only the id is read
*/
public function __construct(
private readonly Database $dbForPlatform,
private readonly int $interval,
private readonly array $subqueries = APP_PROJECTS_SUBQUERIES,
) {
}
#[\Override]
public function snapshot(): iterable
{
yield new Row(id: self::CONCURRENCY, version: '');
yield from $this->projects((new \DateTimeImmutable())->sub(new \DateInterval('P1D')));
}
#[\Override]
public function since(\DateTimeImmutable $moment): iterable
{
yield from $this->projects($moment);
}
#[\Override]
public function make(Row $row): Entry
{
if ($row->id === self::CONCURRENCY) {
return new Entry(new Interval($this->interval));
}
// The worker reloads the project by id, so the payload carries no more.
return new Entry(
new Shifted(new Interval($this->interval), \abs(\crc32($row->id)) % $this->interval),
new Document(['$id' => $row->id]),
);
}
/**
* @return iterable<Row>
*/
private function projects(\DateTimeImmutable $accessedSince): iterable
{
$limit = 1000;
$sum = $limit;
$latest = null;
while ($sum === $limit) {
$queries = [
Query::limit($limit),
Query::equal('region', [System::getEnv('_APP_REGION', 'default')]),
Query::greaterThanEqual('accessedAt', DateTime::format(\DateTime::createFromImmutable($accessedSince))),
Query::orderAsc('$sequence'), // accessedAt can be updated during iteration
];
if ($latest !== null) {
$queries[] = Query::cursorAfter($latest);
}
$projects = $this->dbForPlatform->skipFilters(
fn () => $this->dbForPlatform->find('projects', $queries),
$this->subqueries
);
$sum = \count($projects);
foreach ($projects as $project) {
yield new Row(id: $project->getId(), version: '');
}
$latest = \end($projects) ?: null;
}
}
}
@@ -2,8 +2,27 @@
namespace Appwrite\Utopia\Database\Validator\Queries;
class Executions extends Base
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Queries;
use Utopia\Database\Validator\Query\Cursor;
use Utopia\Database\Validator\Query\Filter;
use Utopia\Database\Validator\Query\Limit;
use Utopia\Database\Validator\Query\Offset;
use Utopia\Database\Validator\Query\Order;
class Executions extends Queries
{
protected const ATTRIBUTE_TYPES = [
'trigger' => Database::VAR_STRING,
'status' => Database::VAR_STRING,
'responseStatusCode' => Database::VAR_INTEGER,
'duration' => Database::VAR_FLOAT,
'requestMethod' => Database::VAR_STRING,
'requestPath' => Database::VAR_STRING,
'deploymentId' => Database::VAR_STRING,
];
public const ALLOWED_ATTRIBUTES = [
'trigger',
'status',
@@ -18,8 +37,51 @@ class Executions extends Base
* Expression constructor
*
*/
public function __construct()
public function __construct(array $allowedAttributes = self::ALLOWED_ATTRIBUTES)
{
parent::__construct('executions', self::ALLOWED_ATTRIBUTES);
$attributes = [];
foreach ($allowedAttributes as $attribute) {
$attributes[] = new Document([
'key' => $attribute,
'type' => self::ATTRIBUTE_TYPES[$attribute],
'array' => false,
]);
}
$attributes = [
...$attributes,
new Document([
'key' => '$id',
'type' => Database::VAR_STRING,
'array' => false,
]),
new Document([
'key' => '$createdAt',
'type' => Database::VAR_DATETIME,
'array' => false,
]),
new Document([
'key' => '$updatedAt',
'type' => Database::VAR_DATETIME,
'array' => false,
]),
new Document([
'key' => '$sequence',
'type' => Database::VAR_INTEGER,
'array' => false,
]),
];
parent::__construct([
new Limit(),
new Offset(),
new Cursor(),
new Filter(
attributes: $attributes,
idAttributeType: Database::VAR_INTEGER,
maxValuesCount: APP_DATABASE_QUERY_MAX_VALUES
),
new Order($attributes),
]);
}
}
@@ -2,7 +2,7 @@
namespace Appwrite\Utopia\Database\Validator\Queries;
class Logs extends Base
class Logs extends Executions
{
public const ALLOWED_ATTRIBUTES = [
'status',
@@ -19,6 +19,6 @@ class Logs extends Base
*/
public function __construct()
{
parent::__construct('executions', self::ALLOWED_ATTRIBUTES); //TODO: Update this later
parent::__construct(self::ALLOWED_ATTRIBUTES);
}
}
+5 -9
View File
@@ -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'] . ')';
+5 -4
View File
@@ -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()
@@ -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);
@@ -238,7 +238,7 @@ final class VCSGiteaConsoleClientTest extends Scope
/** @var array<string, string> $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([
+13
View File
@@ -4,7 +4,10 @@ declare(strict_types=1);
namespace Tests\Unit\General;
use Appwrite\Utopia\Database\Validator\Queries\Executions;
use Appwrite\Utopia\Database\Validator\Queries\Logs;
use PHPUnit\Framework\TestCase;
use Utopia\Database\Query;
final class CollectionsTest extends TestCase
{
@@ -33,4 +36,14 @@ final class CollectionsTest extends TestCase
}
}
}
public function testExecutionQueryValidatorsDoNotNeedCollectionSchema(): void
{
$this->assertTrue((new Executions())->isValid([
Query::equal('status', ['completed']),
]));
$this->assertTrue((new Logs())->isValid([
Query::equal('status', ['completed']),
]));
}
}
@@ -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];
+6 -52
View File
@@ -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();