From 66060a5d9a514c3b9b493d47da6daab7d8332afb Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Tue, 30 Jun 2026 09:38:24 +0530 Subject: [PATCH] Revert "Merge pull request #12195 from appwrite/feat-notifications-worker" This reverts commit cb6570124b79088721fb59fff3abe5c11ca2230a, reversing changes made to a6f753e17bec5bf80b8473c3dcbf1b3f9b626bed. --- .env | 1 - .github/workflows/ci.yml | 1 - Dockerfile | 1 - app/config/collections/platform.php | 257 --- app/config/variables.php | 9 - app/controllers/api/messaging.php | 9 - app/init/constants.php | 10 - app/init/models.php | 3 - app/init/resources.php | 6 - app/init/worker/message.php | 13 - bin/worker-mails | 2 +- bin/worker-notifications | 3 - docker-compose.yml | 44 - .../health/get-queue-notifications.md | 1 - docs/references/notifications/get-logo.md | 1 - .../notifications/list-notifications.md | 1 - .../notifications/update-notification.md | 1 - phpunit.xml | 1 - src/Appwrite/Docker/Compose.php | 4 +- src/Appwrite/Docker/Compose/Service.php | 5 - src/Appwrite/Event/Event.php | 3 - src/Appwrite/Event/Message/Notification.php | 116 -- src/Appwrite/Event/Publisher/Notification.php | 27 - src/Appwrite/Migration/Version/V19.php | 1 - src/Appwrite/Migration/Version/V24.php | 53 - src/Appwrite/Platform/Appwrite.php | 2 - .../Functions/Http/Executions/Create.php | 1 - .../Functions/Http/Functions/Create.php | 1 - .../Functions/Http/Functions/Update.php | 2 - .../Health/Http/Health/Queue/Failed/Get.php | 5 - .../Http/Health/Queue/Notifications/Get.php | 60 - .../Platform/Modules/Health/Services/Http.php | 2 - .../Http/Notifications/Logos/Appwrite/Get.php | 209 --- .../Http/Notifications/Update.php | 87 -- .../Http/Notifications/XList.php | 118 -- .../Platform/Modules/Notifications/Module.php | 14 - .../Modules/Notifications/Services/Http.php | 21 - .../Project/Http/Project/Labels/Update.php | 1 - .../Project/Http/Project/MockPhone/Create.php | 1 - .../Project/Http/Project/MockPhone/Delete.php | 1 - .../Project/Http/Project/MockPhone/Update.php | 1 - .../Projects/Http/Projects/Team/Update.php | 1 - .../Modules/Projects/Http/Projects/Update.php | 1 - .../Projects/Http/Schedules/Create.php | 1 - .../Modules/Projects/Http/Schedules/Get.php | 7 +- .../Modules/Projects/Http/Schedules/XList.php | 19 +- src/Appwrite/Platform/Services/Workers.php | 2 - src/Appwrite/Platform/Workers/Deletes.php | 11 - .../Platform/Workers/Notifications.php | 661 -------- src/Appwrite/Platform/Workers/Webhooks.php | 156 +- src/Appwrite/SDK/ContentType.php | 1 - .../SDK/Specification/Format/OpenAPI3.php | 1 - .../Validator/Queries/Notifications.php | 25 - .../Utopia/Messaging/Adapter/Console.php | 147 -- .../Utopia/Messaging/Adapter/Webhook.php | 124 -- .../Utopia/Messaging/Messages/Console.php | 82 - .../Utopia/Messaging/Messages/Webhook.php | 80 - src/Appwrite/Utopia/Response.php | 4 - src/Appwrite/Utopia/Response/Model/Log.php | 2 +- .../Utopia/Response/Model/Notification.php | 126 -- .../Notifications/NotificationsBase.php | 632 -------- .../NotificationsCustomConsoleTest.php | 16 - .../NotificationsCustomServerTest.php | 16 - tests/resources/docker/docker-compose.yml | 24 - tests/unit/Docker/ComposeTest.php | 14 +- tests/unit/Event/Message/NotificationTest.php | 86 - tests/unit/Event/MockPublisher.php | 2 +- .../unit/Migration/MigrationVersionsTest.php | 106 -- .../Notifications/NotificationsTest.php | 130 -- .../Modules/Projects/SchedulesTest.php | 161 -- tests/unit/Platform/Workers/DeletesTest.php | 93 -- tests/unit/Platform/Workers/MailsTest.php | 98 -- .../Platform/Workers/NotificationsTest.php | 1383 ----------------- .../Platform/Workers/RegistrationTest.php | 30 - tests/unit/Platform/Workers/WebhooksTest.php | 283 ---- .../Messaging/Adapter/CapturingWebhook.php | 34 - .../Utopia/Messaging/Adapter/ConsoleTest.php | 282 ---- .../Utopia/Messaging/Adapter/WebhookTest.php | 180 --- 78 files changed, 53 insertions(+), 6067 deletions(-) delete mode 100755 bin/worker-notifications delete mode 100644 docs/references/health/get-queue-notifications.md delete mode 100644 docs/references/notifications/get-logo.md delete mode 100644 docs/references/notifications/list-notifications.md delete mode 100644 docs/references/notifications/update-notification.md delete mode 100644 src/Appwrite/Event/Message/Notification.php delete mode 100644 src/Appwrite/Event/Publisher/Notification.php delete mode 100644 src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Notifications/Get.php delete mode 100644 src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Logos/Appwrite/Get.php delete mode 100644 src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Update.php delete mode 100644 src/Appwrite/Platform/Modules/Notifications/Http/Notifications/XList.php delete mode 100644 src/Appwrite/Platform/Modules/Notifications/Module.php delete mode 100644 src/Appwrite/Platform/Modules/Notifications/Services/Http.php delete mode 100644 src/Appwrite/Platform/Workers/Notifications.php delete mode 100644 src/Appwrite/Utopia/Database/Validator/Queries/Notifications.php delete mode 100644 src/Appwrite/Utopia/Messaging/Adapter/Console.php delete mode 100644 src/Appwrite/Utopia/Messaging/Adapter/Webhook.php delete mode 100644 src/Appwrite/Utopia/Messaging/Messages/Console.php delete mode 100644 src/Appwrite/Utopia/Messaging/Messages/Webhook.php delete mode 100644 src/Appwrite/Utopia/Response/Model/Notification.php delete mode 100644 tests/e2e/Services/Notifications/NotificationsBase.php delete mode 100644 tests/e2e/Services/Notifications/NotificationsCustomConsoleTest.php delete mode 100644 tests/e2e/Services/Notifications/NotificationsCustomServerTest.php delete mode 100644 tests/unit/Event/Message/NotificationTest.php delete mode 100644 tests/unit/Platform/Modules/Notifications/NotificationsTest.php delete mode 100644 tests/unit/Platform/Modules/Projects/SchedulesTest.php delete mode 100644 tests/unit/Platform/Workers/DeletesTest.php delete mode 100644 tests/unit/Platform/Workers/MailsTest.php delete mode 100644 tests/unit/Platform/Workers/NotificationsTest.php delete mode 100644 tests/unit/Platform/Workers/RegistrationTest.php delete mode 100644 tests/unit/Platform/Workers/WebhooksTest.php delete mode 100644 tests/unit/Utopia/Messaging/Adapter/CapturingWebhook.php delete mode 100644 tests/unit/Utopia/Messaging/Adapter/ConsoleTest.php delete mode 100644 tests/unit/Utopia/Messaging/Adapter/WebhookTest.php diff --git a/.env b/.env index edc7bb741a..dc2bc60763 100644 --- a/.env +++ b/.env @@ -2,7 +2,6 @@ _APP_ENV=development _APP_EDITION=self-hosted _APP_LOCALE=en _APP_OPENSSL_KEY_V1=your-secret-key -_APP_NOTIFICATIONS_TRACKING_SECRET=your-secret-key _APP_RULES_FORMAT=md5 _APP_SYSTEM_RESPONSE_FORMAT= _APP_TRUSTED_HEADERS=x-forwarded-for diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a4e8ab5bd..e3883e1838 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -213,7 +213,6 @@ jobs: { name: 'Webhooks', runner: runner4, functional: true, processes: null, timeout: 15 }, { name: 'VCS', runner: runner4, functional: true, processes: null, timeout: 15 }, { name: 'Messaging', runner: runner4, functional: true, processes: null, timeout: 15 }, - { name: 'Notifications', runner: runner4, functional: true, processes: null, timeout: 15 }, { name: 'Migrations', runner: runner4, functional: true, processes: 1, timeout: 15 }, { name: 'Project', runner: runner4, functional: true, processes: null, timeout: 15 }, { name: 'Presences', runner: runner4, functional: true, processes: null, timeout: 15 }, diff --git a/Dockerfile b/Dockerfile index bdda7298b2..7ffd23f683 100755 --- a/Dockerfile +++ b/Dockerfile @@ -93,7 +93,6 @@ RUN chmod +x /usr/local/bin/doctor && \ chmod +x /usr/local/bin/worker-functions && \ chmod +x /usr/local/bin/worker-mails && \ chmod +x /usr/local/bin/worker-messaging && \ - chmod +x /usr/local/bin/worker-notifications && \ chmod +x /usr/local/bin/worker-migrations && \ chmod +x /usr/local/bin/worker-webhooks && \ chmod +x /usr/local/bin/worker-stats-usage && \ diff --git a/app/config/collections/platform.php b/app/config/collections/platform.php index a90170946b..f93d82456e 100644 --- a/app/config/collections/platform.php +++ b/app/config/collections/platform.php @@ -485,17 +485,6 @@ $platformCollections = [ 'array' => false, 'filters' => [], ], - [ - '$id' => ID::custom('projectInternalId'), - 'type' => Database::VAR_ID, - 'format' => '', - 'size' => 0, - 'signed' => true, - 'required' => false, - 'default' => null, - 'array' => false, - 'filters' => [], - ], [ '$id' => ID::custom('schedule'), 'type' => Database::VAR_STRING, @@ -556,13 +545,6 @@ $platformCollections = [ 'lengths' => [], 'orders' => [], ], - [ - '$id' => ID::custom('_key_region_resourceType_projectInternalId_resourceId'), - 'type' => Database::INDEX_KEY, - 'attributes' => ['region', 'resourceType', 'projectInternalId', 'resourceId'], - 'lengths' => [], - 'orders' => [], - ], [ '$id' => ID::custom('_key_project_id_region'), 'type' => Database::INDEX_KEY, @@ -570,13 +552,6 @@ $platformCollections = [ 'lengths' => [], 'orders' => [], ], - [ - '$id' => ID::custom('_key_project_internal_id_region'), - 'type' => Database::INDEX_KEY, - 'attributes' => ['projectInternalId', 'region'], - 'lengths' => [], - 'orders' => [], - ], [ '$id' => ID::custom('_key_region_rt_active'), 'type' => Database::INDEX_KEY, @@ -1068,238 +1043,6 @@ $platformCollections = [ ], ], - 'notifications' => [ - '$collection' => ID::custom(Database::METADATA), - '$id' => ID::custom('notifications'), - 'name' => 'Notifications', - 'attributes' => [ - [ - '$id' => ID::custom('messageId'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => Database::LENGTH_KEY, - 'signed' => true, - 'required' => false, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('recipientHash'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 64, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('type'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 100, - 'signed' => true, - 'required' => false, - 'default' => 'info', - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('channel'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 64, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('resourceType'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 64, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('resourceId'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => Database::LENGTH_KEY, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('projectId'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => Database::LENGTH_KEY, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('projectInternalId'), - 'type' => Database::VAR_ID, - 'format' => '', - 'size' => 0, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('resourceInternalId'), - 'type' => Database::VAR_ID, - 'format' => '', - 'size' => 0, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('parentResourceType'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 64, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('parentResourceId'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => Database::LENGTH_KEY, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('parentResourceInternalId'), - 'type' => Database::VAR_ID, - 'format' => '', - 'size' => 0, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('title'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 256, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('body'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 65535, - 'signed' => true, - 'required' => true, - 'default' => null, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('read'), - 'type' => Database::VAR_BOOLEAN, - 'format' => '', - 'size' => 0, - 'signed' => true, - 'required' => false, - 'default' => false, - 'array' => false, - 'filters' => [], - ], - [ - '$id' => ID::custom('firstSeen'), - 'type' => Database::VAR_DATETIME, - 'format' => '', - 'size' => 0, - 'signed' => false, - 'required' => false, - 'default' => null, - 'array' => false, - 'filters' => ['datetime'], - ], - [ - '$id' => ID::custom('lastSeen'), - 'type' => Database::VAR_DATETIME, - 'format' => '', - 'size' => 0, - 'signed' => false, - 'required' => false, - 'default' => null, - 'array' => false, - 'filters' => ['datetime'], - ], - ], - 'indexes' => [ - [ - '$id' => ID::custom('_key_messageId'), - 'type' => Database::INDEX_KEY, - 'attributes' => ['messageId'], - 'lengths' => [Database::LENGTH_KEY], - 'orders' => [Database::ORDER_ASC], - ], - [ - '$id' => ID::custom('_key_recipient'), - 'type' => Database::INDEX_UNIQUE, - 'attributes' => ['messageId', 'channel', 'recipientHash'], - 'lengths' => [Database::LENGTH_KEY, 64, 64], - 'orders' => [Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC], - ], - [ - '$id' => ID::custom('_key_project'), - 'type' => Database::INDEX_KEY, - 'attributes' => ['projectId', 'projectInternalId'], - 'lengths' => [Database::LENGTH_KEY, 0], - 'orders' => [Database::ORDER_ASC, Database::ORDER_ASC], - ], - [ - '$id' => ID::custom('_key_project_resource'), - 'type' => Database::INDEX_KEY, - 'attributes' => ['projectId', 'projectInternalId', 'resourceType', 'resourceId', 'resourceInternalId'], - 'lengths' => [Database::LENGTH_KEY, 0, 64, Database::LENGTH_KEY, 0], - 'orders' => [Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC], - ], - [ - '$id' => ID::custom('_key_project_parent_resource'), - 'type' => Database::INDEX_KEY, - 'attributes' => ['projectId', 'projectInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'], - 'lengths' => [Database::LENGTH_KEY, 0, 64, Database::LENGTH_KEY, 0], - 'orders' => [Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC], - ], - ], - ], - 'certificates' => [ '$collection' => ID::custom(Database::METADATA), '$id' => ID::custom('certificates'), diff --git a/app/config/variables.php b/app/config/variables.php index 8b4fa74bf9..b77d841aaf 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -79,15 +79,6 @@ return [ 'question' => 'Choose a secret API key, make sure to make a backup of your key in a secure location', 'filter' => 'token' ], - [ - 'name' => '_APP_NOTIFICATIONS_TRACKING_SECRET', - 'description' => 'Secret key used to sign notification logo tracking tokens. This must be the same value for API containers and notification workers. Change it from the default value before running in production.', - 'introduction' => '1.9.0', - 'default' => 'your-secret-key', - 'required' => true, - 'question' => '', - 'filter' => 'token' - ], [ 'name' => '_APP_DOMAIN', 'description' => 'Your Appwrite domain address. When setting a public suffix domain, Appwrite will attempt to issue a valid SSL certificate automatically. When used with a dev domain, Appwrite will assign a self-signed SSL certificate. The default value is \'localhost\'. Multiple domains can be separated by commas.', diff --git a/app/controllers/api/messaging.php b/app/controllers/api/messaging.php index 61a35761ca..13119ac2c6 100644 --- a/app/controllers/api/messaging.php +++ b/app/controllers/api/messaging.php @@ -3501,7 +3501,6 @@ Http::post('/v1/messaging/messages/email') 'resourceInternalId' => $message->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $scheduledAt, 'active' => true, ])); @@ -3648,7 +3647,6 @@ Http::post('/v1/messaging/messages/sms') 'resourceInternalId' => $message->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $scheduledAt, 'active' => true, ])); @@ -3871,7 +3869,6 @@ Http::post('/v1/messaging/messages/push') 'resourceInternalId' => $message->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $scheduledAt, 'active' => true, ])); @@ -4266,7 +4263,6 @@ Http::patch('/v1/messaging/messages/email/:messageId') 'resourceInternalId' => $message->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $scheduledAt, 'active' => $status === MessageStatus::SCHEDULED, ])); @@ -4283,7 +4279,6 @@ Http::patch('/v1/messaging/messages/email/:messageId') } $schedule - ->setAttribute('projectInternalId', $project->getSequence()) ->setAttribute('resourceUpdatedAt', DateTime::now()) ->setAttribute('active', $scheduledStatus); @@ -4492,7 +4487,6 @@ Http::patch('/v1/messaging/messages/sms/:messageId') 'resourceInternalId' => $message->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $scheduledAt, 'active' => $status === MessageStatus::SCHEDULED, ])); @@ -4509,7 +4503,6 @@ Http::patch('/v1/messaging/messages/sms/:messageId') } $schedule - ->setAttribute('projectInternalId', $project->getSequence()) ->setAttribute('resourceUpdatedAt', DateTime::now()) ->setAttribute('active', $scheduledStatus); @@ -4671,7 +4664,6 @@ Http::patch('/v1/messaging/messages/push/:messageId') 'resourceInternalId' => $message->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $scheduledAt, 'active' => $status === MessageStatus::SCHEDULED, ])); @@ -4688,7 +4680,6 @@ Http::patch('/v1/messaging/messages/push/:messageId') } $schedule - ->setAttribute('projectInternalId', $project->getSequence()) ->setAttribute('resourceUpdatedAt', DateTime::now()) ->setAttribute('active', $scheduledStatus); diff --git a/app/init/constants.php b/app/init/constants.php index e905ed56b4..9efb6e3222 100644 --- a/app/init/constants.php +++ b/app/init/constants.php @@ -168,7 +168,6 @@ const SESSION_PROVIDER_SERVER = 'server'; const ACTOR_TYPE_USER = 'user'; const ACTOR_TYPE_ADMIN = 'admin'; const ACTOR_TYPE_GUEST = 'guest'; -const ACTOR_TYPE_HIDDEN = 'hidden'; const ACTOR_TYPE_KEY_PROJECT = 'keyProject'; const ACTOR_TYPE_KEY_ACCOUNT = 'keyAccount'; const ACTOR_TYPE_KEY_ORGANIZATION = 'keyOrganization'; @@ -279,13 +278,6 @@ const FUNCTION_ALLOWLIST_HEADERS_RESPONSE = ['content-type', 'content-length']; const MESSAGE_TYPE_EMAIL = 'email'; const MESSAGE_TYPE_SMS = 'sms'; const MESSAGE_TYPE_PUSH = 'push'; -// Notification types -const NOTIFICATION_TYPE_EMAIL = MESSAGE_TYPE_EMAIL; -const NOTIFICATION_TYPE_SMS = MESSAGE_TYPE_SMS; -const NOTIFICATION_TYPE_PUSH = MESSAGE_TYPE_PUSH; -const NOTIFICATION_TYPE_CONSOLE = 'console'; -const NOTIFICATION_TYPE_WEBHOOK = 'webhook'; -const NOTIFICATION_TRACKING_JWT_TTL = 60 * 60 * 24 * 7; const MAIL_TEMPLATE_CERTIFICATE_FAILED = 'certificate-failed'; const MAIL_TEMPLATE_DATA_EXPORT = 'data-export'; const MAIL_TEMPLATE_INVITATION = 'invitation'; @@ -471,8 +463,6 @@ const RESOURCE_TYPE_SUBSCRIBERS = 'subscribers'; const RESOURCE_TYPE_MESSAGES = 'messages'; const RESOURCE_TYPE_EXECUTIONS = 'executions'; const RESOURCE_TYPE_VCS = 'vcs'; -const RESOURCE_TYPE_USERS = 'users'; -const RESOURCE_TYPE_TEAMS = 'teams'; const RESOURCE_TYPE_EMBEDDINGS_TEXT = 'embeddingsText'; const RESOURCE_TYPE_INSIGHTS = 'insights'; const RESOURCE_TYPE_REPORTS = 'reports'; diff --git a/app/init/models.php b/app/init/models.php index cdb2a9b9b6..efd2c13215 100644 --- a/app/init/models.php +++ b/app/init/models.php @@ -115,7 +115,6 @@ use Appwrite\Utopia\Response\Model\MigrationReport; use Appwrite\Utopia\Response\Model\Mock; use Appwrite\Utopia\Response\Model\MockNumber; use Appwrite\Utopia\Response\Model\None; -use Appwrite\Utopia\Response\Model\Notification; use Appwrite\Utopia\Response\Model\OAuth2Amazon; use Appwrite\Utopia\Response\Model\OAuth2Apple; use Appwrite\Utopia\Response\Model\OAuth2Auth0; @@ -251,7 +250,6 @@ Response::setModel(new BaseList('Column Indexes List', Response::MODEL_COLUMN_IN Response::setModel(new BaseList('Users List', Response::MODEL_USER_LIST, 'users', Response::MODEL_USER)); Response::setModel(new BaseList('Sessions List', Response::MODEL_SESSION_LIST, 'sessions', Response::MODEL_SESSION)); Response::setModel(new BaseList('Identities List', Response::MODEL_IDENTITY_LIST, 'identities', Response::MODEL_IDENTITY)); -Response::setModel(new BaseList('Notifications List', Response::MODEL_NOTIFICATION_LIST, 'notifications', Response::MODEL_NOTIFICATION)); Response::setModel(new BaseList('Logs List', Response::MODEL_LOG_LIST, 'logs', Response::MODEL_LOG)); Response::setModel(new BaseList('Files List', Response::MODEL_FILE_LIST, 'files', Response::MODEL_FILE)); Response::setModel(new BaseList('Buckets List', Response::MODEL_BUCKET_LIST, 'buckets', Response::MODEL_BUCKET)); @@ -383,7 +381,6 @@ Response::setModel(new Account()); Response::setModel(new Preferences()); Response::setModel(new Session()); Response::setModel(new Identity()); -Response::setModel(new Notification()); Response::setModel(new Token()); Response::setModel(new JWT()); Response::setModel(new Locale()); diff --git a/app/init/resources.php b/app/init/resources.php index 51d0b25f8a..34f66d3de7 100644 --- a/app/init/resources.php +++ b/app/init/resources.php @@ -12,7 +12,6 @@ use Appwrite\Event\Publisher\Func as FunctionPublisher; use Appwrite\Event\Publisher\Mail as MailPublisher; use Appwrite\Event\Publisher\Messaging as MessagingPublisher; use Appwrite\Event\Publisher\Migration as MigrationPublisher; -use Appwrite\Event\Publisher\Notification as NotificationPublisher; use Appwrite\Event\Publisher\Screenshot as ScreenshotPublisher; use Appwrite\Event\Publisher\StatsResources as StatsResourcesPublisher; use Appwrite\Event\Publisher\Usage as UsagePublisher; @@ -151,11 +150,6 @@ $container->set('publisherForMessaging', fn (Publisher $publisher) => new Messag new Queue(System::getEnv('_APP_MESSAGING_QUEUE_NAME', Event::MESSAGING_QUEUE_NAME)) ), ['publisher']); -$container->set('publisherForNotifications', fn (Publisher $publisher) => new NotificationPublisher( - $publisher, - new Queue(System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME)) -), ['publisher']); - $container->set('databaseFactory', fn (Group $pools, Cache $cache, Authorization $authorization) => new DatabaseFactory( $pools, $cache, diff --git a/app/init/worker/message.php b/app/init/worker/message.php index a5838e9257..7cbfe19b0f 100644 --- a/app/init/worker/message.php +++ b/app/init/worker/message.php @@ -2,8 +2,6 @@ use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Event\Event; -use Appwrite\Event\Publisher\Func as FunctionPublisher; -use Appwrite\Event\Publisher\Notification as NotificationPublisher; use Appwrite\Event\Realtime; use Appwrite\Event\Webhook; use Appwrite\Usage\Context; @@ -19,7 +17,6 @@ use Utopia\DI\Container; use Utopia\Logger\Log; use Utopia\Pools\Group; use Utopia\Queue\Publisher; -use Utopia\Queue\Queue; use Utopia\Registry\Registry; use Utopia\Span\Span; use Utopia\Storage\Device\Telemetry as TelemetryDevice; @@ -148,16 +145,6 @@ return function (Container $container): void { return new Webhook($publisher); }, ['publisher']); - $container->set('publisherForNotifications', fn (Publisher $publisher) => new NotificationPublisher( - $publisher, - new Queue(System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME)) - ), ['publisher']); - - $container->set('publisherForFunctions', fn (Publisher $publisher) => new FunctionPublisher( - $publisher, - new Queue(System::getEnv('_APP_FUNCTIONS_QUEUE_NAME', Event::FUNCTIONS_QUEUE_NAME), 'utopia-queue', Event::FUNCTIONS_QUEUE_TTL) - ), ['publisher']); - $container->set('queueForRealtime', function () { return new Realtime(); }, []); diff --git a/bin/worker-mails b/bin/worker-mails index a28b1ddc67..3b1415f45f 100644 --- a/bin/worker-mails +++ b/bin/worker-mails @@ -1,3 +1,3 @@ #!/bin/sh -exec php /usr/src/code/app/worker.php mails "$@" +exec php /usr/src/code/app/worker.php mails "$@" \ No newline at end of file diff --git a/bin/worker-notifications b/bin/worker-notifications deleted file mode 100755 index 1b7bf28745..0000000000 --- a/bin/worker-notifications +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -exec php /usr/src/code/app/worker.php notifications "$@" diff --git a/docker-compose.yml b/docker-compose.yml index 9a43dc1dad..7ad12e7ddf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -99,7 +99,6 @@ services: - _APP_OPTIONS_FORCE_HTTPS - _APP_OPTIONS_ROUTER_FORCE_HTTPS - _APP_OPENSSL_KEY_V1 - - _APP_NOTIFICATIONS_TRACKING_SECRET - _APP_DOMAIN - _APP_CONSOLE_DOMAIN - _APP_CONSOLE_TRUSTED_PROJECTS @@ -748,7 +747,6 @@ services: - _APP_WORKER_PER_CORE - _APP_POOL_ADAPTER - _APP_OPENSSL_KEY_V1 - - _APP_NOTIFICATIONS_TRACKING_SECRET - _APP_SYSTEM_EMAIL_NAME - _APP_SYSTEM_EMAIL_ADDRESS - _APP_REDIS_HOST @@ -771,48 +769,6 @@ services: - _APP_OPTIONS_FORCE_HTTPS - _APP_DATABASE_SHARED_TABLES - appwrite-worker-notifications: - entrypoint: worker-notifications - logging: - driver: json-file - options: - max-file: "5" - max-size: 10m - container_name: appwrite-worker-notifications - restart: unless-stopped - image: ${_APP_IMAGE:-appwrite/appwrite}:${_APP_VERSION:-latest} - networks: - - appwrite - depends_on: - - redis - - ${_APP_DB_HOST:-mariadb} - environment: - - _APP_ENV - - _APP_WORKER_PER_CORE - - _APP_POOL_ADAPTER - - _APP_OPENSSL_KEY_V1 - - _APP_NOTIFICATIONS_TRACKING_SECRET - - _APP_SYSTEM_EMAIL_NAME - - _APP_SYSTEM_EMAIL_ADDRESS - - _APP_REDIS_HOST - - _APP_REDIS_PORT - - _APP_REDIS_USER - - _APP_REDIS_PASS - - _APP_DB_HOST - - _APP_DB_PORT - - _APP_DB_SCHEMA - - _APP_DB_USER - - _APP_DB_PASS - - _APP_DB_ADAPTER - - _APP_SMTP_HOST - - _APP_SMTP_PORT - - _APP_SMTP_SECURE - - _APP_SMTP_USERNAME - - _APP_SMTP_PASSWORD - - _APP_LOGGING_CONFIG - - _APP_DOMAIN - - _APP_OPTIONS_FORCE_HTTPS - - _APP_DATABASE_SHARED_TABLES appwrite-worker-messaging: entrypoint: worker-messaging logging: diff --git a/docs/references/health/get-queue-notifications.md b/docs/references/health/get-queue-notifications.md deleted file mode 100644 index 529d1056e9..0000000000 --- a/docs/references/health/get-queue-notifications.md +++ /dev/null @@ -1 +0,0 @@ -Get the number of jobs in the notifications queue. diff --git a/docs/references/notifications/get-logo.md b/docs/references/notifications/get-logo.md deleted file mode 100644 index eadc755c69..0000000000 --- a/docs/references/notifications/get-logo.md +++ /dev/null @@ -1 +0,0 @@ -Get the Appwrite logo SVG used in notification emails. When loaded with a valid tracking token, the related notification is marked as read and its view timestamps are updated. diff --git a/docs/references/notifications/list-notifications.md b/docs/references/notifications/list-notifications.md deleted file mode 100644 index 3d9f93789c..0000000000 --- a/docs/references/notifications/list-notifications.md +++ /dev/null @@ -1 +0,0 @@ -Get the list of notifications for the currently logged in console user. Use queries to filter the results by attributes such as read status, view timestamps, or creation date. diff --git a/docs/references/notifications/update-notification.md b/docs/references/notifications/update-notification.md deleted file mode 100644 index 220c79b70e..0000000000 --- a/docs/references/notifications/update-notification.md +++ /dev/null @@ -1 +0,0 @@ -Update a notification by its unique ID. Use the `read` parameter to mark the notification as read or unread. diff --git a/phpunit.xml b/phpunit.xml index 56953fdeaf..32e865fe35 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -37,7 +37,6 @@ ./tests/e2e/Services/ProjectWebhooks ./tests/e2e/Services/Messaging ./tests/e2e/Services/Migrations - ./tests/e2e/Services/Notifications ./tests/e2e/Services/Project ./tests/e2e/Services/Advisor ./tests/e2e/Services/Functions/FunctionsBase.php diff --git a/src/Appwrite/Docker/Compose.php b/src/Appwrite/Docker/Compose.php index f879ad7aec..9ea6420d2d 100644 --- a/src/Appwrite/Docker/Compose.php +++ b/src/Appwrite/Docker/Compose.php @@ -4,7 +4,6 @@ namespace Appwrite\Docker; use Appwrite\Docker\Compose\Service; use Exception; -use Spyc; class Compose { @@ -15,8 +14,7 @@ class Compose public function __construct(string $data) { - $compose = \function_exists('yaml_parse') ? \yaml_parse($data) : Spyc::YAMLLoadString($data); - $this->compose = \is_array($compose) ? $compose : []; + $this->compose = yaml_parse($data); $this->compose['services'] = (isset($this->compose['services']) && is_array($this->compose['services'])) ? $this->compose['services'] : []; diff --git a/src/Appwrite/Docker/Compose/Service.php b/src/Appwrite/Docker/Compose/Service.php index 0ea84c12f6..e7993d6927 100644 --- a/src/Appwrite/Docker/Compose/Service.php +++ b/src/Appwrite/Docker/Compose/Service.php @@ -54,11 +54,6 @@ class Service return substr($image, ((int)strpos($image, ':')) + 1); } - public function getEntrypoint(): string - { - return (isset($this->service['entrypoint'])) ? $this->service['entrypoint'] : ''; - } - /** * @return Env */ diff --git a/src/Appwrite/Event/Event.php b/src/Appwrite/Event/Event.php index 54841343e7..357442a07c 100644 --- a/src/Appwrite/Event/Event.php +++ b/src/Appwrite/Event/Event.php @@ -21,9 +21,6 @@ class Event public const MAILS_QUEUE_NAME = 'v1-mails'; public const MAILS_CLASS_NAME = 'MailsV1'; - public const NOTIFICATIONS_QUEUE_NAME = 'v1-notifications'; - public const NOTIFICATIONS_CLASS_NAME = 'NotificationsV1'; - public const FUNCTIONS_QUEUE_NAME = 'v1-functions'; public const FUNCTIONS_CLASS_NAME = 'FunctionsV1'; public const FUNCTIONS_QUEUE_TTL = 60 * 60 * 24 * 7; // 7 days diff --git a/src/Appwrite/Event/Message/Notification.php b/src/Appwrite/Event/Message/Notification.php deleted file mode 100644 index 644d29d300..0000000000 --- a/src/Appwrite/Event/Message/Notification.php +++ /dev/null @@ -1,116 +0,0 @@ - $recipients - * @param array $channels - * @param array $templateParams - * @param array $permissions - * @param array $variables - * @param array $attachment - * @param array $events - * @param array $params - * @param array $platform - */ - public function __construct( - public readonly ?Document $project = null, - public readonly string $recipient = '', - public readonly array $recipients = [], - public readonly array $channels = [], - public readonly string $template = '', - public readonly array $templateParams = [], - public readonly string $deduplicationKey = '', - public readonly array $permissions = [], - public readonly string $name = '', - public readonly string $subject = '', - public readonly string $bodyTemplate = '', - public readonly string $body = '', - public readonly string $preview = '', - public readonly array $variables = [], - public readonly array $attachment = [], - public readonly array $events = [], - public readonly string $event = '', - public readonly array $params = [], - public readonly array $platform = [], - ) { - } - - public function toArray(): array - { - $recipients = $this->recipients; - if (empty($recipients) && $this->recipient !== '') { - $recipients = [[ - 'address' => $this->recipient, - 'channel' => NOTIFICATION_TYPE_EMAIL, - ]]; - } - - $platform = !empty($this->platform) ? $this->platform : Config::getParam('platform', []); - - return [ - 'project' => $this->project === null ? null : [ - '$id' => $this->project->getId(), - '$sequence' => $this->project->getSequence(), - 'database' => $this->project->getAttribute('database'), - ], - 'recipient' => $this->recipient, - 'recipients' => $recipients, - 'channels' => $this->channels, - 'template' => $this->template, - 'templateParams' => $this->templateParams, - 'deduplicationKey' => $this->deduplicationKey, - 'permissions' => $this->permissions, - 'name' => $this->name, - 'subject' => $this->subject, - 'bodyTemplate' => $this->bodyTemplate, - 'body' => $this->body, - 'preview' => $this->preview, - 'variables' => $this->variables, - 'attachment' => $this->attachment, - 'events' => !empty($this->events) ? $this->events : $this->generateEvents(), - 'platform' => $platform, - ]; - } - - public static function fromArray(array $data): static - { - return new self( - project: !empty($data['project']) ? new Document($data['project']) : null, - recipient: $data['recipient'] ?? '', - recipients: $data['recipients'] ?? [], - channels: $data['channels'] ?? [], - template: $data['template'] ?? '', - templateParams: $data['templateParams'] ?? [], - deduplicationKey: $data['deduplicationKey'] ?? '', - permissions: $data['permissions'] ?? [], - name: $data['name'] ?? '', - subject: $data['subject'] ?? '', - bodyTemplate: $data['bodyTemplate'] ?? '', - body: $data['body'] ?? '', - preview: $data['preview'] ?? '', - variables: $data['variables'] ?? [], - attachment: $data['attachment'] ?? [], - events: $data['events'] ?? [], - platform: $data['platform'] ?? [], - ); - } - - /** - * @return array - */ - private function generateEvents(): array - { - if ($this->event === '') { - return []; - } - - return Event::generateEvents($this->event, $this->params); - } -} diff --git a/src/Appwrite/Event/Publisher/Notification.php b/src/Appwrite/Event/Publisher/Notification.php deleted file mode 100644 index 2fe0353276..0000000000 --- a/src/Appwrite/Event/Publisher/Notification.php +++ /dev/null @@ -1,27 +0,0 @@ -publish($queue ?? $this->queue, $message); - } - - public function getSize(bool $failed = false, ?Queue $queue = null): int - { - return $this->getQueueSize($queue ?? $this->queue, $failed); - } -} diff --git a/src/Appwrite/Migration/Version/V19.php b/src/Appwrite/Migration/Version/V19.php index 6f939b4ce4..2526d03009 100644 --- a/src/Appwrite/Migration/Version/V19.php +++ b/src/Appwrite/Migration/Version/V19.php @@ -736,7 +736,6 @@ class V19 extends Migration 'resourceInternalId' => $document->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $this->project->getId(), - 'projectInternalId' => $this->project->getSequence(), 'schedule' => $document->getAttribute('schedule'), 'active' => !empty($document->getAttribute('schedule')) && !empty($document->getAttribute('deployment')), ])); diff --git a/src/Appwrite/Migration/Version/V24.php b/src/Appwrite/Migration/Version/V24.php index ea1cd2088e..82889f8d79 100644 --- a/src/Appwrite/Migration/Version/V24.php +++ b/src/Appwrite/Migration/Version/V24.php @@ -90,12 +90,6 @@ class V24 extends Migration }; $collections = $this->collections[$collectionType]; - $notificationsCollectionExists = false; - - if ($collectionType === 'console') { - $notificationsCollectionExists = !$this->dbForProject->getCollection('notifications')->isEmpty(); - $this->createCollection('notifications'); - } foreach ($collections as $collection) { $id = $collection['$id']; @@ -159,42 +153,6 @@ class V24 extends Migration $this->dbForProject->purgeCachedCollection($id); break; - case 'schedules': - if ($collectionType === 'console') { - try { - $this->createAttributeFromCollection($this->dbForProject, $id, 'projectInternalId'); - } catch (Throwable $th) { - Console::warning("Failed to create attribute \"projectInternalId\" in collection {$id}: {$th->getMessage()}"); - } - - $indexes = [ - '_key_region_resourceType_projectInternalId_resourceId', - '_key_project_internal_id_region', - ]; - foreach ($indexes as $index) { - try { - $this->createIndexFromCollection($this->dbForProject, $id, $index); - } catch (Throwable $th) { - Console::warning("Failed to create index \"{$index}\" from {$id}: {$th->getMessage()}"); - } - } - } - $this->dbForProject->purgeCachedCollection($id); - break; - - case 'notifications': - if ($collectionType === 'console' && $notificationsCollectionExists) { - foreach (['firstSeen', 'lastSeen'] as $attribute) { - try { - $this->createAttributeFromCollection($this->dbForProject, $id, $attribute); - } catch (Throwable $th) { - Console::warning("Failed to create attribute \"{$attribute}\" in collection {$id}: {$th->getMessage()}"); - } - } - } - $this->dbForProject->purgeCachedCollection($id); - break; - case 'rules': if ($collectionType === 'console') { try { @@ -495,17 +453,6 @@ class V24 extends Migration $document->setAttribute('resourceInternalId', $projectInternalId); } break; - case 'schedules': - if (empty($document->getAttribute('projectInternalId'))) { - $projectId = $document->getAttribute('projectId', ''); - if ($projectId !== '') { - $project = $this->dbForProject->getDocument('projects', $projectId); - if (!$project->isEmpty()) { - $document->setAttribute('projectInternalId', $project->getSequence()); - } - } - } - break; default: break; } diff --git a/src/Appwrite/Platform/Appwrite.php b/src/Appwrite/Platform/Appwrite.php index f402050391..4bf3ed4768 100644 --- a/src/Appwrite/Platform/Appwrite.php +++ b/src/Appwrite/Platform/Appwrite.php @@ -11,7 +11,6 @@ use Appwrite\Platform\Modules\Databases; use Appwrite\Platform\Modules\Functions; use Appwrite\Platform\Modules\Health; use Appwrite\Platform\Modules\Migrations; -use Appwrite\Platform\Modules\Notifications; use Appwrite\Platform\Modules\Organization; use Appwrite\Platform\Modules\Presences; use Appwrite\Platform\Modules\Project; @@ -37,7 +36,6 @@ class Appwrite extends Platform $this->addModule(new Presences\Module()); $this->addModule(new Functions\Module()); $this->addModule(new Health\Module()); - $this->addModule(new Notifications\Module()); $this->addModule(new Sites\Module()); $this->addModule(new Console\Module()); $this->addModule(new Proxy\Module()); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php index 303bf1484b..639b9ae2aa 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php @@ -325,7 +325,6 @@ class Create extends Base 'resourceInternalId' => $execution->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $scheduledAt, 'data' => $data, 'active' => true, diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index e674b935c9..5222cba0b0 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -276,7 +276,6 @@ class Create extends Base 'resourceInternalId' => $function->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $function->getAttribute('schedule'), 'active' => false, ])) diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index 5a6f3f8045..f45a762708 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -325,7 +325,6 @@ class Update extends Base 'resourceInternalId' => $function->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $function->getAttribute('schedule'), 'active' => false, ])) @@ -338,7 +337,6 @@ class Update extends Base } $schedule - ->setAttribute('projectInternalId', $project->getSequence()) ->setAttribute('resourceUpdatedAt', DateTime::now()) ->setAttribute('schedule', $function->getAttribute('schedule')) ->setAttribute('active', !empty($function->getAttribute('schedule')) && !empty($function->getAttribute('deploymentId'))); diff --git a/src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Failed/Get.php b/src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Failed/Get.php index 2746886bee..f0dff0a811 100644 --- a/src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Failed/Get.php +++ b/src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Failed/Get.php @@ -12,7 +12,6 @@ use Appwrite\Event\Publisher\Func as FunctionPublisher; use Appwrite\Event\Publisher\Mail as MailPublisher; use Appwrite\Event\Publisher\Messaging as MessagingPublisher; use Appwrite\Event\Publisher\Migration as MigrationPublisher; -use Appwrite\Event\Publisher\Notification as NotificationPublisher; use Appwrite\Event\Publisher\Screenshot; use Appwrite\Event\Publisher\StatsResources as StatsResourcesPublisher; use Appwrite\Event\Publisher\Usage as UsagePublisher; @@ -73,7 +72,6 @@ class Get extends Base System::getEnv('_APP_SCREENSHOTS_QUEUE_NAME', Event::SCREENSHOTS_QUEUE_NAME), System::getEnv('_APP_MESSAGING_QUEUE_NAME', Event::MESSAGING_QUEUE_NAME), System::getEnv('_APP_MIGRATIONS_QUEUE_NAME', Event::MIGRATIONS_QUEUE_NAME), - System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME), ]), 'The name of the queue', enum: new Enum(name: 'HealthQueueName')) ->param('threshold', 5000, new Integer(true), 'Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000.', true) ->inject('response') @@ -90,7 +88,6 @@ class Get extends Base ->inject('publisherForMessaging') ->inject('publisherForMigrations') ->inject('publisherForScreenshots') - ->inject('publisherForNotifications') ->callback($this->action(...)); } @@ -111,7 +108,6 @@ class Get extends Base MessagingPublisher $publisherForMessaging, MigrationPublisher $publisherForMigrations, Screenshot $publisherForScreenshots, - NotificationPublisher $publisherForNotifications, ): void { $threshold = (int) $threshold; @@ -129,7 +125,6 @@ class Get extends Base System::getEnv('_APP_SCREENSHOTS_QUEUE_NAME', Event::SCREENSHOTS_QUEUE_NAME) => $publisherForScreenshots, System::getEnv('_APP_MESSAGING_QUEUE_NAME', Event::MESSAGING_QUEUE_NAME) => $publisherForMessaging, System::getEnv('_APP_MIGRATIONS_QUEUE_NAME', Event::MIGRATIONS_QUEUE_NAME) => $publisherForMigrations, - System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME) => $publisherForNotifications, default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown queue name: ' . $name), }; $failed = $queue->getSize(failed: true); diff --git a/src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Notifications/Get.php b/src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Notifications/Get.php deleted file mode 100644 index 50337cf9d0..0000000000 --- a/src/Appwrite/Platform/Modules/Health/Http/Health/Queue/Notifications/Get.php +++ /dev/null @@ -1,60 +0,0 @@ -setHttpMethod(Base::HTTP_REQUEST_METHOD_GET) - ->setHttpPath('/v1/health/queue/notifications') - ->desc('Get notifications queue') - ->groups(['api', 'health']) - ->label('scope', 'health.read') - ->label('sdk', new Method( - namespace: 'health', - group: 'queue', - name: 'getQueueNotifications', - description: '/docs/references/health/get-queue-notifications.md', - auth: [AuthType::ADMIN, AuthType::KEY], - responses: [ - new SDKResponse( - code: Response::STATUS_CODE_OK, - model: Response::MODEL_HEALTH_QUEUE, - ) - ], - contentType: ContentType::JSON - )) - ->param('threshold', 5000, new Integer(true), 'Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000.', true) - ->inject('publisherForNotifications') - ->inject('response') - ->callback($this->action(...)); - } - - public function action(int|string $threshold, NotificationPublisher $publisherForNotifications, Response $response): void - { - $threshold = (int) $threshold; - - $size = $publisherForNotifications->getSize(); - - $this->assertQueueThreshold($size, $threshold); - - $response->dynamic(new Document(['size' => $size]), Response::MODEL_HEALTH_QUEUE); - } -} diff --git a/src/Appwrite/Platform/Modules/Health/Services/Http.php b/src/Appwrite/Platform/Modules/Health/Services/Http.php index a6acbcb4d4..54c6f9ad6d 100644 --- a/src/Appwrite/Platform/Modules/Health/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Health/Services/Http.php @@ -19,7 +19,6 @@ use Appwrite\Platform\Modules\Health\Http\Health\Queue\Logs\Get as GetQueueLogs; use Appwrite\Platform\Modules\Health\Http\Health\Queue\Mails\Get as GetQueueMails; use Appwrite\Platform\Modules\Health\Http\Health\Queue\Messaging\Get as GetQueueMessaging; use Appwrite\Platform\Modules\Health\Http\Health\Queue\Migrations\Get as GetQueueMigrations; -use Appwrite\Platform\Modules\Health\Http\Health\Queue\Notifications\Get as GetQueueNotifications; use Appwrite\Platform\Modules\Health\Http\Health\Queue\StatsResources\Get as GetQueueStatsResources; use Appwrite\Platform\Modules\Health\Http\Health\Queue\StatsUsage\Get as GetQueueUsage; use Appwrite\Platform\Modules\Health\Http\Health\Queue\Webhooks\Get as GetQueueWebhooks; @@ -57,7 +56,6 @@ class Http extends Service $this->addAction(GetQueueMails::getName(), new GetQueueMails()); $this->addAction(GetQueueMessaging::getName(), new GetQueueMessaging()); $this->addAction(GetQueueMigrations::getName(), new GetQueueMigrations()); - $this->addAction(GetQueueNotifications::getName(), new GetQueueNotifications()); $this->addAction(GetQueueFunctions::getName(), new GetQueueFunctions()); $this->addAction(GetQueueStatsResources::getName(), new GetQueueStatsResources()); $this->addAction(GetQueueUsage::getName(), new GetQueueUsage()); diff --git a/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Logos/Appwrite/Get.php b/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Logos/Appwrite/Get.php deleted file mode 100644 index 7bb99c7ceb..0000000000 --- a/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Logos/Appwrite/Get.php +++ /dev/null @@ -1,209 +0,0 @@ -setHttpMethod(Action::HTTP_REQUEST_METHOD_GET) - ->setHttpPath('/v1/notifications/logos/appwrite') - ->desc('Get notification logo') - ->groups(['api', 'notifications']) - ->label('scope', 'public') - ->label('sdk', new Method( - namespace: 'notifications', - group: 'logos', - name: 'getLogo', - description: '/docs/references/notifications/get-logo.md', - auth: [], - type: MethodType::LOCATION, - responses: [ - new SDKResponse( - code: Response::STATUS_CODE_OK, - model: Response::MODEL_NONE, - ), - ], - contentType: ContentType::IMAGE_SVG, - )) - ->param('jwt', '', new Text(2048, 0), 'Tracking token.', true) - ->param('theme', 'system', new WhiteList(['system', 'light', 'dark']), 'Logo color theme.', true) - ->inject('request') - ->inject('response') - ->inject('dbForPlatform') - ->inject('authorization') - ->inject('publisherForAudits') - ->callback($this->action(...)); - } - - public function action( - string $jwt, - string $theme, - Request $request, - Response $response, - Database $dbForPlatform, - Authorization $authorization, - AuditPublisher $publisherForAudits, - ): void { - $secret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET'); - - if (!empty($secret) && $jwt !== '') { - try { - $decoder = new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0); - $decoded = $decoder->decode($jwt); - - $result = $authorization->skip(fn () => $this->trackView($decoded, $dbForPlatform)); - - if ($result !== null) { - $this->logView( - $result['notification'], - $result['project'], - $result['seenAt'], - $request, - $publisherForAudits, - ); - } - } catch (\Throwable) { - // Always return the logo and avoid exposing token validity. - } - } - - $response - ->setContentType('image/svg+xml') - ->addHeader('Cache-Control', 'no-store') - ->send($this->renderLogo($theme)); - } - - /** - * @return array{notification: Document, project: Document, seenAt: string}|null - */ - private function trackView(array $decoded, Database $dbForPlatform): ?array - { - if ( - !isset($decoded['messageId'], $decoded['recipientHash'], $decoded['channel'], $decoded['projectId'], $decoded['purpose']) - || $decoded['purpose'] !== 'notification_track' - ) { - return null; - } - - $notifications = $dbForPlatform->find('notifications', [ - Query::equal('messageId', [(string) $decoded['messageId']]), - Query::equal('channel', [(string) $decoded['channel']]), - Query::equal('recipientHash', [(string) $decoded['recipientHash']]), - Query::limit(1), - ]); - - if (empty($notifications)) { - return null; - } - - $notification = $notifications[0]; - if ( - $notification->getAttribute('projectId') !== (string) $decoded['projectId'] - || (isset($decoded['projectInternalId']) && $notification->getAttribute('projectInternalId') !== (string) $decoded['projectInternalId']) - ) { - return null; - } - - $seenAt = DateTime::now(); - $updates = [ - 'read' => true, - 'lastSeen' => $seenAt, - ]; - - if (empty($notification->getAttribute('firstSeen'))) { - $updates['firstSeen'] = $seenAt; - } - - $updated = $dbForPlatform->updateDocument('notifications', $notification->getId(), new Document($updates)); - $project = $dbForPlatform->getDocument('projects', $notification->getAttribute('projectId')); - - if ($project->isEmpty()) { - $project = new Document([ - '$id' => 'console', - '$sequence' => 'console', - ]); - } - - return [ - 'notification' => $updated, - 'project' => $project, - 'seenAt' => $seenAt, - ]; - } - - private function logView(Document $notification, Document $project, string $seenAt, Request $request, AuditPublisher $publisherForAudits): void - { - $publisherForAudits->enqueue(new AuditMessage( - event: 'notification.view', - payload: [ - 'notificationId' => $notification->getId(), - 'messageId' => $notification->getAttribute('messageId', ''), - 'channel' => $notification->getAttribute('channel', ''), - 'projectId' => $notification->getAttribute('projectId', ''), - 'firstSeen' => $notification->getAttribute('firstSeen'), - 'lastSeen' => $notification->getAttribute('lastSeen'), - 'seenAt' => $seenAt, - ], - project: $project, - user: new Document([ - '$id' => $notification->getAttribute('resourceId', ''), - '$sequence' => $notification->getAttribute('resourceInternalId', ''), - 'name' => '', - 'email' => '', - 'type' => ACTOR_TYPE_HIDDEN, - ]), - resource: 'notification/' . $notification->getId(), - mode: APP_MODE_DEFAULT, - ip: $request->getIP(), - userAgent: $request->getUserAgent(''), - hostname: $request->getHostname(), - )); - } - - private function renderLogo(string $theme): string - { - $style = match ($theme) { - 'light' => '.wordmark { fill: #19191C; }', - 'dark' => '.wordmark { fill: #F5F5F7; }', - default => '.wordmark { fill: #19191C; } @media (prefers-color-scheme: dark) { .wordmark { fill: #F5F5F7; } }', - }; - - return << - - - - Appwrite - -SVG; - } -} diff --git a/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Update.php b/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Update.php deleted file mode 100644 index 9ca7b6b683..0000000000 --- a/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/Update.php +++ /dev/null @@ -1,87 +0,0 @@ -setHttpMethod(Action::HTTP_REQUEST_METHOD_PATCH) - ->setHttpPath('/v1/notifications/:notificationId') - ->desc('Update notification') - ->groups(['api', 'notifications']) - ->label('scope', 'account') - ->label('sdk', new Method( - namespace: 'notifications', - group: null, - name: 'update', - description: '/docs/references/notifications/update-notification.md', - auth: [AuthType::SESSION, AuthType::JWT], - responses: [ - new SDKResponse( - code: Response::STATUS_CODE_OK, - model: Response::MODEL_NOTIFICATION, - ) - ] - )) - ->param('notificationId', '', new UID(), 'Notification ID.') - ->param('read', null, new Boolean(), 'Notification read status.') - ->inject('response') - ->inject('dbForPlatform') - ->inject('authorization') - ->inject('project') - ->inject('user') - ->callback($this->action(...)); - } - - public function action( - string $notificationId, - bool $read, - Response $response, - Database $dbForPlatform, - Authorization $authorization, - Document $project, - Document $user, - ): void { - if ($project->getId() !== 'console') { - throw new Exception(Exception::USER_UNAUTHORIZED); - } - - $notification = $dbForPlatform->getDocument('notifications', $notificationId); - - if ($notification->isEmpty()) { - $exists = $authorization->skip(fn () => !$dbForPlatform->getDocument('notifications', $notificationId)->isEmpty()); - if ($exists) { - throw new Exception(Exception::USER_UNAUTHORIZED); - } - throw new Exception(Exception::DOCUMENT_NOT_FOUND); - } - - $updated = $dbForPlatform->updateDocument('notifications', $notificationId, new Document([ - 'read' => $read, - ])); - - $response->dynamic($updated, Response::MODEL_NOTIFICATION); - } -} diff --git a/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/XList.php b/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/XList.php deleted file mode 100644 index 558190d99a..0000000000 --- a/src/Appwrite/Platform/Modules/Notifications/Http/Notifications/XList.php +++ /dev/null @@ -1,118 +0,0 @@ -setHttpMethod(Action::HTTP_REQUEST_METHOD_GET) - ->setHttpPath('/v1/notifications') - ->desc('List notifications') - ->groups(['api', 'notifications']) - ->label('scope', 'account') - ->label('sdk', new Method( - namespace: 'notifications', - group: null, - name: 'list', - description: '/docs/references/notifications/list-notifications.md', - auth: [AuthType::SESSION, AuthType::JWT], - responses: [ - new SDKResponse( - code: Response::STATUS_CODE_OK, - model: Response::MODEL_NOTIFICATION_LIST, - ) - ] - )) - ->param('queries', [], new NotificationQueries(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', NotificationQueries::ALLOWED_ATTRIBUTES), true) - ->inject('response') - ->inject('dbForPlatform') - ->inject('project') - ->inject('user') - ->callback($this->action(...)); - } - - /** - * @param array $queries - */ - public function action( - array $queries, - Response $response, - Database $dbForPlatform, - Document $project, - Document $user - ): void { - if ($project->getId() !== 'console') { - throw new Exception(Exception::USER_UNAUTHORIZED); - } - - try { - $queries = Query::parseQueries($queries); - } catch (QueryException $e) { - throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage()); - } - - $cursor = \array_filter($queries, function ($query) { - return \in_array($query->getMethod(), [Query::TYPE_CURSOR_AFTER, Query::TYPE_CURSOR_BEFORE]); - }); - $cursor = reset($cursor); - if ($cursor) { - /** @var Query $cursor */ - - $validator = new Cursor(); - if (!$validator->isValid($cursor)) { - throw new Exception(Exception::GENERAL_QUERY_INVALID, $validator->getDescription()); - } - - $notificationId = $cursor->getValue(); - $cursorDocument = $dbForPlatform->getDocument('notifications', $notificationId); - - if ($cursorDocument->isEmpty()) { - throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Notification '{$notificationId}' for the 'cursor' value not found."); - } - - $cursor->setValue($cursorDocument); - } - - $queries[] = Query::equal('channel', [NOTIFICATION_TYPE_CONSOLE]); - $queries[] = Query::equal('resourceType', [RESOURCE_TYPE_USERS]); - $queries[] = Query::equal('resourceId', [$user->getId()]); - - $filterQueries = Query::groupByType($queries)['filters']; - - try { - $results = $dbForPlatform->find('notifications', $queries); - $total = $dbForPlatform->count('notifications', $filterQueries, APP_LIMIT_COUNT); - } catch (OrderException $e) { - throw new Exception(Exception::DATABASE_QUERY_ORDER_NULL, "The order attribute '{$e->getAttribute()}' had a null value. Cursor pagination requires all documents order attribute values are non-null."); - } - - $response->dynamic(new Document([ - 'notifications' => $results, - 'total' => $total, - ]), Response::MODEL_NOTIFICATION_LIST); - } -} diff --git a/src/Appwrite/Platform/Modules/Notifications/Module.php b/src/Appwrite/Platform/Modules/Notifications/Module.php deleted file mode 100644 index f4e1c574cc..0000000000 --- a/src/Appwrite/Platform/Modules/Notifications/Module.php +++ /dev/null @@ -1,14 +0,0 @@ -addService('http', new Http()); - } -} diff --git a/src/Appwrite/Platform/Modules/Notifications/Services/Http.php b/src/Appwrite/Platform/Modules/Notifications/Services/Http.php deleted file mode 100644 index 91700ca125..0000000000 --- a/src/Appwrite/Platform/Modules/Notifications/Services/Http.php +++ /dev/null @@ -1,21 +0,0 @@ -type = Service::TYPE_HTTP; - - $this - ->addAction(ListNotifications::getName(), new ListNotifications()) - ->addAction(UpdateNotification::getName(), new UpdateNotification()) - ->addAction(GetAppwriteLogo::getName(), new GetAppwriteLogo()); - } -} diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Labels/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Labels/Update.php index 76c47a32f8..8a3506eb13 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Labels/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Labels/Update.php @@ -71,7 +71,6 @@ class Update extends Action $labels = (array) \array_values(\array_unique($labels)); $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document(['labels' => $labels]))); - $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); $response->dynamic($project, Response::MODEL_PROJECT); } diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Create.php b/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Create.php index 759dd931c0..f4002c60ef 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Create.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Create.php @@ -101,7 +101,6 @@ class Create extends Action ]); $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); - $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); $queueForEvents->setParam('number', $number); diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Delete.php b/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Delete.php index f65a955b3d..0fb23e1764 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Delete.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Delete.php @@ -95,7 +95,6 @@ class Delete extends Action ]); $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); - $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); $queueForEvents->setParam('number', $number); diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Update.php index f2b618c39e..48b90a1b97 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/MockPhone/Update.php @@ -97,7 +97,6 @@ class Update extends Action ]); $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); - $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); $queueForEvents->setParam('number', $number); diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Team/Update.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Team/Update.php index d2f7d5a29d..ab92d1a15f 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Team/Update.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Team/Update.php @@ -78,7 +78,6 @@ class Update extends Action 'teamInternalId' => $team->getSequence(), '$permissions' => $permissions, ])); - $dbForPlatform->purgeCachedDocument('projects', $project->getId()); $installations = $dbForPlatform->find('installations', [ Query::equal('projectInternalId', [$project->getSequence()]), diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Update.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Update.php index c633a7adbf..f6df843d07 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Update.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Update.php @@ -72,7 +72,6 @@ class Update extends Action ->setAttribute('legalAddress', $legalAddress) ->setAttribute('legalTaxId', $legalTaxId) ->setAttribute('search', implode(' ', [$projectId, $name]))); - $dbForPlatform->purgeCachedDocument('projects', $project->getId()); $response->dynamic($project, Response::MODEL_PROJECT); } diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Create.php index 0d433ab5d9..7cf13c5ca2 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Create.php @@ -132,7 +132,6 @@ class Create extends Action 'resourceInternalId' => $resource->getSequence(), 'resourceUpdatedAt' => DateTime::now(), 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), 'schedule' => $schedule, 'active' => $active, ]; diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Get.php b/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Get.php index 05c4a925db..d14d4c361d 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Get.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Schedules/Get.php @@ -67,12 +67,7 @@ class Get extends Action throw new Exception(Exception::SCHEDULE_NOT_FOUND); } - $projectInternalId = $schedule->getAttribute('projectInternalId'); - - if ( - $schedule->getAttribute('projectId') !== $project->getId() - || ($projectInternalId !== null && $projectInternalId !== '' && $projectInternalId !== $project->getSequence()) - ) { + if ($schedule->getAttribute('projectId') !== $project->getId()) { throw new Exception(Exception::SCHEDULE_NOT_FOUND); } diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Schedules/XList.php b/src/Appwrite/Platform/Modules/Projects/Http/Schedules/XList.php index 7f82162a2c..66879f798f 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Schedules/XList.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Schedules/XList.php @@ -77,10 +77,6 @@ class XList extends Action } $queries[] = Query::equal('projectId', [$project->getId()]); - $queries[] = Query::or([ - Query::equal('projectInternalId', [$project->getSequence()]), - Query::isNull('projectInternalId'), - ]); $cursor = Query::getCursorQueries($queries, false); $cursor = \reset($cursor); @@ -94,11 +90,7 @@ class XList extends Action $scheduleId = $cursor->getValue(); $cursorDocument = $dbForPlatform->getDocument('schedules', $scheduleId); - if ( - $cursorDocument->isEmpty() - || $cursorDocument->getAttribute('projectId') !== $project->getId() - || !$this->matchesProjectInternalId($cursorDocument, $project) - ) { + if ($cursorDocument->isEmpty()) { throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Schedule '{$scheduleId}' for the 'cursor' value not found."); } @@ -119,13 +111,4 @@ class XList extends Action 'total' => $total, ]), Response::MODEL_SCHEDULE_LIST); } - - private function matchesProjectInternalId(Document $schedule, Document $project): bool - { - $projectInternalId = $schedule->getAttribute('projectInternalId'); - - return $projectInternalId === null - || $projectInternalId === '' - || $projectInternalId === $project->getSequence(); - } } diff --git a/src/Appwrite/Platform/Services/Workers.php b/src/Appwrite/Platform/Services/Workers.php index 5af3d078de..fa77725f7a 100644 --- a/src/Appwrite/Platform/Services/Workers.php +++ b/src/Appwrite/Platform/Services/Workers.php @@ -10,7 +10,6 @@ use Appwrite\Platform\Workers\Functions; use Appwrite\Platform\Workers\Mails; use Appwrite\Platform\Workers\Messaging; use Appwrite\Platform\Workers\Migrations; -use Appwrite\Platform\Workers\Notifications; use Appwrite\Platform\Workers\StatsResources; use Appwrite\Platform\Workers\StatsUsage; use Appwrite\Platform\Workers\Webhooks; @@ -29,7 +28,6 @@ class Workers extends Service ->addAction(Functions::getName(), new Functions()) ->addAction(Mails::getName(), new Mails()) ->addAction(Messaging::getName(), new Messaging()) - ->addAction(Notifications::getName(), new Notifications()) ->addAction(Webhooks::getName(), new Webhooks()) ->addAction(StatsUsage::getName(), new StatsUsage()) ->addAction(Migrations::getName(), new Migrations()) diff --git a/src/Appwrite/Platform/Workers/Deletes.php b/src/Appwrite/Platform/Workers/Deletes.php index 403e695603..1ac808c682 100644 --- a/src/Appwrite/Platform/Workers/Deletes.php +++ b/src/Appwrite/Platform/Workers/Deletes.php @@ -788,17 +788,6 @@ class Deletes extends Action Console::error('Failed to delete schedules: ' . $th->getMessage()); } - // Delete Notifications - try { - $this->deleteByGroup('notifications', [ - Query::equal('projectId', [$projectId]), - Query::equal('projectInternalId', [$projectInternalId]), - Query::orderAsc() - ], $dbForPlatform); - } catch (Throwable $th) { - Console::error('Failed to delete notifications: ' . $th->getMessage()); - } - // Delete Advisor insights try { $this->deleteByGroup('insights', [ diff --git a/src/Appwrite/Platform/Workers/Notifications.php b/src/Appwrite/Platform/Workers/Notifications.php deleted file mode 100644 index 04f705e2d1..0000000000 --- a/src/Appwrite/Platform/Workers/Notifications.php +++ /dev/null @@ -1,661 +0,0 @@ - - */ - protected array $richTextParams = [ - 'b' => '', - '/b' => '', - ]; - - public static function getName(): string - { - return 'notifications'; - } - - public function __construct() - { - $this - ->desc('Notifications worker') - ->inject('message') - ->inject('project') - ->inject('register') - ->inject('dbForPlatform') - ->inject('log') - ->callback($this->action(...)); - } - - public function action(Message $message, Document $project, Registry $register, Database $dbForPlatform, Log $log): void - { - if (\class_exists(Runtime::class)) { - Runtime::setHookFlags(SWOOLE_HOOK_ALL ^ SWOOLE_HOOK_TCP); - } - $payload = $message->getPayload(); - - if (empty($payload)) { - throw new Exception('Missing payload'); - } - - $deduplicationKey = $payload['deduplicationKey'] ?? ''; - $messageId = $deduplicationKey !== '' ? \md5($deduplicationKey) : ''; - - $recipients = $this->resolveRecipients($payload); - if (empty($recipients)) { - throw new Exception('No recipients in payload'); - } - - $failure = null; - foreach ($recipients as $recipient) { - $recipient = $this->normalizeRecipient($recipient, $project); - $channel = $recipient['channel']; - - if ($messageId !== '') { - if ($channel === NOTIFICATION_TYPE_CONSOLE) { - $this->validateConsoleRecipient($recipient); - } - $this->validateAlertResource($recipient); - } - - if ($messageId !== '' && $this->alreadyDelivered($dbForPlatform, self::buildAlertId($messageId, $recipient))) { - $log->addTag('dedup', 'hit'); - $log->addTag('channel', $channel); - continue; - } - - try { - $alertId = $this->dispatch($recipient, $messageId, $payload, $project, $register, $dbForPlatform, $log); - if ($messageId !== '' && $channel === NOTIFICATION_TYPE_WEBHOOK && $alertId === null) { - $this->persistAlert($dbForPlatform, $messageId, $recipient, $payload, $project); - } - } catch (Throwable $error) { - $log->addTag('channel', $channel); - $log->addTag('error', $error->getMessage()); - $failure ??= $error; - } - } - - if ($failure !== null) { - throw $failure; - } - } - - /** - * @return array - */ - private function resolveRecipients(array $payload): array - { - $recipients = $payload['recipients'] ?? []; - if (!empty($recipients)) { - return $recipients; - } - - $address = $payload['recipient'] ?? ''; - if ($address === '') { - return []; - } - - return [['address' => $address, 'channel' => NOTIFICATION_TYPE_EMAIL]]; - } - - /** - * @param array{address: string, channel: string, signatureKey?: string, resourceType?: string, resourceId?: string, resourceInternalId?: string, parentResourceType?: string, parentResourceId?: string, parentResourceInternalId?: string} $recipient - * @return array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} - */ - private function normalizeRecipient(array $recipient, Document $project): array - { - $recipient['resourceType'] = $recipient['resourceType'] ?? ''; - $recipient['resourceId'] = $recipient['resourceId'] ?? ''; - $recipient['resourceInternalId'] = $recipient['resourceInternalId'] ?? ''; - $recipient['parentResourceType'] = $recipient['parentResourceType'] ?? RESOURCE_TYPE_PROJECTS; - $recipient['parentResourceId'] = $recipient['parentResourceId'] ?? (string) $project->getId(); - $recipient['parentResourceInternalId'] = $recipient['parentResourceInternalId'] ?? (string) $project->getSequence(); - - if ( - $recipient['channel'] === NOTIFICATION_TYPE_CONSOLE - && $recipient['resourceId'] === '' - ) { - $recipient['resourceType'] = RESOURCE_TYPE_USERS; - $recipient['resourceId'] = $recipient['address']; - } - - foreach (['resourceType', 'resourceId', 'resourceInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'] as $key) { - $recipient[$key] = (string) $recipient[$key]; - } - - return $recipient; - } - - private function alreadyDelivered(Database $dbForPlatform, string $alertId): bool - { - return !$dbForPlatform->getDocument('notifications', $alertId)->isEmpty(); - } - - /** - * Dispatch a single recipient through the channel-appropriate adapter. - * - * Returns the alertId when the dispatcher (or its adapter) has already - * persisted an alert row, so the action loop knows to skip persistence. - * Returns null when persistence is the caller's responsibility. - * - * @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - protected function dispatch( - array $recipient, - string $messageId, - array $payload, - Document $project, - Registry $register, - Database $dbForPlatform, - Log $log, - ): ?string { - $channel = $recipient['channel']; - - return match ($channel) { - NOTIFICATION_TYPE_EMAIL => $this->dispatchEmail($recipient, $messageId, $payload, $project, $register, $dbForPlatform, $log), - NOTIFICATION_TYPE_CONSOLE => $this->dispatchConsole($recipient, $messageId, $payload, $project, $dbForPlatform), - NOTIFICATION_TYPE_WEBHOOK => $this->dispatchWebhook($recipient, $payload, $log), - default => throw new Exception('Unsupported notification channel: ' . $channel), - }; - } - - /** - * @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - protected function dispatchEmail( - array $recipient, - string $messageId, - array $payload, - Document $project, - Registry $register, - Database $dbForPlatform, - Log $log, - ): ?string { - $address = $recipient['address']; - $smtp = $this->resolveSmtpConfig($project, $payload); - - if (empty($smtp) && empty(System::getEnv('_APP_SMTP_HOST'))) { - $log->addTag('email_skipped', 'no_smtp'); - throw new Exception('Skipped mail processing. No SMTP configuration has been set.'); - } - - $type = empty($smtp) ? 'cloud' : 'smtp'; - $log->addTag('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; - $name = $payload['name'] ?? ''; - $body = $payload['body'] ?? ''; - $preview = $payload['preview'] ?? ''; - - $variables['subject'] = $subject; - $variables['heading'] = $variables['heading'] ?? $subject; - $variables['year'] = \date('Y'); - - $attachment = $payload['attachment'] ?? []; - $bodyTemplate = $payload['bodyTemplate'] ?? ''; - if (empty($bodyTemplate)) { - $bodyTemplate = $payload['template'] ?? ''; - } - if (empty($bodyTemplate)) { - $bodyTemplate = __DIR__ . '/../../../../app/config/locale/templates/email-base.tpl'; - } - - $bodyTemplate = Template::fromFile($bodyTemplate); - $bodyTemplate->setParam('{{body}}', $body, escapeHtml: false); - foreach ($variables as $key => $value) { - $bodyTemplate->setParam('{{' . $key . '}}', $value, escapeHtml: $key !== 'redirect'); - } - foreach ($this->richTextParams as $key => $value) { - $bodyTemplate->setParam('{{' . $key . '}}', $value, escapeHtml: false); - } - - $previewWhitespace = ''; - if (!empty($preview)) { - $previewTemplate = Template::fromString($preview); - foreach ($variables as $key => $value) { - $previewTemplate->setParam('{{' . $key . '}}', $value); - } - $preview = \strip_tags($previewTemplate->render()); - - $previewLen = \strlen($preview); - if ($previewLen < $this->previewMaxLen) { - $previewWhitespace = \str_repeat($this->whitespaceCodes, $this->previewMaxLen - $previewLen); - } - } - - $bodyTemplate->setParam('{{preview}}', $preview); - $bodyTemplate->setParam('{{previewWhitespace}}', $previewWhitespace, false); - - $body = $bodyTemplate->render(); - - $subjectTemplate = Template::fromString($subject); - foreach ($variables as $key => $value) { - $subjectTemplate->setParam('{{' . $key . '}}', $value); - } - $subject = \strip_tags($subjectTemplate->render()); - - $recipientHash = self::buildRecipientHash($recipient); - $trackingSecret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET'); - if ($messageId !== '' && !empty($trackingSecret)) { - $body = $this->injectTrackingLogo($body, $messageId, $recipient['channel'], $recipientHash, $project, $trackingSecret); - } - - /** @var EmailAdapter $adapter */ - $adapter = empty($smtp) - ? $register->get('smtp') - : new SMTP( - host: $smtp['host'], - port: (int) $smtp['port'], - username: $smtp['username'] ?? '', - password: $smtp['password'] ?? '', - smtpSecure: $smtp['secure'] ?? '', - smtpAutoTLS: false, - xMailer: 'Appwrite Mailer', - timeout: 10, - keepAlive: true, - timelimit: 30, - ); - - $defaultFromEmail = System::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM); - $defaultFromName = \urldecode(System::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server')); - - $fromEmail = !empty($smtp) ? ($smtp['senderEmail'] ?? $defaultFromEmail) : $defaultFromEmail; - $fromName = !empty($smtp) ? ($smtp['senderName'] ?? $defaultFromName) : $defaultFromName; - $replyTo = $defaultFromEmail; - $replyToName = $defaultFromName; - - $customMailOptions = $payload['customMailOptions'] ?? []; - if (!\is_array($customMailOptions)) { - $customMailOptions = []; - } - - if (!empty($customMailOptions['senderEmail'])) { - $fromEmail = (string) $customMailOptions['senderEmail']; - } - if (!empty($customMailOptions['senderName'])) { - $fromName = (string) $customMailOptions['senderName']; - } - - if (!empty($customMailOptions['replyToEmail']) || !empty($customMailOptions['replyToName'])) { - $replyTo = (string) ($customMailOptions['replyToEmail'] ?? $replyTo); - $replyToName = (string) ($customMailOptions['replyToName'] ?? $replyToName); - } elseif (!empty($smtp)) { - $smtpReplyToEmail = $smtp['replyToEmail'] ?? $smtp['replyTo'] ?? ''; - $replyTo = !empty($smtpReplyToEmail) ? $smtpReplyToEmail : ($smtp['senderEmail'] ?? $replyTo); - $replyToName = !empty($smtp['replyToName']) ? $smtp['replyToName'] : ($smtp['senderName'] ?? $replyToName); - } - - $attachments = null; - if (!empty($attachment['content'] ?? '')) { - $attachments = [ - new Attachment( - name: $attachment['filename'] ?? 'unknown.file', - path: '', - type: $attachment['type'] ?? 'plain/text', - content: \base64_decode($attachment['content']), - ), - ]; - } - - $emailMessage = new EmailMessage( - to: [['email' => $address, 'name' => $name]], - subject: $subject, - content: $body, - fromName: $fromName, - fromEmail: $fromEmail, - replyToName: $replyToName, - replyToEmail: $replyTo, - attachments: $attachments, - html: true, - ); - - try { - $adapter->send($emailMessage); - } catch (Throwable $error) { - throw new Exception('Error sending notification: ' . $error->getMessage(), $type === 'smtp' ? 401 : 500); - } - - if ($messageId !== '') { - return $this->persistAlert($dbForPlatform, $messageId, $recipient, $payload, $project); - } - - return null; - } - - /** - * @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - protected function dispatchConsole(array $recipient, string $messageId, array $payload, Document $project, Database $dbForPlatform): ?string - { - $this->validateConsoleRecipient($recipient); - - $params = $payload['templateParams'] ?? ($payload['variables'] ?? []); - $title = self::renderText($payload['subject'] ?? '', $params); - $body = self::renderText($payload['preview'] ?? '', $params); - if ($body === '') { - $body = self::renderText($payload['body'] ?? '', $params); - } - - $alertId = $messageId !== '' ? self::buildAlertId($messageId, $recipient) : null; - $recipientHash = $messageId !== '' ? self::buildRecipientHash($recipient) : null; - - $consoleRecipient = [ - 'address' => $recipient['address'], - 'resourceType' => $recipient['resourceType'], - 'resourceId' => $recipient['resourceId'], - 'resourceInternalId' => $recipient['resourceInternalId'], - 'parentResourceType' => $recipient['parentResourceType'], - 'parentResourceId' => $recipient['parentResourceId'], - 'parentResourceInternalId' => $recipient['parentResourceInternalId'], - ]; - if ($alertId !== null) { - $consoleRecipient['alertId'] = $alertId; - $consoleRecipient['recipientHash'] = $recipientHash; - } - - $consoleMessage = new ConsoleMessage( - recipients: [$consoleRecipient], - title: $title, - body: $body, - type: $payload['type'] ?? 'info', - messageId: $messageId !== '' ? $messageId : null, - projectId: $project->getId(), - projectInternalId: $project->getSequence(), - ); - - $adapter = new ConsoleAdapter($dbForPlatform); - $result = $adapter->send($consoleMessage); - - if (($result['deliveredTo'] ?? 0) === 0) { - $error = $result['results'][0]['error'] ?? 'unknown error'; - throw new Exception('Console alert delivery failed: ' . $error); - } - - return $alertId; - } - - /** - * @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - protected function dispatchWebhook(array $recipient, array $payload, Log $log): ?string - { - $address = $recipient['address']; - $signatureKey = $recipient['signatureKey'] ?? null; - - $body = [ - 'subject' => $payload['subject'] ?? '', - 'body' => $payload['body'] ?? '', - 'template' => $payload['template'] ?? '', - 'params' => $payload['templateParams'] ?? [], - 'project' => \is_array($payload['project'] ?? null) ? ($payload['project']['$id'] ?? null) : null, - 'deduplicationKey' => $payload['deduplicationKey'] ?? '', - 'events' => $payload['events'] ?? [], - ]; - - if ($signatureKey === null || $signatureKey === '') { - $log->addTag('webhook_signed', 'false'); - } - - $message = new WebhookMessage( - urls: [$address], - payload: $body, - signingSecret: $signatureKey, - ); - - $adapter = new WebhookAdapter(); - $result = $adapter->send($message); - - if (($result['deliveredTo'] ?? 0) === 0) { - $error = $result['results'][0]['error'] ?? 'Unknown error'; - throw new Exception('Webhook delivery failed: ' . $error); - } - - // Caller persists the alert AFTER successful dispatch. - return null; - } - - /** - * Persist an alert row. Returns the alertId so callers can reference the row. - * - * Idempotent: on a duplicate composite-key violation the existing - * row's id is returned. - * - * @param array{address: string, channel: string, signatureKey?: string, resourceType?: string, resourceId?: string, resourceInternalId?: string, parentResourceType?: string, parentResourceId?: string, parentResourceInternalId?: string} $recipient - */ - protected function persistAlert(Database $dbForPlatform, string $messageId, array $recipient, array $payload, Document $project): string - { - $recipient = $this->normalizeRecipient($recipient, $project); - - $channel = $recipient['channel']; - - $alertId = self::buildAlertId($messageId, $recipient); - $recipientHash = self::buildRecipientHash($recipient); - - $permissions = $this->buildAlertPermissions($recipient['resourceType'], $recipient['resourceId'], $project->getId()); - if (empty($permissions)) { - $permissions = $payload['permissions'] ?? []; - } - - $params = $payload['templateParams'] ?? ($payload['variables'] ?? []); - $body = self::renderText($payload['preview'] ?? '', $params); - if ($body === '') { - $body = self::renderText($payload['body'] ?? '', $params); - } - - $document = new Document([ - '$id' => $alertId, - '$permissions' => $permissions, - 'messageId' => $messageId, - 'recipientHash' => $recipientHash, - 'type' => $payload['type'] ?? 'info', - 'channel' => $channel, - 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), - 'resourceType' => $recipient['resourceType'], - 'resourceId' => $recipient['resourceId'], - 'resourceInternalId' => $recipient['resourceInternalId'], - 'parentResourceType' => $recipient['parentResourceType'], - 'parentResourceId' => $recipient['parentResourceId'], - 'parentResourceInternalId' => $recipient['parentResourceInternalId'], - 'title' => self::renderText($payload['subject'] ?? '', $params), - 'body' => $body, - 'read' => false, - ]); - - try { - $dbForPlatform->createDocument('notifications', $document); - return $alertId; - } catch (DuplicateException) { - $existing = $dbForPlatform->getDocument('notifications', $alertId); - return $existing->isEmpty() ? $alertId : $existing->getId(); - } - } - - /** - * Build the deterministic alertId composed of the messageId plus a - * recipient hash. - * - * @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - private static function buildAlertId(string $messageId, array $recipient): string - { - return \substr($messageId, 0, 19) . '_' . self::buildRecipientHash($recipient); - } - - /** - * @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - private static function buildRecipientHash(array $recipient): string - { - $channel = $recipient['channel']; - $address = $recipient['address']; - - return \substr(\md5( - $channel - . ':' . $address - . ':' . $recipient['resourceType'] - . ':' . $recipient['resourceId'] - . ':' . $recipient['resourceInternalId'] - . ':' . $recipient['parentResourceType'] - . ':' . $recipient['parentResourceId'] - . ':' . $recipient['parentResourceInternalId'] - ), 0, 16); - } - - /** - * @return array - */ - private function buildAlertPermissions(string $resourceType, string $resourceId, string $projectId): array - { - $permissions = []; - if ($resourceType === RESOURCE_TYPE_USERS) { - $permissions[] = Permission::read(Role::user($resourceId)); - $permissions[] = Permission::update(Role::user($resourceId)); - $permissions[] = Permission::delete(Role::user($resourceId)); - } - if ($resourceType === RESOURCE_TYPE_TEAMS) { - $permissions[] = Permission::read(Role::team($resourceId)); - $permissions[] = Permission::update(Role::team($resourceId, 'owner')); - $permissions[] = Permission::delete(Role::team($resourceId, 'owner')); - if ($projectId !== '') { - $permissions[] = Permission::read(Role::team($resourceId, 'project-' . $projectId . '-owner')); - $permissions[] = Permission::update(Role::team($resourceId, 'project-' . $projectId . '-owner')); - $permissions[] = Permission::delete(Role::team($resourceId, 'project-' . $projectId . '-owner')); - } - } - return $permissions; - } - - /** - * @param array $payload - * @return array - */ - private function resolveSmtpConfig(Document $project, array $payload): array - { - $payloadSmtp = $payload['smtp'] ?? []; - if (\is_array($payloadSmtp) && !empty($payloadSmtp)) { - return $payloadSmtp; - } - - $smtp = $project->getAttribute('smtp', []); - if (!\is_array($smtp) || empty($smtp['enabled'] ?? false)) { - return []; - } - - return [ - 'host' => $smtp['host'] ?? '', - 'port' => $smtp['port'] ?? '', - 'username' => $smtp['username'] ?? '', - 'password' => $smtp['password'] ?? '', - 'secure' => $smtp['secure'] ?? '', - 'senderEmail' => $smtp['senderEmail'] ?? '', - 'senderName' => $smtp['senderName'] ?? '', - 'replyToEmail' => $smtp['replyToEmail'] ?? $smtp['replyTo'] ?? '', - 'replyToName' => $smtp['replyToName'] ?? '', - ]; - } - - private function validateConsoleRecipient(array $recipient): void - { - $validator = new UID(); - - if (!$validator->isValid($recipient['resourceId'])) { - throw new Exception('Invalid console alert resourceId: ' . $validator->getDescription()); - } - } - - /** - * @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - private function validateAlertResource(array $recipient): void - { - foreach (['resourceType', 'resourceId', 'resourceInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'] as $key) { - if ($recipient[$key] === '') { - throw new Exception('Missing notification ' . $key); - } - } - } - - private static function renderText(string $value, array $params): string - { - if ($value !== '' && !empty($params)) { - $template = Template::fromString($value); - foreach ($params as $key => $param) { - $template->setParam('{{' . $key . '}}', (string) $param); - } - $value = $template->render(); - } - - return \trim(\strip_tags($value)); - } - - /** - * Splice a visible tracking logo before the last `` tag (or - * append at the end if the body has no closing tag). The logo URL - * carries a signed JWT identifying the notification recipient, which the - * `/v1/notifications/logos/appwrite` endpoint verifies before marking - * the notification as read and recording view timestamps. - */ - private function injectTrackingLogo(string $body, string $messageId, string $channel, string $recipientHash, Document $project, string $trackingSecret): string - { - $jwt = (new JWT($trackingSecret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0)) - ->encode([ - 'messageId' => $messageId, - 'channel' => $channel, - 'recipientHash' => $recipientHash, - 'projectId' => $project->getId(), - 'projectInternalId' => $project->getSequence(), - 'purpose' => 'notification_track', - ]); - - $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'disabled' ? 'http' : 'https'; - $hostname = System::getEnv('_APP_DOMAIN', 'localhost'); - - $logoUrl = $protocol . '://' . $hostname . '/v1/notifications/logos/appwrite?jwt=' . \urlencode($jwt); - $logo = 'Appwrite logo'; - - // Case-insensitive splice before the LAST . - if (\preg_match('/<\/body\s*>(?!.*<\/body\s*>)/is', $body)) { - return \preg_replace('/<\/body\s*>(?!.*<\/body\s*>)/is', $logo . '$0', $body, 1) ?? ($body . $logo); - } - - return $body . $logo; - } -} diff --git a/src/Appwrite/Platform/Workers/Webhooks.php b/src/Appwrite/Platform/Workers/Webhooks.php index 5466ade630..593fd39767 100644 --- a/src/Appwrite/Platform/Workers/Webhooks.php +++ b/src/Appwrite/Platform/Workers/Webhooks.php @@ -2,9 +2,9 @@ namespace Appwrite\Platform\Workers; -use Appwrite\Event\Message\Notification as NotificationMessage; +use Appwrite\Event\Message\Mail as MailMessage; use Appwrite\Event\Message\Usage as UsageMessage; -use Appwrite\Event\Publisher\Notification as NotificationPublisher; +use Appwrite\Event\Publisher\Mail as MailPublisher; use Appwrite\Event\Publisher\Usage as UsagePublisher; use Appwrite\Network\Validator\PublicHostname; use Appwrite\Template\Template; @@ -37,7 +37,7 @@ class Webhooks extends Action ->inject('message') ->inject('project') ->inject('dbForPlatform') - ->inject('publisherForNotifications') + ->inject('publisherForMails') ->inject('publisherForUsage') ->inject('log') ->inject('plan') @@ -48,14 +48,14 @@ class Webhooks extends Action * @param Message $message * @param Document $project * @param Database $dbForPlatform - * @param NotificationPublisher $publisherForNotifications + * @param MailPublisher $publisherForMails * @param UsagePublisher $publisherForUsage * @param Log $log * @param array $plan * @return void * @throws Exception */ - public function action(Message $message, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, UsagePublisher $publisherForUsage, Log $log, array $plan): void + public function action(Message $message, Document $project, Database $dbForPlatform, MailPublisher $publisherForMails, UsagePublisher $publisherForUsage, Log $log, array $plan): void { $payload = $message->getPayload(); @@ -72,7 +72,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, $publisherForMails, $publisherForUsage, $plan); if ($error !== null) { $errors[] = $error; } @@ -91,12 +91,11 @@ class Webhooks extends Action * @param Document $user * @param Document $project * @param Database $dbForPlatform - * @param NotificationPublisher $publisherForNotifications - * @param UsagePublisher $publisherForUsage + * @param MailPublisher $publisherForMails * @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, MailPublisher $publisherForMails, UsagePublisher $publisherForUsage, array $plan): ?string { if ($webhook->getAttribute('enabled') !== true) { return null; @@ -185,7 +184,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->sendEmailAlert($attempts, $statusCode, $webhook, $project, $dbForPlatform, $publisherForMails, $plan); } $dbForPlatform->updateDocument('webhooks', $webhook->getId(), new Document($updatePayload)); @@ -219,136 +218,65 @@ class Webhooks extends Action * @param Document $webhook * @param Document $project * @param Database $dbForPlatform - * @param NotificationPublisher $publisherForNotifications + * @param MailPublisher $publisherForMails * @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 sendEmailAlert(int $attempts, mixed $statusCode, Document $webhook, Document $project, Database $dbForPlatform, MailPublisher $publisherForMails, array $plan): void { $memberships = $dbForPlatform->find('memberships', [ Query::equal('teamInternalId', [$project->getAttribute('teamInternalId')]), Query::limit(APP_LIMIT_SUBQUERY) ]); - $ownerMemberships = \array_filter( - $memberships, - fn (Document $membership) => self::hasOwnerRole($membership) - ); - - if (empty($ownerMemberships)) { - return; - } - - $userIds = \array_values(\array_unique(\array_filter(\array_map( - fn (Document $membership) => $membership->getAttribute('userId'), - $ownerMemberships - )))); - - if (empty($userIds)) { - return; - } + $userIds = array_column(\array_map(fn ($membership) => $membership->getArrayCopy(), $memberships), 'userId'); $users = $dbForPlatform->find('users', [ Query::equal('$id', $userIds), - Query::limit(APP_LIMIT_SUBQUERY), ]); - if (empty($users)) { - return; - } - $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')); + $template = Template::fromFile(__DIR__ . '/../../../../app/config/locale/templates/email-webhook-failed.tpl'); + $template->setParam('{{webhook}}', $webhook->getAttribute('name')); + $template->setParam('{{project}}', $project->getAttribute('name')); + $template->setParam('{{url}}', $webhook->getAttribute('url')); + $template->setParam('{{error}}', 'The server returned ' . $statusCode . ' status code'); + $template->setParam('{{path}}', "/console/project-$region-$projectId/settings/webhooks/$webhookId"); + $template->setParam('{{attempts}}', $attempts); + + $template->setParam('{{logoUrl}}', $plan['logoUrl'] ?? APP_EMAIL_LOGO_URL); + $template->setParam('{{accentColor}}', $plan['accentColor'] ?? APP_EMAIL_ACCENT_COLOR); + $template->setParam('{{twitterUrl}}', $plan['twitterUrl'] ?? APP_SOCIAL_TWITTER); + $template->setParam('{{discordUrl}}', $plan['discordUrl'] ?? APP_SOCIAL_DISCORD); + $template->setParam('{{githubUrl}}', $plan['githubUrl'] ?? APP_SOCIAL_GITHUB_APPWRITE); + $template->setParam('{{termsUrl}}', $plan['termsUrl'] ?? APP_EMAIL_TERMS_URL); + $template->setParam('{{privacyUrl}}', $plan['privacyUrl'] ?? APP_EMAIL_PRIVACY_URL); + + // TODO: Use setbodyTemplate once #7307 is merged $subject = 'Webhook deliveries have been paused'; - $preview = 'Webhook "' . $webhook->getAttribute('name') . '" has been paused after ' . $attempts . ' failed delivery attempts.'; + $preview = 'Webhook deliveries to your endpoint have been paused.'; + $body = Template::fromFile(__DIR__ . '/../../../../app/config/locale/templates/email-base-styled.tpl'); + + $body + ->setParam('{{subject}}', $subject) + ->setParam('{{message}}', $template->render()) + ->setParam('{{year}}', date("Y")); foreach ($users as $user) { - $email = $user->getAttribute('email'); - $userId = $user->getId(); - - $recipients = [[ - 'address' => $userId, - 'channel' => NOTIFICATION_TYPE_CONSOLE, - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => $userId, - 'resourceInternalId' => (string) $user->getSequence(), - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => $projectId, - 'parentResourceInternalId' => (string) $projectInternalId, - ]]; - - if (!empty($email)) { - $recipients[] = [ - 'address' => $email, - 'channel' => NOTIFICATION_TYPE_EMAIL, - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => $userId, - 'resourceInternalId' => (string) $user->getSequence(), - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => $projectId, - 'parentResourceInternalId' => (string) $projectInternalId, - ]; - } - - $template = Template::fromFile(__DIR__ . '/../../../../app/config/locale/templates/email-webhook-failed.tpl'); - $userName = (string) ($user->getAttribute('name', 'there') ?: 'there'); - $template->setParam('{{user}}', $userName); - $template->setParam('{{webhook}}', $webhook->getAttribute('name')); - $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}}', "/console/project-$region-$projectId/settings/webhooks/$webhookId"); - $template->setParam('{{attempts}}', $attempts); - - $publisherForNotifications->enqueue(new NotificationMessage( + $publisherForMails->enqueue(new MailMessage( project: $project, - recipients: $recipients, - deduplicationKey: 'webhook:' . $webhook->getId() . ':paused:' . $webhook->getUpdatedAt(), + recipient: $user->getAttribute('email'), + name: $user->getAttribute('name', ''), subject: $subject, - bodyTemplate: __DIR__ . '/../../../../app/config/locale/templates/email-base-styled.tpl', - body: $template->render(), + template: MAIL_TEMPLATE_WEBHOOK_FAILED, + body: $body->render(), preview: $preview, - variables: [ - 'logoUrl' => $plan['logoUrl'] ?? APP_EMAIL_LOGO_URL, - 'accentColor' => $plan['accentColor'] ?? APP_EMAIL_ACCENT_COLOR, - 'twitter' => $plan['twitterUrl'] ?? APP_SOCIAL_TWITTER, - 'discord' => $plan['discordUrl'] ?? APP_SOCIAL_DISCORD, - 'github' => $plan['githubUrl'] ?? APP_SOCIAL_GITHUB_APPWRITE, - 'terms' => $plan['termsUrl'] ?? APP_EMAIL_TERMS_URL, - 'privacy' => $plan['privacyUrl'] ?? APP_EMAIL_PRIVACY_URL, - 'platform' => $plan['platformName'] ?? APP_NAME, - ], + variables: ['user' => $user->getAttribute('name', '')], )); } } - - private static function hasOwnerRole(Document $membership): bool - { - $roles = $membership->getAttribute('roles', []); - if (\is_string($roles)) { - $roles = \array_map('trim', \explode(',', $roles)); - } - if (!\is_array($roles)) { - return false; - } - - foreach ($roles as $role) { - if (!\is_string($role)) { - continue; - } - - if (\strtolower($role) === 'owner') { - return true; - } - } - - return false; - } } diff --git a/src/Appwrite/SDK/ContentType.php b/src/Appwrite/SDK/ContentType.php index 7a1671df7a..174c889815 100644 --- a/src/Appwrite/SDK/ContentType.php +++ b/src/Appwrite/SDK/ContentType.php @@ -8,7 +8,6 @@ enum ContentType: string case JSON = 'application/json'; case IMAGE = 'image/*'; case IMAGE_PNG = 'image/png'; - case IMAGE_SVG = 'image/svg+xml'; case MULTIPART = 'multipart/form-data'; case HTML = 'text/html'; case TEXT = 'text/plain'; diff --git a/src/Appwrite/SDK/Specification/Format/OpenAPI3.php b/src/Appwrite/SDK/Specification/Format/OpenAPI3.php index a98cd6f83f..38f81bca69 100644 --- a/src/Appwrite/SDK/Specification/Format/OpenAPI3.php +++ b/src/Appwrite/SDK/Specification/Format/OpenAPI3.php @@ -318,7 +318,6 @@ class OpenAPI3 extends Format 'image/jpeg', 'image/gif', 'image/png', - 'image/svg+xml', 'image/webp', 'image/svg-x', 'image/x-icon', diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Notifications.php b/src/Appwrite/Utopia/Database/Validator/Queries/Notifications.php deleted file mode 100644 index a85609aaa7..0000000000 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Notifications.php +++ /dev/null @@ -1,25 +0,0 @@ -process($message); - } - - protected function process(ConsoleMessage $message): array - { - $response = new Response($this->getType()); - $delivered = 0; - - foreach ($message->getRecipients() as $recipient) { - $resourceType = $recipient['resourceType']; - $resourceId = $recipient['resourceId']; - $key = $resourceType . ':' . $resourceId; - - $messageId = $message->getMessageId(); - $recipientKey = self::buildRecipientKey($recipient); - $recipientHash = $recipient['recipientHash'] ?? \substr(\md5($recipientKey), 0, 16); - $documentId = $messageId !== null - ? ($recipient['alertId'] ?? \substr($messageId, 0, 19) . '_' . $recipientHash) - : ID::unique(); - - try { - $document = new Document([ - '$id' => $documentId, - '$permissions' => $this->buildPermissions($resourceType, $resourceId, $message->getProjectId() ?? ''), - 'messageId' => $messageId, - 'recipientHash' => $recipientHash, - 'type' => $message->getType(), - 'channel' => self::TYPE, - 'projectId' => $message->getProjectId(), - 'projectInternalId' => $message->getProjectInternalId(), - 'resourceType' => $resourceType, - 'resourceId' => $resourceId, - 'resourceInternalId' => $recipient['resourceInternalId'], - 'parentResourceType' => $recipient['parentResourceType'], - 'parentResourceId' => $recipient['parentResourceId'], - 'parentResourceInternalId' => $recipient['parentResourceInternalId'], - 'title' => $message->getTitle(), - 'body' => $message->getBody(), - ]); - - $this->database->createDocument('notifications', $document); - $delivered++; - $response->addResult($key); - } catch (DuplicateException) { - // Idempotent retry: row already exists for this messageId/recipient. - // Treat as a successful (already-delivered) result so the worker - // does not throw and re-queue. - $delivered++; - $response->addResult($key); - } catch (\Throwable $error) { - $response->addResult($key, $error->getMessage()); - } - } - - $response->setDeliveredTo($delivered); - return $response->toArray(); - } - - /** - * @return array - */ - private function buildPermissions(string $resourceType, string $resourceId, string $projectId): array - { - $permissions = []; - if ($resourceType === RESOURCE_TYPE_USERS) { - $permissions[] = Permission::read(Role::user($resourceId)); - $permissions[] = Permission::update(Role::user($resourceId)); - $permissions[] = Permission::delete(Role::user($resourceId)); - } - if ($resourceType === RESOURCE_TYPE_TEAMS) { - $permissions[] = Permission::read(Role::team($resourceId)); - $permissions[] = Permission::update(Role::team($resourceId, 'owner')); - $permissions[] = Permission::delete(Role::team($resourceId, 'owner')); - if ($projectId !== '') { - $permissions[] = Permission::read(Role::team($resourceId, 'project-' . $projectId . '-owner')); - $permissions[] = Permission::update(Role::team($resourceId, 'project-' . $projectId . '-owner')); - $permissions[] = Permission::delete(Role::team($resourceId, 'project-' . $projectId . '-owner')); - } - } - return $permissions; - } - - /** - * @param array{address?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient - */ - private static function buildRecipientKey(array $recipient): string - { - return ($recipient['address'] ?? '') - . ':' . $recipient['resourceType'] - . ':' . $recipient['resourceId'] - . ':' . $recipient['resourceInternalId'] - . ':' . $recipient['parentResourceType'] - . ':' . $recipient['parentResourceId'] - . ':' . $recipient['parentResourceInternalId']; - } -} diff --git a/src/Appwrite/Utopia/Messaging/Adapter/Webhook.php b/src/Appwrite/Utopia/Messaging/Adapter/Webhook.php deleted file mode 100644 index 76e7234261..0000000000 --- a/src/Appwrite/Utopia/Messaging/Adapter/Webhook.php +++ /dev/null @@ -1,124 +0,0 @@ -process($message); - } - - protected function process(WebhookMessage $message): array - { - $response = new Response($this->getType()); - $body = \json_encode($message->getPayload(), JSON_THROW_ON_ERROR); - $timestamp = (string) \time(); - - $headers = [ - 'Content-Type: application/json', - self::TIMESTAMP_HEADER . ': ' . $timestamp, - ]; - - $secret = $message->getSigningSecret(); - if ($secret !== null && $secret !== '') { - $signature = \hash_hmac('sha256', $timestamp . '.' . $body, $secret); - $headers[] = self::SIGNATURE_HEADER . ': sha256=' . $signature; - } - - foreach ($message->getHeaders() as $name => $value) { - $headers[] = $name . ': ' . $value; - } - - $delivered = 0; - foreach ($message->getUrls() as $url) { - $result = $this->dispatch('POST', $url, $headers, $body, $message->getTimeout()); - if ($result['statusCode'] >= 200 && $result['statusCode'] < 300 && empty($result['error'])) { - $delivered++; - $response->addResult($url); - } else { - $response->addResult($url, $result['error'] ?: ('HTTP ' . $result['statusCode'])); - } - } - - $response->setDeliveredTo($delivered); - return $response->toArray(); - } - - /** - * @param array $headers - * @return array{statusCode: int, response: string|null, error: string|null} - */ - protected function dispatch(string $method, string $url, array $headers, string $body, int $timeout): array - { - $client = new FetchClient(); - $client - ->setTimeout($timeout * 1000) - ->setConnectTimeout(\min(10, $timeout) * 1000) - ->setAllowRedirects(false) - ->setUserAgent('Appwrite Webhook'); - - foreach ($headers as $header) { - $parts = \explode(':', $header, 2); - if (\count($parts) === 2) { - $client->addHeader(\trim($parts[0]), \trim($parts[1])); - } - } - - try { - $response = $client->fetch($url, $method, $body); - } catch (FetchException $exception) { - return [ - 'statusCode' => 0, - 'response' => null, - 'error' => $exception->getMessage(), - ]; - } - - $output = $response->getBody(); - - return [ - 'statusCode' => $response->getStatusCode(), - 'response' => \is_string($output) ? $output : null, - 'error' => null, - ]; - } -} diff --git a/src/Appwrite/Utopia/Messaging/Messages/Console.php b/src/Appwrite/Utopia/Messaging/Messages/Console.php deleted file mode 100644 index 20d85f27e0..0000000000 --- a/src/Appwrite/Utopia/Messaging/Messages/Console.php +++ /dev/null @@ -1,82 +0,0 @@ - $recipients - */ - public function __construct( - protected array $recipients, - protected string $title, - protected string $body, - protected string $type = 'info', - protected ?string $messageId = null, - protected ?string $projectId = null, - protected ?string $projectInternalId = null, - ) { - } - - /** - * @return array - */ - public function getRecipients(): array - { - return $this->recipients; - } - - /** - * @return array - */ - public function getTo(): array - { - return $this->recipients; - } - - public function getTitle(): string - { - return $this->title; - } - - public function getBody(): string - { - return $this->body; - } - - public function getType(): string - { - return $this->type; - } - - public function getMessageId(): ?string - { - return $this->messageId; - } - - public function getProjectId(): ?string - { - return $this->projectId; - } - - public function getProjectInternalId(): ?string - { - return $this->projectInternalId; - } - - public function setOrigin(?string $origin): self - { - $this->origin = $origin; - - return $this; - } - - public function getOrigin(): ?string - { - return $this->origin; - } -} diff --git a/src/Appwrite/Utopia/Messaging/Messages/Webhook.php b/src/Appwrite/Utopia/Messaging/Messages/Webhook.php deleted file mode 100644 index e1146f9bd0..0000000000 --- a/src/Appwrite/Utopia/Messaging/Messages/Webhook.php +++ /dev/null @@ -1,80 +0,0 @@ - $urls - * @param array $payload - * @param array $headers - */ - public function __construct( - protected array $urls, - protected array $payload, - protected ?string $signingSecret = null, - protected array $headers = [], - protected int $timeout = 30, - ) { - } - - /** - * @return array - */ - public function getUrls(): array - { - return $this->urls; - } - - /** - * Alias used by the base adapter to bound max messages per request. - * - * @return array - */ - public function getTo(): array - { - return $this->urls; - } - - /** - * @return array - */ - public function getPayload(): array - { - return $this->payload; - } - - public function getSigningSecret(): ?string - { - return $this->signingSecret; - } - - /** - * @return array - */ - public function getHeaders(): array - { - return $this->headers; - } - - public function getTimeout(): int - { - return $this->timeout; - } - - public function setOrigin(?string $origin): self - { - $this->origin = $origin; - - return $this; - } - - public function getOrigin(): ?string - { - return $this->origin; - } -} diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index e6b713d530..e8701b315e 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -70,10 +70,6 @@ class Response extends SwooleResponse public const MODEL_ROW = 'row'; public const MODEL_ROW_LIST = 'rowList'; - // Notifications - public const MODEL_NOTIFICATION = 'notification'; - public const MODEL_NOTIFICATION_LIST = 'notificationList'; - // Database Attributes public const MODEL_ATTRIBUTE = 'attribute'; public const MODEL_ATTRIBUTE_LIST = 'attributeList'; diff --git a/src/Appwrite/Utopia/Response/Model/Log.php b/src/Appwrite/Utopia/Response/Model/Log.php index 038eb9eea7..1e48a6bc89 100644 --- a/src/Appwrite/Utopia/Response/Model/Log.php +++ b/src/Appwrite/Utopia/Response/Model/Log.php @@ -42,7 +42,7 @@ class Log extends Model ]) ->addRule('userType', [ 'type' => self::TYPE_STRING, - 'description' => 'User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization.', + 'description' => 'User type who triggered the audit log. Possible values: user, admin, guest, keyProject, keyAccount, keyOrganization.', 'default' => '', 'example' => 'user', ]) diff --git a/src/Appwrite/Utopia/Response/Model/Notification.php b/src/Appwrite/Utopia/Response/Model/Notification.php deleted file mode 100644 index 601871c620..0000000000 --- a/src/Appwrite/Utopia/Response/Model/Notification.php +++ /dev/null @@ -1,126 +0,0 @@ -addRule('$id', [ - 'type' => self::TYPE_STRING, - 'description' => 'Notification ID.', - 'default' => '', - 'example' => '5e5ea5c16897e', - ]) - ->addRule('$createdAt', [ - 'type' => self::TYPE_DATETIME, - 'description' => 'Notification creation date in ISO 8601 format.', - 'default' => '', - 'example' => self::TYPE_DATETIME_EXAMPLE, - ]) - ->addRule('$updatedAt', [ - 'type' => self::TYPE_DATETIME, - 'description' => 'Notification update date in ISO 8601 format.', - 'default' => '', - 'example' => self::TYPE_DATETIME_EXAMPLE, - ]) - ->addRule('messageId', [ - 'type' => self::TYPE_STRING, - 'description' => 'Stable message ID used for dedup.', - 'default' => '', - 'example' => 'session.create', - 'required' => false, - ]) - ->addRule('type', [ - 'type' => self::TYPE_STRING, - 'description' => 'Notification type: info, warning, error.', - 'default' => 'info', - 'example' => 'info', - ]) - ->addRule('channel', [ - 'type' => self::TYPE_STRING, - 'description' => 'Channel: email, sms, push, console, webhook.', - 'default' => '', - 'example' => 'email', - ]) - ->addRule('resourceType', [ - 'type' => self::TYPE_STRING, - 'description' => 'Resource type this notification is addressed to.', - 'default' => '', - 'example' => 'users', - ]) - ->addRule('resourceId', [ - 'type' => self::TYPE_STRING, - 'description' => 'Resource ID this notification is addressed to.', - 'default' => '', - 'example' => '5e5bb8c16897e', - ]) - ->addRule('parentResourceType', [ - 'type' => self::TYPE_STRING, - 'description' => 'Parent resource type for the notification.', - 'default' => '', - 'example' => 'projects', - ]) - ->addRule('parentResourceId', [ - 'type' => self::TYPE_STRING, - 'description' => 'Parent resource ID for the notification.', - 'default' => '', - 'example' => '5e5bb8c16897e', - ]) - ->addRule('projectId', [ - 'type' => self::TYPE_STRING, - 'description' => 'Project the notification pertains to.', - 'default' => '', - 'example' => '5e5bb8c16897e', - 'required' => false, - ]) - ->addRule('title', [ - 'type' => self::TYPE_STRING, - 'description' => 'Notification title.', - 'default' => '', - 'example' => 'New sign-in detected', - ]) - ->addRule('body', [ - 'type' => self::TYPE_STRING, - 'description' => 'Notification body.', - 'default' => '', - 'example' => 'A new device signed in to your account.', - ]) - ->addRule('read', [ - 'type' => self::TYPE_BOOLEAN, - 'description' => 'Whether the notification has been read.', - 'default' => false, - 'example' => false, - 'required' => false, - ]) - ->addRule('firstSeen', [ - 'type' => self::TYPE_DATETIME, - 'description' => 'First time the notification was viewed from a notification logo.', - 'default' => null, - 'example' => self::TYPE_DATETIME_EXAMPLE, - 'required' => false, - ]) - ->addRule('lastSeen', [ - 'type' => self::TYPE_DATETIME, - 'description' => 'Most recent time the notification was viewed from a notification logo.', - 'default' => null, - 'example' => self::TYPE_DATETIME_EXAMPLE, - 'required' => false, - ]) - ; - } - - public function getName(): string - { - return 'Notification'; - } - - public function getType(): string - { - return Response::MODEL_NOTIFICATION; - } -} diff --git a/tests/e2e/Services/Notifications/NotificationsBase.php b/tests/e2e/Services/Notifications/NotificationsBase.php deleted file mode 100644 index e6c8babe9b..0000000000 --- a/tests/e2e/Services/Notifications/NotificationsBase.php +++ /dev/null @@ -1,632 +0,0 @@ -client->call(Client::METHOD_GET, '/health/queue/notifications', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders())); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertIsInt($response['body']['size']); - $this->assertGreaterThanOrEqual(0, $response['body']['size']); - } - - public function testHealthQueueNotificationsThresholdGuard(): void - { - $response = $this->client->call(Client::METHOD_GET, '/health/queue/notifications', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), ['threshold' => '0']); - - $this->assertContains($response['headers']['status-code'], [200, 503]); - } - - public function testHealthQueueFailedAcceptsNotifications(): void - { - $response = $this->client->call(Client::METHOD_GET, '/health/queue/failed/v1-notifications', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders())); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertIsInt($response['body']['size']); - } - - public function testListNotificationsEmpty(): void - { - // Always read notifications as the console-authenticated owner of the team. - // The /v1/notifications endpoint is platform-scoped (dbForPlatform) and - // requires a session; server-mode API keys do not satisfy it. - $response = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders()); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertArrayHasKey('notifications', $response['body']); - $this->assertArrayHasKey('total', $response['body']); - $this->assertIsArray($response['body']['notifications']); - $this->assertIsInt($response['body']['total']); - - // The shared root console user may carry notifications from prior tests in the - // same suite — assert only that the response shape is correct and that - // counts agree. - $this->assertSame(\count($response['body']['notifications']), \min(\count($response['body']['notifications']), $response['body']['total'])); - } - - public function testWebhookFailureCreatesConsoleAlert(): void - { - $alertId = $this->seedWebhookFailureAlert(); - - $this->assertNotEmpty($alertId); - - $list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders()); - $this->assertSame(200, $list['headers']['status-code']); - - $found = null; - foreach ($list['body']['notifications'] as $alert) { - if ($alert['$id'] === $alertId) { - $found = $alert; - break; - } - } - - $this->assertNotNull($found, 'Seeded alert not present in /notifications response.'); - $this->assertSame('console', $found['channel']); - $this->assertStringContainsStringIgnoringCase('webhook', $found['title']); - - // Cache the seeded alert id for downstream tests in the same process. - self::$seededAlertId = $alertId; - } - - /** - * The webhook-paused fanout enqueues a single Notification with both a - * console and an email recipient. The console side is asserted above; this - * verifies the email channel travels the full path — Notifications worker - * → SMTP → maildev — by polling the maildev inbox for the rendered email - * addressed to the project owner. - */ - public function testWebhookFailureSendsEmailNotification(): void - { - // Reuse the fanout from the console-alert test when it already ran in - // this process; otherwise drive a fresh one. Either way the owner email - // lands in maildev for the root user this suite created. - if (self::$seededAlertId === null) { - self::$seededAlertId = $this->seedWebhookFailureAlert(); - } - - $ownerEmail = $this->getRoot()['email']; - - $this->assertEventually(function () use ($ownerEmail) { - $this->assertGreaterThanOrEqual( - 1, - $this->countNotificationEmails($ownerEmail, 'Webhook deliveries have been paused'), - 'No webhook-paused email observed in maildev for ' . $ownerEmail - ); - }, 30000, 1000); - } - - public function testMarkNotificationReadTogglesFlag(): void - { - $alertId = self::$seededAlertId ?? $this->seedWebhookFailureAlert(); - $this->assertNotEmpty($alertId); - - $patch = $this->client->call( - Client::METHOD_PATCH, - '/notifications/' . $alertId, - $this->getConsoleAlertHeaders(), - ['read' => true] - ); - - $this->assertSame(200, $patch['headers']['status-code']); - $this->assertSame($alertId, $patch['body']['$id']); - $this->assertTrue($patch['body']['read']); - - $list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders()); - $this->assertSame(200, $list['headers']['status-code']); - - $found = null; - foreach ($list['body']['notifications'] as $alert) { - if ($alert['$id'] === $alertId) { - $found = $alert; - break; - } - } - - $this->assertNotNull($found); - $this->assertTrue($found['read']); - - self::$seededAlertId = null; // notification is read, downstream tests will seed fresh - } - - public function testMarkNotificationReadUnauthorized(): void - { - $alertId = $this->seedWebhookFailureAlert(); - $this->assertNotEmpty($alertId); - - // Create a stranger console user with their own session. - $stranger = $this->createConsoleUser(); - - $unauthorized = $this->client->call( - Client::METHOD_PATCH, - '/notifications/' . $alertId, - [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $stranger['session'], - 'x-appwrite-project' => 'console', - ], - ['read' => true] - ); - - $this->assertSame(401, $unauthorized['headers']['status-code']); - $this->assertSame('user_unauthorized', $unauthorized['body']['type'] ?? ''); - - // Owner re-fetches — alert must still be unread. - $list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders()); - $this->assertSame(200, $list['headers']['status-code']); - - $found = null; - foreach ($list['body']['notifications'] as $alert) { - if ($alert['$id'] === $alertId) { - $found = $alert; - break; - } - } - - $this->assertNotNull($found); - $this->assertFalse($found['read']); - - self::$seededAlertId = $alertId; - } - - public function testProjectAccountCannotListPlatformNotificationsWithCollidingUserId(): void - { - $alertId = $this->seedWebhookFailureAlert(); - $this->assertNotEmpty($alertId); - - $attackerProject = $this->getProject(true); - $projectId = $attackerProject['$id']; - $email = \uniqid('colliding-alert-user-', true) . '@localhost.test'; - $password = 'password'; - - $created = $this->client->call(Client::METHOD_POST, '/users', [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $attackerProject['apiKey'], - ], [ - 'userId' => $this->getRoot()['$id'], - 'email' => $email, - 'password' => $password, - 'name' => 'Colliding Alert User', - ]); - - $this->assertSame(201, $created['headers']['status-code']); - - $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], [ - 'email' => $email, - 'password' => $password, - ]); - - $this->assertSame(201, $session['headers']['status-code']); - $this->assertNotEmpty($session['cookies']['a_session_' . $projectId] ?? ''); - - $response = $this->client->call(Client::METHOD_GET, '/notifications', [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], - 'x-appwrite-project' => $projectId, - ]); - - $this->assertSame(401, $response['headers']['status-code']); - $this->assertSame('user_unauthorized', $response['body']['type'] ?? ''); - - self::$seededAlertId = $alertId; - } - - public function testNotificationLogoTracksViews(): void - { - $alertId = self::$seededAlertId ?? $this->seedWebhookFailureAlert(); - $this->assertNotEmpty($alertId); - $alert = $this->findConsoleAlert($alertId); - $this->assertFalse($alert['read']); - $this->assertEmpty($alert['firstSeen'] ?? null); - $this->assertEmpty($alert['lastSeen'] ?? null); - - $secret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET'); - $this->assertNotEmpty($secret, '_APP_NOTIFICATIONS_TRACKING_SECRET must be set for notification logo test'); - $recipientHash = \substr($alertId, \strrpos($alertId, '_') + 1); - - // Logo endpoint requires `purpose: 'notification_track'`. Other claim - // purposes are silently ignored, which the purpose-claim test covers. - $jwt = (new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0))->encode([ - 'messageId' => $alert['messageId'], - 'channel' => $alert['channel'], - 'recipientHash' => $recipientHash, - 'projectId' => $alert['projectId'], - 'purpose' => 'notification_track', - ]); - - $response = $this->client->call( - Client::METHOD_GET, - '/notifications/logos/appwrite', - ['x-appwrite-project' => 'console'], - [ - 'jwt' => $jwt, - 'theme' => 'dark', - ] - ); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']); - $this->assertNotEmpty($response['body']); - $this->assertStringStartsWith('assertStringContainsString('Appwrite', $response['body']); - - $tracked = $this->findConsoleAlert($alertId); - $this->assertTrue($tracked['read']); - $this->assertNotEmpty($tracked['firstSeen']); - $this->assertNotEmpty($tracked['lastSeen']); - - \sleep(1); - - $secondResponse = $this->client->call( - Client::METHOD_GET, - '/notifications/logos/appwrite', - ['x-appwrite-project' => 'console'], - ['jwt' => $jwt] - ); - - $this->assertSame(200, $secondResponse['headers']['status-code']); - - $viewedAgain = $this->findConsoleAlert($alertId); - $this->assertSame($tracked['firstSeen'], $viewedAgain['firstSeen']); - $this->assertNotSame($tracked['lastSeen'], $viewedAgain['lastSeen']); - - self::$seededAlertId = null; - } - - /** - * Reviewer M7: a tracking JWT without a `purpose: 'notification_track'` claim - * must be silently rejected. Without the purpose check, any JWT minted - * with the same secret (sessions, password reset, etc.) could be - * replayed against this endpoint to mark arbitrary notifications as read. - * - * The endpoint always returns the SVG logo (200 image/svg+xml) — the only - * observable difference is whether the alert flips to `read: true`. - */ - public function testNotificationLogoRejectsJwtWithoutPurposeClaim(): void - { - $alertId = $this->seedWebhookFailureAlert(); - $this->assertNotEmpty($alertId); - $alert = $this->findConsoleAlert($alertId); - - $secret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET'); - $this->assertNotEmpty($secret, '_APP_NOTIFICATIONS_TRACKING_SECRET must be set for the JWT purpose-claim test'); - $recipientHash = \substr($alertId, \strrpos($alertId, '_') + 1); - - // Mint a JWT with valid message/recipient claims but NO purpose claim. - $jwtNoPurpose = (new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0))->encode([ - 'messageId' => $alert['messageId'], - 'channel' => $alert['channel'], - 'recipientHash' => $recipientHash, - 'projectId' => $alert['projectId'], - ]); - - $response = $this->client->call( - Client::METHOD_GET, - '/notifications/logos/appwrite', - ['x-appwrite-project' => 'console'], - ['jwt' => $jwtNoPurpose] - ); - - $this->assertSame(200, $response['headers']['status-code'], 'endpoint must always return 200'); - $this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']); - - $found = $this->findConsoleAlert($alertId); - $this->assertFalse($found['read'], 'JWT without purpose claim must not flip the read flag'); - $this->assertEmpty($found['firstSeen'] ?? null); - $this->assertEmpty($found['lastSeen'] ?? null); - - // Mint a JWT with a wrong purpose value: same expectation, silently rejected. - $jwtWrongPurpose = (new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0))->encode([ - 'messageId' => $alert['messageId'], - 'channel' => $alert['channel'], - 'recipientHash' => $recipientHash, - 'projectId' => $alert['projectId'], - 'purpose' => 'something_else', - ]); - - $response = $this->client->call( - Client::METHOD_GET, - '/notifications/logos/appwrite', - ['x-appwrite-project' => 'console'], - ['jwt' => $jwtWrongPurpose] - ); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']); - - $found = $this->findConsoleAlert($alertId); - $this->assertFalse($found['read'], 'JWT with wrong purpose value must not flip the read flag'); - $this->assertEmpty($found['firstSeen'] ?? null); - $this->assertEmpty($found['lastSeen'] ?? null); - - self::$seededAlertId = $alertId; - } - - public function testNotificationLogoInvalidTokenReturnsSvg(): void - { - $alertId = $this->seedWebhookFailureAlert(); - $this->assertNotEmpty($alertId); - - $response = $this->client->call( - Client::METHOD_GET, - '/notifications/logos/appwrite', - ['x-appwrite-project' => 'console'], - ['jwt' => 'tampered-or-empty'] - ); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']); - $this->assertNotEmpty($response['body']); - $this->assertStringStartsWith('findConsoleAlert($alertId); - $this->assertFalse($found['read']); - $this->assertEmpty($found['firstSeen'] ?? null); - $this->assertEmpty($found['lastSeen'] ?? null); - - self::$seededAlertId = $alertId; - } - - /** - * @var string|null Cached seeded alert id so consecutive tests can reuse it - * without paying the cost of another 10-failure webhook drive. - */ - protected static ?string $seededAlertId = null; - - /** - * Build the auth header set used to talk to the platform-scoped - * /v1/notifications endpoints. Always console session, regardless of - * the trait's host (server vs console) — the endpoint requires a session - * and the root user owns the project team. - * - * @return array - */ - protected function getConsoleAlertHeaders(): array - { - return [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], - 'x-appwrite-project' => 'console', - ]; - } - - /** - * Count emails sitting in the maildev inbox that are addressed to the given - * recipient and carry the given subject. Mirrors the maildev polling used - * by the session-alert e2e suite. - */ - protected function countNotificationEmails(string $address, string $subject): int - { - $host = System::getEnv('_APP_SMTP_HOST', 'maildev'); - $inbox = \file_get_contents('http://' . $host . ':1080/email'); - if ($inbox === false) { - return 0; - } - - $emails = \json_decode($inbox, true) ?? []; - $count = 0; - foreach ($emails as $email) { - if (($email['subject'] ?? '') !== $subject) { - continue; - } - foreach ($email['to'] ?? [] as $recipient) { - if (($recipient['address'] ?? '') === $address) { - $count++; - } - } - } - - return $count; - } - - /** - * @return array - */ - protected function findConsoleAlert(string $alertId): array - { - $list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders()); - $this->assertSame(200, $list['headers']['status-code']); - - foreach ($list['body']['notifications'] as $alert) { - if ($alert['$id'] === $alertId) { - return $alert; - } - } - - $this->fail('Alert not present in /notifications response: ' . $alertId); - } - - /** - * Drive a webhook past the failure threshold so the - * Webhooks worker emits a console+email alert fanout to the project - * owner. Returns the alert id. - * - * Uses a unique webhook-per-call so concurrent tests don't share - * attempt counters. - */ - protected function seedWebhookFailureAlert(): string - { - $project = $this->getProject(); - $projectId = $project['$id']; - - // Register a webhook pointing at an unroutable address. The Webhook - // worker will fail every delivery and after 10 attempts pause it - // and enqueue a console+email alert for the project owner. - $webhookName = 'Failing Webhook ' . \uniqid(); - $webhook = $this->client->call(Client::METHOD_POST, '/webhooks', [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], - 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin', - ], [ - 'webhookId' => ID::unique(), - 'name' => $webhookName, - 'events' => ['users.*.create'], - 'url' => 'http://request-catcher-webhook:1/', - 'tls' => false, - ]); - - $this->assertSame(201, $webhook['headers']['status-code']); - $webhookId = $webhook['body']['$id']; - - $maxAttempts = (int) System::getEnv('_APP_WEBHOOK_MAX_FAILED_ATTEMPTS', '10'); - - // Drive the webhook past its failure threshold by issuing user-create - // events, each of which triggers a delivery attempt the worker will - // fail. Each create event is also dispatched to the project's - // pre-existing reachable webhook — that one stays healthy. - for ($i = 0; $i < $maxAttempts + 2; $i++) { - $email = \uniqid('alert-seed-', true) . '@localhost.test'; - $created = $this->client->call(Client::METHOD_POST, '/users', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'userId' => ID::unique(), - 'email' => $email, - 'password' => 'password', - 'name' => 'Webhook Failure Driver', - ]); - - // Tolerate transient 409s under parallel load. - $this->assertContains( - $created['headers']['status-code'], - [201, 409], - 'User create failed while seeding webhook failure: ' . ($created['body']['message'] ?? '') - ); - } - - // Poll for the alert. Alert creation is async (notification worker) - // and webhook deliveries also queue up — give them generous time. - $alertId = null; - $this->assertEventually(function () use (&$alertId, $projectId, $webhookId, $webhookName) { - $list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders()); - $this->assertSame(200, $list['headers']['status-code']); - - foreach ($list['body']['notifications'] as $alert) { - if ( - ($alert['channel'] ?? '') === 'console' - && ($alert['projectId'] ?? '') === $projectId - && ($alert['parentResourceId'] ?? '') === $projectId - && ($alert['title'] ?? '') === 'Webhook deliveries have been paused' - && \str_contains($alert['body'] ?? '', $webhookName) - ) { - $alertId = $alert['$id']; - return; - } - } - - $this->fail('No webhook-paused console alert observed yet for webhook ' . $webhookId); - }, 60000, 1000); - - // Cleanup the failing webhook so it doesn't keep firing in the - // background for subsequent tests in the same process. - $this->client->call(Client::METHOD_DELETE, '/webhooks/' . $webhookId, [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], - 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin', - ]); - - return $alertId; - } - - /** - * Create a fresh console user with its own session, separate from the - * shared root user. Used to assert that strangers cannot mark someone - * else's alert as read. - * - * @return array{'$id': string, email: string, session: string} - */ - protected function createConsoleUser(): array - { - $email = \uniqid('stranger-', true) . \getmypid() . \bin2hex(\random_bytes(4)) . '@localhost.test'; - $password = 'password'; - - $user = $this->client->call(Client::METHOD_POST, '/account', [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'x-appwrite-project' => 'console', - ], [ - 'userId' => ID::unique(), - 'email' => $email, - 'password' => $password, - 'name' => 'Stranger', - ]); - - $this->assertSame(201, $user['headers']['status-code']); - - $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'x-appwrite-project' => 'console', - ], [ - 'email' => $email, - 'password' => $password, - ]); - - $this->assertSame(201, $session['headers']['status-code']); - $this->assertNotEmpty($session['cookies']['a_session_console'] ?? ''); - - return [ - '$id' => $user['body']['$id'], - 'email' => $email, - 'session' => $session['cookies']['a_session_console'], - ]; - } -} diff --git a/tests/e2e/Services/Notifications/NotificationsCustomConsoleTest.php b/tests/e2e/Services/Notifications/NotificationsCustomConsoleTest.php deleted file mode 100644 index d44a6921fe..0000000000 --- a/tests/e2e/Services/Notifications/NotificationsCustomConsoleTest.php +++ /dev/null @@ -1,16 +0,0 @@ -assertCount(17, $this->object->getServices()); + $this->assertCount(16, $this->object->getServices()); $this->assertSame('appwrite', $this->object->getService('appwrite')->getContainerName()); $this->assertSame('', $this->object->getService('appwrite')->getImageVersion()); - $this->assertSame('3.6', $this->object->getService('traefik')->getImageVersion()); + $this->assertEquals('3.6', $this->object->getService('traefik')->getImageVersion()); $this->assertSame(['2080' => '80', '2443' => '443', '8080' => '8080'], $this->object->getService('traefik')->getPorts()); - $this->assertSame('appwrite-worker-mails', $this->object->getService('appwrite-worker-mails')->getContainerName()); - $this->assertSame('worker-mails', $this->object->getService('appwrite-worker-mails')->getEntrypoint()); - $this->assertSame('appwrite-worker-notifications', $this->object->getService('appwrite-worker-notifications')->getContainerName()); - $this->assertSame('worker-notifications', $this->object->getService('appwrite-worker-notifications')->getEntrypoint()); } public function testNetworks(): void @@ -44,8 +40,8 @@ final class ComposeTest extends TestCase public function testVolumes(): void { $this->assertCount(7, $this->object->getVolumes()); - $this->assertSame('appwrite-mariadb', $this->object->getVolumes()[0]); - $this->assertSame('appwrite-redis', $this->object->getVolumes()[1]); - $this->assertSame('appwrite-cache', $this->object->getVolumes()[2]); + $this->assertEquals('appwrite-mariadb', $this->object->getVolumes()[0]); + $this->assertEquals('appwrite-redis', $this->object->getVolumes()[1]); + $this->assertEquals('appwrite-cache', $this->object->getVolumes()[2]); } } diff --git a/tests/unit/Event/Message/NotificationTest.php b/tests/unit/Event/Message/NotificationTest.php deleted file mode 100644 index eecf583f34..0000000000 --- a/tests/unit/Event/Message/NotificationTest.php +++ /dev/null @@ -1,86 +0,0 @@ - 'project-1', - '$sequence' => 'project-internal-1', - 'database' => 'mysql://database', - ]), - recipient: 'owner@example.test', - subject: 'Subject', - body: 'Body', - preview: 'Preview', - event: 'databases.[databaseId].collections.[collectionId].documents.[documentId].create', - params: [ - 'databaseId' => 'database-1', - 'collectionId' => 'collection-1', - 'documentId' => 'document-1', - ], - platform: ['name' => 'test-platform'], - ); - - $payload = $message->toArray(); - - $this->assertSame([ - '$id' => 'project-1', - '$sequence' => 'project-internal-1', - 'database' => 'mysql://database', - ], $payload['project']); - $this->assertSame([ - [ - 'address' => 'owner@example.test', - 'channel' => NOTIFICATION_TYPE_EMAIL, - ], - ], $payload['recipients']); - $this->assertSame('Subject', $payload['subject']); - $this->assertSame('Body', $payload['body']); - $this->assertSame('Preview', $payload['preview']); - $this->assertContains( - 'databases.database-1.collections.collection-1.documents.document-1.create', - $payload['events'] - ); - $this->assertSame(['name' => 'test-platform'], $payload['platform']); - - $this->assertSame($payload, NotificationMessage::fromArray($payload)->toArray()); - } - - public function testNotificationPublisherUsesConfiguredQueue(): void - { - $publisher = new MockPublisher(); - $publisherForNotifications = new NotificationPublisher($publisher, new Queue('custom-notifications')); - - $publisherForNotifications->enqueue(new NotificationMessage( - project: new Document(['$id' => 'project-1']), - recipients: [ - [ - 'address' => 'user-1', - 'channel' => NOTIFICATION_TYPE_CONSOLE, - ], - ], - subject: 'Alert', - )); - - $events = $publisher->getEvents('custom-notifications'); - - $this->assertCount(1, $events); - $this->assertSame('Alert', $events[0]['subject']); - $this->assertSame(1, $publisherForNotifications->getSize()); - } -} diff --git a/tests/unit/Event/MockPublisher.php b/tests/unit/Event/MockPublisher.php index b990179969..8363ed4e85 100644 --- a/tests/unit/Event/MockPublisher.php +++ b/tests/unit/Event/MockPublisher.php @@ -30,6 +30,6 @@ class MockPublisher implements Publisher public function getQueueSize(Queue $queue, bool $failedJobs = false): int { - return count($this->events[$queue->name] ?? []); + return count($this->events[$queue->name]); } } diff --git a/tests/unit/Migration/MigrationVersionsTest.php b/tests/unit/Migration/MigrationVersionsTest.php index 6274d0820c..a97a582bd9 100644 --- a/tests/unit/Migration/MigrationVersionsTest.php +++ b/tests/unit/Migration/MigrationVersionsTest.php @@ -5,14 +5,7 @@ declare(strict_types=1); namespace Tests\Unit\Migration; use Appwrite\Migration\Migration; -use Appwrite\Migration\Version\V24; use PHPUnit\Framework\TestCase; -use Utopia\Cache\Adapter\None as NoCache; -use Utopia\Cache\Cache; -use Utopia\Database\Adapter\Memory; -use Utopia\Database\Database; -use Utopia\Database\Document; -use Utopia\Database\Validator\Authorization; final class MigrationVersionsTest extends TestCase { @@ -33,103 +26,4 @@ final class MigrationVersionsTest extends TestCase $this->assertArrayHasKey(APP_VERSION_STABLE, Migration::$versions); } } - - public function testV24CreatesAlertsCollectionForConsoleProject(): void - { - require_once __DIR__ . '/../../../app/init.php'; - - $authorization = new Authorization(); - $database = new Database(new Memory(), new Cache(new NoCache())); - $database - ->setAuthorization($authorization) - ->setDatabase('migrationV24') - ->setNamespace('migration_' . \uniqid()); - $database->create(); - - $migration = new V24(); - $migration->setProject( - new Document(['$id' => 'console', '$sequence' => 'console']), - $database, - $database, - $authorization, - ); - - $migrateCollections = new \ReflectionMethod($migration, 'migrateCollections'); - \ob_start(); - try { - $migrateCollections->invoke($migration); - } finally { - \ob_end_clean(); - } - - $collection = $database->getCollection('notifications'); - $this->assertFalse($collection->isEmpty()); - - $attributes = []; - foreach ($collection->getAttribute('attributes', []) as $attribute) { - $id = $attribute instanceof Document ? $attribute->getAttribute('$id') : ($attribute['$id'] ?? ''); - $attributes[$id] = $attribute; - } - $this->assertArrayHasKey('resourceInternalId', $attributes); - $this->assertArrayHasKey('parentResourceInternalId', $attributes); - $this->assertArrayHasKey('firstSeen', $attributes); - $this->assertArrayHasKey('lastSeen', $attributes); - - $indexes = []; - foreach ($collection->getAttribute('indexes', []) as $index) { - $id = $index instanceof Document ? $index->getAttribute('$id') : ($index['$id'] ?? ''); - $indexes[$id] = $index instanceof Document ? $index->getAttribute('attributes') : ($index['attributes'] ?? []); - } - - $this->assertSame([ - '_key_messageId', - '_key_recipient', - '_key_project', - '_key_project_resource', - '_key_project_parent_resource', - ], \array_keys($indexes)); - $this->assertSame(['projectId', 'projectInternalId'], $indexes['_key_project']); - $this->assertSame(['projectId', 'projectInternalId', 'resourceType', 'resourceId', 'resourceInternalId'], $indexes['_key_project_resource']); - $this->assertSame(['projectId', 'projectInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'], $indexes['_key_project_parent_resource']); - } - - public function testV24AddsSeenAttributesToExistingAlertsCollection(): void - { - require_once __DIR__ . '/../../../app/init.php'; - - $authorization = new Authorization(); - $database = new Database(new Memory(), new Cache(new NoCache())); - $database - ->setAuthorization($authorization) - ->setDatabase('migrationV24ExistingAlerts') - ->setNamespace('migration_existing_alerts_' . \uniqid()); - $database->create(); - $database->createCollection('notifications'); - - $migration = new V24(); - $migration->setProject( - new Document(['$id' => 'console', '$sequence' => 'console']), - $database, - $database, - $authorization, - ); - - $migrateCollections = new \ReflectionMethod($migration, 'migrateCollections'); - \ob_start(); - try { - $migrateCollections->invoke($migration); - } finally { - \ob_end_clean(); - } - - $collection = $database->getCollection('notifications'); - $attributes = []; - foreach ($collection->getAttribute('attributes', []) as $attribute) { - $id = $attribute instanceof Document ? $attribute->getAttribute('$id') : ($attribute['$id'] ?? ''); - $attributes[$id] = $attribute; - } - - $this->assertArrayHasKey('firstSeen', $attributes); - $this->assertArrayHasKey('lastSeen', $attributes); - } } diff --git a/tests/unit/Platform/Modules/Notifications/NotificationsTest.php b/tests/unit/Platform/Modules/Notifications/NotificationsTest.php deleted file mode 100644 index 5daed2633e..0000000000 --- a/tests/unit/Platform/Modules/Notifications/NotificationsTest.php +++ /dev/null @@ -1,130 +0,0 @@ -document = $document; - $this->model = $model; - } -} - -final class NotificationsTest extends TestCase -{ - private Authorization $authorization; - private Database $database; - - protected function setUp(): void - { - $this->authorization = new Authorization(); - $this->authorization->addRole(Role::any()->toString()); - - $this->database = new Database(new Memory(), new Cache(new NoCache())); - $this->database - ->setAuthorization($this->authorization) - ->setDatabase('notificationEndpointTests') - ->setNamespace('notifications_' . \uniqid()); - - $permissions = [ - Permission::create(Role::any()), - Permission::read(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ]; - - $this->database->create(); - $this->database->createCollection('notifications', [], [], $permissions, false); - $this->database->createAttribute('notifications', 'messageId', Database::VAR_STRING, 255, false); - $this->database->createAttribute('notifications', 'recipientHash', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'type', Database::VAR_STRING, 64, false, 'info'); - $this->database->createAttribute('notifications', 'channel', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'projectId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'projectInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'resourceType', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'resourceId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'resourceInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'parentResourceType', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'parentResourceId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'parentResourceInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'title', Database::VAR_STRING, 256, true); - $this->database->createAttribute('notifications', 'body', Database::VAR_STRING, 16384, true); - $this->database->createAttribute('notifications', 'read', Database::VAR_BOOLEAN, 0, false, false); - } - - protected function tearDown(): void - { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); - } - - public function testListReturnsOnlyCurrentUserNotifications(): void - { - $this->createNotification('user-alert', RESOURCE_TYPE_USERS, 'user-a'); - $this->createNotification('team-alert', RESOURCE_TYPE_TEAMS, 'team-a'); - $this->createNotification('user-email-receipt', RESOURCE_TYPE_USERS, 'user-a', NOTIFICATION_TYPE_EMAIL); - - $response = new CapturingNotificationsResponse(); - - (new XList())->action( - [], - $response, - $this->database, - new Document(['$id' => 'console']), - new Document(['$id' => 'user-a']), - ); - - $notifications = $response->document->getAttribute('notifications'); - - $this->assertCount(1, $notifications); - $this->assertSame('user-alert', $notifications[0]->getId()); - $this->assertSame(1, $response->document->getAttribute('total')); - $this->assertSame(Response::MODEL_NOTIFICATION_LIST, $response->model); - } - - private function createNotification(string $id, string $resourceType, string $resourceId, string $channel = NOTIFICATION_TYPE_CONSOLE): Document - { - return $this->database->createDocument('notifications', new Document([ - '$id' => $id, - 'messageId' => $id, - 'recipientHash' => \substr(\md5($id), 0, 16), - 'type' => 'info', - 'channel' => $channel, - 'projectId' => 'project', - 'projectInternalId' => '10', - 'resourceType' => $resourceType, - 'resourceId' => $resourceId, - 'resourceInternalId' => '20', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project', - 'parentResourceInternalId' => '10', - 'title' => 'Title', - 'body' => 'Body', - 'read' => false, - ])); - } -} diff --git a/tests/unit/Platform/Modules/Projects/SchedulesTest.php b/tests/unit/Platform/Modules/Projects/SchedulesTest.php deleted file mode 100644 index ca3f105f6c..0000000000 --- a/tests/unit/Platform/Modules/Projects/SchedulesTest.php +++ /dev/null @@ -1,161 +0,0 @@ -document = $document; - $this->model = $model; - } -} - -final class SchedulesTest extends TestCase -{ - private Authorization $authorization; - private Database $database; - private Document $project; - - protected function setUp(): void - { - $this->authorization = new Authorization(); - $this->authorization->addRole(Role::any()->toString()); - - $this->database = new Database(new Memory(), new Cache(new NoCache())); - $this->database - ->setAuthorization($this->authorization) - ->setDatabase('scheduleTests') - ->setNamespace('schedules_' . \uniqid()); - - $permissions = [ - Permission::create(Role::any()), - Permission::read(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ]; - - $this->database->create(); - $this->database->createCollection('projects', [], [], $permissions, false); - $this->database->createCollection('schedules', [], [], $permissions, false); - $this->database->createAttribute('schedules', 'projectId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('schedules', 'projectInternalId', Database::VAR_ID, 0, false); - - $this->project = $this->database->createDocument('projects', new Document([ - '$id' => 'project-a', - ])); - } - - protected function tearDown(): void - { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); - } - - public function testGetAllowsLegacyScheduleWithoutProjectInternalId(): void - { - $this->createSchedule('legacy'); - - $response = new CapturingSchedulesResponse(); - - (new Get())->action('project-a', 'legacy', $response, $this->database); - - $this->assertSame('legacy', $response->document->getId()); - $this->assertSame(Response::MODEL_SCHEDULE, $response->model); - } - - public function testGetRejectsScheduleWithMismatchedProjectInternalId(): void - { - $this->createSchedule('mismatch', projectInternalId: '999'); - - $this->expectException(AppwriteException::class); - - (new Get())->action('project-a', 'mismatch', new CapturingSchedulesResponse(), $this->database); - } - - public function testListIncludesLegacyAndCurrentProjectSchedules(): void - { - $this->createSchedule('legacy'); - $this->createSchedule('current', projectInternalId: $this->project->getSequence()); - $this->createSchedule('mismatch', projectInternalId: '999'); - $this->createSchedule('other-project', projectId: 'project-b'); - - $response = new CapturingSchedulesResponse(); - - (new XList())->action('project-a', [], true, $response, $this->database); - - $schedules = $response->document->getAttribute('schedules'); - $scheduleIds = \array_map( - fn (Document $schedule) => $schedule->getId(), - $schedules, - ); - - $this->assertContains('legacy', $scheduleIds); - $this->assertContains('current', $scheduleIds); - $this->assertNotContains('mismatch', $scheduleIds); - $this->assertNotContains('other-project', $scheduleIds); - $this->assertSame(2, $response->document->getAttribute('total')); - $this->assertSame(Response::MODEL_SCHEDULE_LIST, $response->model); - } - - public function testListCursorAllowsLegacyScheduleWithoutProjectInternalId(): void - { - $legacy = $this->createSchedule('legacy'); - $this->createSchedule('current', projectInternalId: $this->project->getSequence()); - - $response = new CapturingSchedulesResponse(); - - (new XList())->action( - 'project-a', - [Query::cursorAfter($legacy)->toString()], - true, - $response, - $this->database, - ); - - $this->assertSame(Response::MODEL_SCHEDULE_LIST, $response->model); - } - - private function createSchedule( - string $id, - string $projectId = 'project-a', - int|string|null $projectInternalId = null, - ): Document { - $attributes = [ - '$id' => $id, - 'projectId' => $projectId, - ]; - - if ($projectInternalId !== null) { - $attributes['projectInternalId'] = $projectInternalId; - } - - return $this->database->createDocument('schedules', new Document($attributes)); - } -} diff --git a/tests/unit/Platform/Workers/DeletesTest.php b/tests/unit/Platform/Workers/DeletesTest.php deleted file mode 100644 index 42dc4ac895..0000000000 --- a/tests/unit/Platform/Workers/DeletesTest.php +++ /dev/null @@ -1,93 +0,0 @@ - 'project-1', - '$sequence' => 'project-internal-1', - 'database' => 'mysql://localhost/appwrite', - ]); - - $worker = new class () extends Deletes { - /** - * @var array> - */ - public array $groups = []; - - public function runProjectDelete( - Database $database, - Document $project, - callable $getProjectDB, - callable $getDatabasesDB, - Device $device, - CertificatesAdapter $certificates, - ): void { - $this->deleteProject( - $database, - $getProjectDB, - $getDatabasesDB, - $device, - $device, - $device, - $device, - $device, - $certificates, - $project, - ); - } - - protected function deleteByGroup(string $collection, array $queries, Database $database, ?callable $callback = null): void - { - $this->groups[$collection] = $queries; - } - }; - $getProjectDB = static fn () => throw new \RuntimeException('stop'); - $getDatabasesDB = static fn () => $database; - - try { - $worker->runProjectDelete( - $database, - $project, - $getProjectDB, - $getDatabasesDB, - $this->createStub(Device::class), - $this->createStub(CertificatesAdapter::class), - ); - } catch (\RuntimeException $exception) { - $this->assertSame('stop', $exception->getMessage()); - } - - $this->assertArrayHasKey('notifications', $worker->groups); - - $queries = $worker->groups['notifications']; - $this->assertSame(Query::TYPE_EQUAL, $queries[0]->getMethod()); - $this->assertSame('projectId', $queries[0]->getAttribute()); - $this->assertSame(['project-1'], $queries[0]->getValues()); - - $this->assertSame(Query::TYPE_EQUAL, $queries[1]->getMethod()); - $this->assertSame('projectInternalId', $queries[1]->getAttribute()); - $this->assertSame(['project-internal-1'], $queries[1]->getValues()); - - $this->assertSame(Query::TYPE_ORDER_ASC, $queries[2]->getMethod()); - } -} diff --git a/tests/unit/Platform/Workers/MailsTest.php b/tests/unit/Platform/Workers/MailsTest.php deleted file mode 100644 index a6b7a123d7..0000000000 --- a/tests/unit/Platform/Workers/MailsTest.php +++ /dev/null @@ -1,98 +0,0 @@ -sendCount++; - $this->captured = $message; - - return [ - 'deliveredTo' => 1, - 'type' => $this->getType(), - 'results' => [['recipient' => $message->getTo()[0]['email'] ?? '', 'status' => 'sent']], - ]; - } -} - -final class MailsTest extends TestCase -{ - public function testLegacyMailPayloadIsSentByMailsWorker(): void - { - $adapter = new SpyMailAdapter(); - $registry = new Registry(); - $registry->set('smtp', static fn () => $adapter); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - - try { - $worker = new Mails(); - $worker->action( - new Message([ - 'pid' => 'pid', - 'queue' => 'v1-mails', - 'timestamp' => \time(), - 'payload' => [ - 'recipient' => 'legacy@example.test', - 'name' => 'Legacy User', - 'subject' => 'Hello {{name}}', - 'body' => 'Body {{name}}', - 'variables' => ['name' => 'Legacy'], - 'customMailOptions' => [ - 'senderEmail' => 'sender@example.test', - 'senderName' => 'Custom Sender', - 'replyToEmail' => 'reply@example.test', - 'replyToName' => 'Custom Reply', - ], - ], - ]), - new Document(['$id' => 'project-x']), - $registry, - new Log(), - new None(), - ); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - - $this->assertSame(1, $adapter->sendCount); - $this->assertInstanceOf(\Utopia\Messaging\Messages\Email::class, $adapter->captured); - - $message = $adapter->captured; - $this->assertSame('legacy@example.test', $message->getTo()[0]['email'] ?? ''); - $this->assertSame('Legacy User', $message->getTo()[0]['name'] ?? ''); - $this->assertSame('Hello Legacy', $message->getSubject()); - $this->assertSame('sender@example.test', $message->getFromEmail()); - $this->assertSame('Custom Sender', $message->getFromName()); - $this->assertSame('reply@example.test', $message->getReplyToEmail()); - $this->assertSame('Custom Reply', $message->getReplyToName()); - } -} diff --git a/tests/unit/Platform/Workers/NotificationsTest.php b/tests/unit/Platform/Workers/NotificationsTest.php deleted file mode 100644 index 96c93c42fe..0000000000 --- a/tests/unit/Platform/Workers/NotificationsTest.php +++ /dev/null @@ -1,1383 +0,0 @@ -}> */ - public array $dispatched = []; - - /** @var array */ - public array $throwOn = []; - - protected function dispatch( - array $recipient, - string $messageId, - array $payload, - Document $project, - Registry $register, - Database $dbForPlatform, - Log $log, - ): ?string { - $channel = $recipient['channel']; - $this->dispatched[] = [ - 'channel' => $channel, - 'address' => $recipient['address'], - 'signatureKey' => $recipient['signatureKey'] ?? null, - 'payload' => $payload, - ]; - - if (isset($this->throwOn[$channel])) { - throw $this->throwOn[$channel]; - } - - // Mirror the real adapters' persistence contract so the action - // loop's branching (console/email persist internally; webhook - // persists in caller) is exercised end-to-end. - if ($messageId === '') { - return null; - } - - if ($channel === NOTIFICATION_TYPE_CONSOLE || $channel === NOTIFICATION_TYPE_EMAIL) { - return $this->persistAlert($dbForPlatform, $messageId, $recipient, $payload, $project); - } - - return null; - } -} - -/** - * Worker that runs the real `dispatchConsole` (so the ConsoleAdapter writes - * the alert row) but counts how many times the action loop calls - * `persistAlert`. Used to assert that the loop does NOT double-persist for - * console recipients (Greptile P1 #3). - */ -class CountingPersistAlertNotifications extends Notifications -{ - public int $persistAlertCalls = 0; - - /** @var array */ - public array $persistedIds = []; - - protected function persistAlert(Database $dbForPlatform, string $messageId, array $recipient, array $payload, Document $project): string - { - $this->persistAlertCalls++; - $alertId = parent::persistAlert($dbForPlatform, $messageId, $recipient, $payload, $project); - $this->persistedIds[] = $alertId; - return $alertId; - } -} - -/** - * Worker that simulates a console-adapter zero-delivery outcome (e.g. - * permission denied on createDocument) without depending on a real adapter - * failure mode. - */ -class ZeroDeliveryConsoleNotifications extends Notifications -{ - protected function dispatchConsole(array $recipient, string $messageId, array $payload, Document $project, Database $dbForPlatform): ?string - { - // Simulate the Console adapter swallowing a per-recipient - // exception and reporting zero deliveries. - throw new \Exception('Console alert delivery failed: permission denied'); - } -} - -/** - * Captures the EmailMessage handed to the SMTP adapter so tests can assert - * on the rendered HTML body without touching a real mail server. - * - * Set `$throwOnSend = true` to simulate a hard SMTP failure (DNS, refused - * connection, auth error). The adapter's `send()` calls `process()` directly, - * so a throw from here propagates exactly like a real PHPMailer error. - */ -class SpyEmailAdapter extends EmailAdapter -{ - public ?EmailMessage $captured = null; - public int $sendCount = 0; - public bool $throwOnSend = false; - - public function getName(): string - { - return 'SpySMTP'; - } - - public function getMaxMessagesPerRequest(): int - { - return 1000; - } - - protected function process(EmailMessage $message): array - { - $this->sendCount++; - $this->captured = $message; - - if ($this->throwOnSend) { - throw new \Exception('SMTP unavailable'); - } - - return [ - 'deliveredTo' => 1, - 'type' => $this->getType(), - 'results' => [['recipient' => $message->getTo()[0]['email'] ?? '', 'status' => 'sent']], - ]; - } -} - -final class NotificationsTest extends TestCase -{ - private Database $database; - private Authorization $authorization; - private Registry $registry; - private Document $project; - private Log $log; - - protected function setUp(): void - { - $this->authorization = new Authorization(); - $this->authorization->addRole(Role::any()->toString()); - - $this->database = new Database(new Memory(), new Cache(new NoCache())); - $this->database - ->setAuthorization($this->authorization) - ->setDatabase('notifTests') - ->setNamespace('notif_' . \uniqid()); - - $this->database->create(); - $this->database->createCollection( - 'notifications', - [], - [], - [Permission::create(Role::any()), Permission::read(Role::any()), Permission::update(Role::any()), Permission::delete(Role::any())], - false, - ); - $this->database->createAttribute('notifications', 'messageId', Database::VAR_STRING, 255, false); - $this->database->createAttribute('notifications', 'recipientHash', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'type', Database::VAR_STRING, 64, false, 'info'); - $this->database->createAttribute('notifications', 'channel', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'projectId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'projectInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'resourceType', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'resourceId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'resourceInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'parentResourceType', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'parentResourceId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'parentResourceInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'title', Database::VAR_STRING, 256, true); - $this->database->createAttribute('notifications', 'body', Database::VAR_STRING, 16384, true); - $this->database->createAttribute('notifications', 'read', Database::VAR_BOOLEAN, 0, false, false); - $this->database->createAttribute('notifications', 'firstSeen', Database::VAR_DATETIME, 0, false); - $this->database->createAttribute('notifications', 'lastSeen', Database::VAR_DATETIME, 0, false); - - // Mirror the production `_key_recipient` UNIQUE composite index so the - // duplicate-handling branch in persistAlert (catch DuplicateException -> - // return existing alertId) is actually exercised by tests. - $this->database->createIndex( - 'notifications', - '_key_recipient', - Database::INDEX_UNIQUE, - ['messageId', 'channel', 'recipientHash'], - [Database::LENGTH_KEY, 64, 64], - [Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC], - ); - - $this->registry = new Registry(); - $this->project = new Document(['$id' => 'project-x', '$sequence' => 'project-internal-x']); - $this->log = new Log(); - } - - protected function tearDown(): void - { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); - } - - private function buildMessage(array $payload): Message - { - return new Message([ - 'pid' => 'pid', - 'queue' => 'v1-notifications', - 'timestamp' => \time(), - 'payload' => $payload, - ]); - } - - private function recipientHash( - string $channel, - string $address, - string $resourceType, - string $resourceId, - string $resourceInternalId, - string $parentResourceType = RESOURCE_TYPE_PROJECTS, - string $parentResourceId = 'project-x', - string $parentResourceInternalId = 'project-internal-x', - ): string { - return \substr(\md5( - $channel - . ':' . $address - . ':' . $resourceType - . ':' . $resourceId - . ':' . $resourceInternalId - . ':' . $parentResourceType - . ':' . $parentResourceId - . ':' . $parentResourceInternalId - ), 0, 16); - } - - private function alertId(string $messageId, string $channel, string $address, string $resourceType, string $resourceId): string - { - return \substr($messageId, 0, 19) . '_' . $this->recipientHash($channel, $address, $resourceType, $resourceId, $resourceId . '-internal'); - } - - /** - * @return array{address: string, channel: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} - */ - private function userRecipient(string $address, string $channel, string $resourceId): array - { - return [ - 'address' => $address, - 'channel' => $channel, - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => $resourceId, - 'resourceInternalId' => $resourceId . '-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-x', - 'parentResourceInternalId' => 'project-internal-x', - ]; - } - - public function testDispatchesPerChannelToCorrectAdapter(): void - { - $worker = new SpyNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user@example.test', NOTIFICATION_TYPE_EMAIL, 'user-1'), - $this->userRecipient('user-1', NOTIFICATION_TYPE_CONSOLE, 'user-1'), - $this->userRecipient('https://hooks.example.test/in', NOTIFICATION_TYPE_WEBHOOK, 'user-1'), - ], - 'subject' => 'Hi', - 'body' => 'Body', - 'deduplicationKey' => 'event-1', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertCount(3, $worker->dispatched); - $channels = \array_map(static fn ($d) => $d['channel'], $worker->dispatched); - $this->assertSame([NOTIFICATION_TYPE_EMAIL, NOTIFICATION_TYPE_CONSOLE, NOTIFICATION_TYPE_WEBHOOK], $channels); - } - - public function testPersistsOneAlertPerRecipientChannel(): void - { - $worker = new SpyNotifications(); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user-1', NOTIFICATION_TYPE_CONSOLE, 'user-1'), - $this->userRecipient('user-2', NOTIFICATION_TYPE_CONSOLE, 'user-2'), - ], - 'subject' => 'Heads up', - 'body' => 'Read me', - 'deduplicationKey' => 'evt-multi', - 'permissions' => [Permission::read(Role::any())], - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $rows = $this->database->find('notifications'); - $this->assertCount(2, $rows); - $resourceIds = \array_map(static fn (Document $row) => $row->getAttribute('resourceId'), $rows); - \sort($resourceIds); - $this->assertSame(['user-1', 'user-2'], $resourceIds); - - foreach ($rows as $row) { - $this->assertSame(\md5('evt-multi'), $row->getAttribute('messageId')); - $this->assertSame('console', $row->getAttribute('channel')); - $this->assertSame('project-x', $row->getAttribute('projectId')); - $this->assertSame('project-internal-x', $row->getAttribute('projectInternalId')); - $this->assertSame(RESOURCE_TYPE_USERS, $row->getAttribute('resourceType')); - $this->assertSame(RESOURCE_TYPE_PROJECTS, $row->getAttribute('parentResourceType')); - $this->assertSame('project-x', $row->getAttribute('parentResourceId')); - $this->assertSame('project-internal-x', $row->getAttribute('parentResourceInternalId')); - $this->assertSame('Heads up', $row->getAttribute('title')); - } - } - - public function testDedupHitShortCircuitsBeforeDispatch(): void - { - $worker = new SpyNotifications(); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [$this->userRecipient('user-1', NOTIFICATION_TYPE_CONSOLE, 'user-1')], - 'subject' => 'Sub', - 'body' => 'B', - 'deduplicationKey' => 'dup-key', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - $this->assertCount(1, $worker->dispatched); - - $worker->dispatched = []; - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - $this->assertCount(0, $worker->dispatched, 'second invocation must short-circuit on dedup hit'); - } - - public function testMissingRecipientsAndAddressThrows(): void - { - $worker = new SpyNotifications(); - $this->expectException(\Exception::class); - $this->expectExceptionMessage('No recipients in payload'); - - $worker->action( - $this->buildMessage(['project' => ['$id' => 'project-x'], 'subject' => '', 'body' => '']), - $this->project, - $this->registry, - $this->database, - $this->log, - ); - } - - public function testFallbackToLegacyRecipient(): void - { - $worker = new SpyNotifications(); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipient' => 'legacy@example.test', - 'subject' => 'X', - 'body' => 'Y', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertCount(1, $worker->dispatched); - $this->assertSame('legacy@example.test', $worker->dispatched[0]['address']); - $this->assertSame(NOTIFICATION_TYPE_EMAIL, $worker->dispatched[0]['channel']); - } - - public function testLegacyMailPayloadOptionsAreAppliedByEmailChannel(): void - { - $spy = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $spy); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - - try { - $worker = new Notifications(); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipient' => 'legacy@example.test', - 'name' => 'Legacy User', - 'subject' => 'Hello {{name}}', - 'body' => 'Body {{name}}', - 'variables' => ['name' => 'Legacy'], - 'customMailOptions' => [ - 'senderEmail' => 'sender@example.test', - 'senderName' => 'Custom Sender', - 'replyToEmail' => 'reply@example.test', - 'replyToName' => 'Custom Reply', - ], - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - - $this->assertSame(1, $spy->sendCount); - $this->assertInstanceOf(\Utopia\Messaging\Messages\Email::class, $spy->captured); - - $message = $spy->captured; - $this->assertSame('legacy@example.test', $message->getTo()[0]['email'] ?? ''); - $this->assertSame('Legacy User', $message->getTo()[0]['name'] ?? ''); - $this->assertSame('Hello Legacy', $message->getSubject()); - $this->assertSame('sender@example.test', $message->getFromEmail()); - $this->assertSame('Custom Sender', $message->getFromName()); - $this->assertSame('reply@example.test', $message->getReplyToEmail()); - $this->assertSame('Custom Reply', $message->getReplyToName()); - } - - public function testLegacyPayloadSmtpOverridesProjectSmtp(): void - { - $worker = new Notifications(); - $project = new Document([ - 'smtp' => [ - 'enabled' => true, - 'host' => 'project.smtp.test', - 'port' => 2525, - 'senderEmail' => 'project@example.test', - ], - ]); - - $reflection = new \ReflectionMethod($worker, 'resolveSmtpConfig'); - $reflection->setAccessible(true); - /** @var array $smtp */ - $smtp = $reflection->invoke($worker, $project, [ - 'smtp' => [ - 'host' => 'payload.smtp.test', - 'port' => 587, - 'senderEmail' => 'payload@example.test', - ], - ]); - - $this->assertSame('payload.smtp.test', $smtp['host']); - $this->assertSame(587, $smtp['port']); - $this->assertSame('payload@example.test', $smtp['senderEmail']); - } - - public function testLegacyMailPayloadThrowsWhenSmtpIsNotConfigured(): void - { - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST='); - - try { - $worker = new Notifications(); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipient' => 'legacy@example.test', - 'subject' => 'No SMTP', - 'body' => 'Body', - ]; - - $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, $this->log); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - } - - public function testWebhookRecipientForwardsSignatureKey(): void - { - $worker = new SpyNotifications(); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - [ - 'address' => 'https://hooks.example.test/signed', - 'channel' => NOTIFICATION_TYPE_WEBHOOK, - 'signatureKey' => 'tenant-secret', - ], - [ - 'address' => 'https://hooks.example.test/unsigned', - 'channel' => NOTIFICATION_TYPE_WEBHOOK, - ], - ], - 'subject' => 's', - 'body' => 'b', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertCount(2, $worker->dispatched); - $this->assertSame('tenant-secret', $worker->dispatched[0]['signatureKey']); - $this->assertNull($worker->dispatched[1]['signatureKey']); - } - - public function testDispatchErrorTagsLogAndPropagates(): void - { - $worker = new SpyNotifications(); - $worker->throwOn[NOTIFICATION_TYPE_WEBHOOK] = new \RuntimeException('boom'); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [$this->userRecipient('https://h.example.test', NOTIFICATION_TYPE_WEBHOOK, 'user-1')], - 'subject' => 's', - 'body' => 'b', - 'deduplicationKey' => 'err-1', - ]; - - try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - $this->fail('expected exception to propagate'); - } catch (\Throwable $error) { - $this->assertSame('boom', $error->getMessage()); - } - - $tags = $this->log->getTags(); - $this->assertSame(NOTIFICATION_TYPE_WEBHOOK, $tags['channel'] ?? null); - $this->assertSame('boom', $tags['error'] ?? null); - - $rows = $this->database->find('notifications'); - $this->assertCount(0, $rows, 'failed dispatch must not persist alert'); - } - - public function testDedupSkipsOnlyDeliveredRecipientAfterPartialFanoutFailure(): void - { - $worker = new SpyNotifications(); - $worker->throwOn[NOTIFICATION_TYPE_WEBHOOK] = new \RuntimeException('webhook down'); - - $messageId = \md5('partial-key'); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user-1', NOTIFICATION_TYPE_CONSOLE, 'user-1'), - $this->userRecipient('https://hooks.example.test/in', NOTIFICATION_TYPE_WEBHOOK, 'user-1'), - ], - 'subject' => 'Sub', - 'body' => 'B', - 'deduplicationKey' => 'partial-key', - ]; - - try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - $this->fail('expected webhook failure to propagate'); - } catch (\RuntimeException $error) { - $this->assertSame('webhook down', $error->getMessage()); - } - - $rows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - ]); - $this->assertCount(1, $rows, 'first attempt should persist only the successful console recipient'); - $this->assertSame(NOTIFICATION_TYPE_CONSOLE, $rows[0]->getAttribute('channel')); - - $retry = new SpyNotifications(); - $retry->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertCount(1, $retry->dispatched, 'retry should dispatch only the previously undelivered webhook'); - $this->assertSame(NOTIFICATION_TYPE_WEBHOOK, $retry->dispatched[0]['channel']); - - $rows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - ]); - $this->assertCount(2, $rows, 'retry must complete the missing recipient without duplicating console'); - } - - public function testConsoleChannelSkipsPersistAlert(): void - { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user-1', NOTIFICATION_TYPE_CONSOLE, 'user-1'), - ], - 'subject' => 'Heads up', - 'body' => 'console body', - 'deduplicationKey' => 'console-skip', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - // The Console adapter wrote exactly one alert; the action loop - // must NOT have called persistAlert (otherwise we'd see 2 rows or - // a duplicate-key swallow plus a non-zero counter). - $consoleRows = $this->database->find('notifications', [ - Query::equal('channel', ['console']), - ]); - $this->assertCount(1, $consoleRows); - $this->assertSame(0, $worker->persistAlertCalls, 'console channel must NOT trigger action-loop persistAlert'); - } - - public function testConsoleZeroDeliveryThrows(): void - { - $worker = new ZeroDeliveryConsoleNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user-1', NOTIFICATION_TYPE_CONSOLE, 'user-1'), - ], - 'subject' => 'Heads up', - 'body' => 'console body', - 'deduplicationKey' => 'console-fail', - ]; - - try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - $this->fail('expected console zero-delivery to throw'); - } catch (\Throwable $error) { - $this->assertStringContainsString('Console alert delivery failed', $error->getMessage()); - } - - $this->assertCount(0, $this->database->find('notifications'), 'failed console dispatch must not persist alert'); - } - - public function testMultiRecipientFanoutNoCollision(): void - { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user-1', NOTIFICATION_TYPE_CONSOLE, 'user-1'), - $this->userRecipient('user-2', NOTIFICATION_TYPE_CONSOLE, 'user-2'), - ], - 'subject' => 'Heads up', - 'body' => 'console body', - 'deduplicationKey' => 'fanout', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $rows = $this->database->find('notifications'); - $this->assertCount(2, $rows, 'two recipients must produce two distinct alert rows'); - - $messageId = \md5('fanout'); - $ids = []; - foreach ($rows as $row) { - $this->assertSame($messageId, $row->getAttribute('messageId'), 'all rows share the dedup messageId'); - $ids[] = $row->getId(); - } - $this->assertCount(2, \array_unique($ids), 'recipient suffixes must keep $id values distinct'); - } - - public function testRecipientStructRoundtripsResourceFields(): void - { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - [ - 'address' => 'console-recipient', - 'channel' => NOTIFICATION_TYPE_CONSOLE, - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => 'u1', - 'resourceInternalId' => 'u1-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-x', - 'parentResourceInternalId' => 'project-internal-x', - ], - ], - 'subject' => 'Heads up', - 'body' => 'b', - 'deduplicationKey' => 'roundtrip', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $rows = $this->database->find('notifications'); - $this->assertCount(1, $rows); - $this->assertSame(RESOURCE_TYPE_USERS, $rows[0]->getAttribute('resourceType')); - $this->assertSame('u1', $rows[0]->getAttribute('resourceId')); - $this->assertSame('u1-internal', $rows[0]->getAttribute('resourceInternalId')); - $this->assertSame(RESOURCE_TYPE_PROJECTS, $rows[0]->getAttribute('parentResourceType')); - $this->assertSame('project-x', $rows[0]->getAttribute('parentResourceId')); - $this->assertSame('project-internal-x', $rows[0]->getAttribute('parentResourceInternalId')); - } - - public function testTrackingLogoInjectedIntoEmailHtml(): void - { - $spy = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $spy); - - // Force the cloud SMTP branch (project has no smtp config) and - // provide the tracking secret so injectTrackingLogo actually runs. - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - $previousTrackingSecret = \getenv('_APP_NOTIFICATIONS_TRACKING_SECRET'); - $previousDomain = \getenv('_APP_DOMAIN'); - $previousConsoleDomain = \getenv('_APP_CONSOLE_DOMAIN'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - \putenv('_APP_NOTIFICATIONS_TRACKING_SECRET=test-key-32bytes-min-aaaaaaaaaaaaaa'); - \putenv('_APP_DOMAIN=api.example.test'); - \putenv('_APP_CONSOLE_DOMAIN=console.example.test'); - - try { - $worker = new Notifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user@example.test', NOTIFICATION_TYPE_EMAIL, 'user-7'), - ], - 'subject' => 'Heads up', - 'body' => 'plain body', - 'deduplicationKey' => 'logo-key', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - \putenv($previousTrackingSecret === false ? '_APP_NOTIFICATIONS_TRACKING_SECRET' : '_APP_NOTIFICATIONS_TRACKING_SECRET=' . $previousTrackingSecret); - \putenv($previousDomain === false ? '_APP_DOMAIN' : '_APP_DOMAIN=' . $previousDomain); - \putenv($previousConsoleDomain === false ? '_APP_CONSOLE_DOMAIN' : '_APP_CONSOLE_DOMAIN=' . $previousConsoleDomain); - } - - $this->assertInstanceOf(\Utopia\Messaging\Messages\Email::class, $spy->captured, 'SpyEmailAdapter must capture exactly one EmailMessage'); - - $body = $spy->captured->getContent(); - $this->assertStringContainsString(' must be present'); - $this->assertStringContainsString('/v1/notifications/logos/appwrite?jwt=', $body); - $this->assertStringContainsString('alt="Appwrite logo"', $body); - $this->assertStringContainsString('width="120"', $body); - $this->assertStringContainsString('height="28"', $body); - $this->assertStringNotContainsString('display:none', $body); - $this->assertStringContainsString('http://api.example.test/v1/notifications/logos/appwrite?jwt=', \html_entity_decode($body)); - $this->assertStringNotContainsString('console.example.test/v1/notifications/logos/appwrite', \html_entity_decode($body)); - - \preg_match('/logos\/appwrite\?jwt=([^"&]+)/', \html_entity_decode($body), $matches); - $this->assertNotEmpty($matches[1] ?? ''); - - $claims = (new JWT('test-key-32bytes-min-aaaaaaaaaaaaaa', 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0)) - ->decode(\urldecode($matches[1])); - $this->assertSame(\md5('logo-key'), $claims['messageId'] ?? null); - $this->assertSame(NOTIFICATION_TYPE_EMAIL, $claims['channel'] ?? null); - $this->assertSame($this->recipientHash( - NOTIFICATION_TYPE_EMAIL, - 'user@example.test', - RESOURCE_TYPE_USERS, - 'user-7', - 'user-7-internal', - ), $claims['recipientHash'] ?? null); - $this->assertSame('project-x', $claims['projectId'] ?? null); - $this->assertSame('project-internal-x', $claims['projectInternalId'] ?? null); - $this->assertSame('notification_track', $claims['purpose'] ?? null); - $this->assertArrayNotHasKey('alertId', $claims); - - // The logo must sit BEFORE the last . - $lastBodyClose = \strripos($body, ''); - $logoPosition = \strripos($body, ''); - $this->assertNotFalse($logoPosition); - $this->assertLessThan($lastBodyClose, $logoPosition, 'logo must be spliced before the final '); - } - - public function testTrackingLogoDoesNotUseOpenSslKeyFallback(): void - { - $spy = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $spy); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - $previousTrackingSecret = \getenv('_APP_NOTIFICATIONS_TRACKING_SECRET'); - $previousOpenSslKey = \getenv('_APP_OPENSSL_KEY_V1'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - \putenv('_APP_NOTIFICATIONS_TRACKING_SECRET='); - \putenv('_APP_OPENSSL_KEY_V1=openssl-key-must-not-sign-tracking'); - - try { - $worker = new Notifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user@example.test', NOTIFICATION_TYPE_EMAIL, 'user-8'), - ], - 'subject' => 'Heads up', - 'body' => 'plain body', - 'deduplicationKey' => 'logo-key-no-tracking-secret', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - \putenv($previousTrackingSecret === false ? '_APP_NOTIFICATIONS_TRACKING_SECRET' : '_APP_NOTIFICATIONS_TRACKING_SECRET=' . $previousTrackingSecret); - \putenv($previousOpenSslKey === false ? '_APP_OPENSSL_KEY_V1' : '_APP_OPENSSL_KEY_V1=' . $previousOpenSslKey); - } - - $this->assertInstanceOf(\Utopia\Messaging\Messages\Email::class, $spy->captured, 'SpyEmailAdapter must capture exactly one EmailMessage'); - $this->assertStringNotContainsString('/v1/notifications/logos/appwrite?jwt=', $spy->captured->getContent()); - } - - public function testPersistAlertReturnsExistingAlertIdOnDuplicate(): void - { - $spy = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $spy); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - - try { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user@example.test', NOTIFICATION_TYPE_EMAIL, 'user-7'), - ], - 'subject' => 'Heads up', - 'body' => 'b', - 'deduplicationKey' => 'persist-dup', - ]; - - // First dispatch: writes a row through the action loop and - // returns the deterministic alertId. - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertSame(1, $worker->persistAlertCalls); - $firstAlertId = $worker->persistedIds[0]; - - $messageId = \md5('persist-dup'); - $recipient = [ - 'address' => 'user@example.test', - 'channel' => NOTIFICATION_TYPE_EMAIL, - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => 'user-7', - 'resourceInternalId' => 'user-7-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-x', - 'parentResourceInternalId' => 'project-internal-x', - ]; - - // Second invocation with the SAME messageId/recipient. The - // action loop's alreadyDelivered() check short-circuits before - // persistAlert, so call persistAlert directly to actually hit - // the duplicate branch. The deterministic $id collides on the - // primary key -> DuplicateException -> branch returns the - // existing alertId without throwing. - $reflection = new \ReflectionMethod($worker, 'persistAlert'); - $secondAlertId = $reflection->invoke($worker, $this->database, $messageId, $recipient, $payload, $this->project); - - $this->assertSame($firstAlertId, $secondAlertId, 'duplicate persist must return the existing alertId'); - - // Third write: bypass the deterministic $id path and use a - // distinct $id with the same recipient tuple. The - // `_key_recipient` UNIQUE composite must reject it, proving - // the unique-index (not just primary-key) is what backstops the - // duplicate-handling branch. - $sameTupleDoc = new Document([ - '$id' => 'sibling-id-' . \uniqid(), - '$permissions' => [Permission::read(Role::any())], - 'messageId' => $messageId, - 'recipientHash' => $this->recipientHash(NOTIFICATION_TYPE_EMAIL, 'user@example.test', RESOURCE_TYPE_USERS, 'user-7', 'user-7-internal'), - 'channel' => NOTIFICATION_TYPE_EMAIL, - 'projectId' => 'project-x', - 'projectInternalId' => 'project-internal-x', - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => 'user-7', - 'resourceInternalId' => 'user-7-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-x', - 'parentResourceInternalId' => 'project-internal-x', - 'title' => 'sibling', - 'body' => 'sibling', - 'read' => false, - ]); - - $threw = false; - try { - $this->database->createDocument('notifications', $sameTupleDoc); - } catch (\Utopia\Database\Exception\Duplicate) { - $threw = true; - } - $this->assertTrue($threw, 'unique-index `_key_recipient` must reject a second row sharing the recipient tuple'); - - $rows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - ]); - $this->assertCount(1, $rows, 'unique-index must prevent a second row from being persisted'); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - } - - public function testPersistAlertReturnsAlertIdAndStoresResource(): void - { - $spy = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $spy); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - - try { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user@example.test', NOTIFICATION_TYPE_EMAIL, 'user-7'), - ], - 'subject' => 'Heads up', - 'body' => 'b', - 'deduplicationKey' => 'persist-email', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - - $this->assertSame(1, $worker->persistAlertCalls, 'email channel must persist exactly once'); - $this->assertCount(1, $worker->persistedIds); - - $alertId = $worker->persistedIds[0]; - $row = $this->database->getDocument('notifications', $alertId); - $this->assertFalse($row->isEmpty(), 'persistAlert must return an id resolvable via getDocument'); - $this->assertSame(RESOURCE_TYPE_USERS, $row->getAttribute('resourceType')); - $this->assertSame('user-7', $row->getAttribute('resourceId')); - $this->assertSame('user-7-internal', $row->getAttribute('resourceInternalId')); - $this->assertFalse($row->getAttribute('read'), 'new alerts default to unread'); - $this->assertSame(\md5('persist-email'), $row->getAttribute('messageId')); - } - - /** - * Reviewer C1: SMTP failure must NOT orphan a dedup row. - * - * Order in the worker matters: persist BEFORE send leaves a poisoned - * `messageId` row that the next retry will dedup-hit and never deliver. - * The fix is to persist only after a successful adapter send. A retry - * with the same payload must therefore actually deliver and produce - * exactly one alert row. - */ - public function testEmailSendFailureDoesNotPersistAlert(): void - { - $failing = new SpyEmailAdapter(); - $failing->throwOnSend = true; - $this->registry->set('smtp', static fn () => $failing); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user@example.test', NOTIFICATION_TYPE_EMAIL, 'user-9'), - ], - 'subject' => 'Subj', - 'body' => 'Body', - 'deduplicationKey' => 'smtp-fail-key', - ]; - - $messageId = \md5('smtp-fail-key'); - - try { - $worker = new Notifications(); - - $threw = false; - try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } catch (\Throwable $error) { - $threw = true; - $this->assertStringContainsString('SMTP unavailable', $error->getMessage()); - } - $this->assertTrue($threw, 'SMTP failure must propagate so the queue retries'); - $this->assertSame(1, $failing->sendCount, 'adapter must have been invoked exactly once'); - - // Critical: no orphan dedup row. If there is one, the retry below - // will short-circuit and the user never gets the email. - $orphans = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - ]); - $this->assertCount(0, $orphans, 'failed SMTP send must not leave a dedup row behind'); - - // Retry with a working adapter using the same payload — must deliver - // AND persist exactly one alert row. - $working = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $working); - - $retryWorker = new Notifications(); - $retryWorker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertSame(1, $working->sendCount, 'retry must invoke the working adapter'); - - $rows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - ]); - $this->assertCount(1, $rows, 'retry must persist exactly one alert row'); - $this->assertSame('user-9', $rows[0]->getAttribute('resourceId')); - $this->assertFalse($rows[0]->getAttribute('read')); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - } - - public function testEmailFailureDoesNotBlockConsoleRecipient(): void - { - $failing = new SpyEmailAdapter(); - $failing->throwOnSend = true; - $this->registry->set('smtp', static fn () => $failing); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - - $payload = [ - 'project' => ['$id' => 'project-x', '$sequence' => 'project-internal-x'], - 'recipients' => [ - $this->userRecipient('user@example.test', NOTIFICATION_TYPE_EMAIL, 'user-9'), - $this->userRecipient('user-9', NOTIFICATION_TYPE_CONSOLE, 'user-9'), - ], - 'subject' => 'Subj', - 'body' => 'Body', - 'deduplicationKey' => 'smtp-fail-console-key', - ]; - - $messageId = \md5('smtp-fail-console-key'); - - try { - $worker = new Notifications(); - - $threw = false; - try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } catch (\Throwable $error) { - $threw = true; - $this->assertStringContainsString('SMTP unavailable', $error->getMessage()); - } - $this->assertTrue($threw, 'SMTP failure must still propagate so the email recipient is retried'); - - $consoleRows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - Query::equal('channel', [NOTIFICATION_TYPE_CONSOLE]), - ]); - $this->assertCount(1, $consoleRows, 'console recipient must be persisted even when email fails first'); - $this->assertSame('project-x', $consoleRows[0]->getAttribute('projectId')); - $this->assertSame('project-internal-x', $consoleRows[0]->getAttribute('projectInternalId')); - - $emailRows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - Query::equal('channel', [NOTIFICATION_TYPE_EMAIL]), - ]); - $this->assertCount(0, $emailRows, 'failed email recipient must not leave an orphan dedup row'); - - $working = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $working); - - $retryWorker = new Notifications(); - $retryWorker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertSame(1, $working->sendCount, 'retry must still deliver the email recipient'); - $rows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - ]); - $this->assertCount(2, $rows, 'retry must add email without duplicating the already-delivered console alert'); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - } - - /** - * Worker happy-path: email channel. - * - * Asserts the SMTP adapter is invoked once with the expected - * to/subject/body, the rendered body carries the tracking logo before - * ``, and an alert row is persisted AFTER the send returns - * successfully (see C1: persist-after-send invariant). - */ - public function testEmailChannelHappyPath(): void - { - $spy = new SpyEmailAdapter(); - $this->registry->set('smtp', static fn () => $spy); - - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - $previousTrackingSecret = \getenv('_APP_NOTIFICATIONS_TRACKING_SECRET'); - \putenv('_APP_SMTP_HOST=spy.smtp.test'); - \putenv('_APP_NOTIFICATIONS_TRACKING_SECRET=test-key-32bytes-min-aaaaaaaaaaaaaa'); - - try { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('happy@example.test', NOTIFICATION_TYPE_EMAIL, 'user-happy'), - ], - 'subject' => 'Welcome aboard', - 'body' => 'plain body', - 'deduplicationKey' => 'happy-email', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - \putenv($previousTrackingSecret === false ? '_APP_NOTIFICATIONS_TRACKING_SECRET' : '_APP_NOTIFICATIONS_TRACKING_SECRET=' . $previousTrackingSecret); - } - - $this->assertSame(1, $spy->sendCount, 'SMTP send must be invoked exactly once'); - $this->assertInstanceOf(\Utopia\Messaging\Messages\Email::class, $spy->captured); - - $message = $spy->captured; - $this->assertSame('happy@example.test', $message->getTo()[0]['email'] ?? ''); - $this->assertSame('Welcome aboard', $message->getSubject()); - - $body = $message->getContent(); - $this->assertStringContainsString('assertStringContainsString('/v1/notifications/logos/appwrite?jwt=', $body); - - $closing = \strripos($body, ''); - $logo = \strripos($body, ''); - - $this->assertSame(1, $worker->persistAlertCalls, 'email channel must persist exactly once after a successful send'); - $messageId = \md5('happy-email'); - $rows = $this->database->find('notifications', [ - Query::equal('messageId', [$messageId]), - ]); - $this->assertCount(1, $rows); - $row = $rows[0]; - $this->assertSame('user-happy', $row->getAttribute('resourceId')); - $this->assertSame(NOTIFICATION_TYPE_EMAIL, $row->getAttribute('channel')); - $this->assertFalse($row->getAttribute('read')); - - // dispatchEmail's returned alertId must match the row $id. - $this->assertSame($worker->persistedIds[0], $row->getId()); - $this->assertLessThanOrEqual(36, \strlen($row->getId()), 'alert ids must pass the UID route validator'); - } - - /** - * Worker happy-path: console channel. - * - * The Console adapter writes the alert directly; the action loop must - * NOT call `persistAlert` for console recipients. Permissions must grant - * the recipient resource read/update/delete access. - */ - public function testConsoleChannelHappyPath(): void - { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - [ - 'address' => 'console-recipient', - 'channel' => NOTIFICATION_TYPE_CONSOLE, - 'resourceType' => RESOURCE_TYPE_TEAMS, - 'resourceId' => 't1', - 'resourceInternalId' => 't1-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-x', - 'parentResourceInternalId' => 'project-internal-x', - ], - ], - 'subject' => 'Heads up', - 'body' => 'console body', - 'deduplicationKey' => 'happy-console', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $rows = $this->database->find('notifications', [ - Query::equal('channel', ['console']), - ]); - $this->assertCount(1, $rows, 'console adapter must write exactly one alert'); - - $row = $rows[0]; - $this->assertSame(RESOURCE_TYPE_TEAMS, $row->getAttribute('resourceType')); - $this->assertSame('t1', $row->getAttribute('resourceId')); - $this->assertSame('t1-internal', $row->getAttribute('resourceInternalId')); - $this->assertSame(NOTIFICATION_TYPE_CONSOLE, $row->getAttribute('channel')); - $this->assertFalse($row->getAttribute('read')); - - $messageId = \md5('happy-console'); - $expectedId = $this->alertId($messageId, NOTIFICATION_TYPE_CONSOLE, 'console-recipient', RESOURCE_TYPE_TEAMS, 't1'); - $this->assertSame($expectedId, $row->getId(), 'row $id must match adapter suffix scheme'); - $this->assertLessThanOrEqual(36, \strlen($row->getId()), 'alert ids must pass the UID route validator'); - - $permissions = $row->getPermissions(); - $this->assertContains(Permission::read(Role::team('t1')), $permissions); - $this->assertContains(Permission::update(Role::team('t1', 'owner')), $permissions); - $this->assertContains(Permission::delete(Role::team('t1', 'owner')), $permissions); - - $this->assertSame(0, $worker->persistAlertCalls, 'console channel must NOT trigger action-loop persistAlert'); - } - - public function testConsoleChannelUsesPreviewBodyInsteadOfRenderedEmailHtml(): void - { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('user-preview', NOTIFICATION_TYPE_CONSOLE, 'user-preview'), - ], - 'subject' => 'Webhook {{name}} paused', - 'preview' => 'Plain alert for {{name}}.', - 'body' => 'Email-only HTML', - 'templateParams' => ['name' => 'orders'], - 'deduplicationKey' => 'console-preview', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $rows = $this->database->find('notifications'); - $this->assertCount(1, $rows); - $this->assertSame('Webhook orders paused', $rows[0]->getAttribute('title')); - $this->assertSame('Plain alert for orders.', $rows[0]->getAttribute('body')); - $this->assertStringNotContainsString('', $rows[0]->getAttribute('body')); - } - - public function testEmailChannelThrowsWhenSmtpIsNotConfigured(): void - { - $previousSmtpHost = \getenv('_APP_SMTP_HOST'); - \putenv('_APP_SMTP_HOST='); - $threw = false; - - try { - $worker = new CountingPersistAlertNotifications(); - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - $this->userRecipient('missing-smtp@example.test', NOTIFICATION_TYPE_EMAIL, 'user-smtp'), - ], - 'subject' => 'No SMTP', - 'body' => 'Body', - 'deduplicationKey' => 'missing-smtp', - ]; - - try { - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } catch (\Exception $error) { - $this->assertStringContainsString('No SMTP configuration has been set', $error->getMessage()); - $threw = true; - } - } finally { - \putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost); - } - - $this->assertTrue($threw, 'missing SMTP must fail email delivery so the queue can retry'); - $this->assertSame(0, $worker->persistAlertCalls); - $this->assertCount(0, $this->database->find('notifications')); - $this->assertSame('no_smtp', $this->log->getTags()['email_skipped'] ?? null); - } - - public function testConsoleChannelRejectsInvalidImplicitUserId(): void - { - $worker = new CountingPersistAlertNotifications(); - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - ['address' => 'not an appwrite user id', 'channel' => NOTIFICATION_TYPE_CONSOLE], - ], - 'subject' => 'Invalid', - 'body' => 'Body', - 'deduplicationKey' => 'invalid-console-user', - ]; - - $this->expectException(\Exception::class); - $this->expectExceptionMessage('Invalid console alert resourceId'); - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - } - - /** - * Worker happy-path: webhook channel. - * - * The webhook adapter receives a POST with the rendered subject/body, - * an `X-Appwrite-Webhook-Signature` header derived from the per-recipient - * `signatureKey`, and a single alert row is persisted by the action loop - * AFTER the send returns successfully (webhook adapters do not persist - * themselves). - * - * We swap in a worker subclass that uses the in-process `CapturingWebhook` - * adapter so we exercise the real signing path without touching the network. - */ - public function testWebhookChannelHappyPath(): void - { - $captured = []; - $worker = new class ($captured) extends CountingPersistAlertNotifications { - /** @param array> $captured */ - public function __construct(public array &$captured) - { - parent::__construct(); - } - - protected function dispatchWebhook(array $recipient, array $payload, Log $log): ?string - { - $adapter = new \Tests\Unit\Utopia\Messaging\Adapter\CapturingWebhook(); - $message = new \Appwrite\Utopia\Messaging\Messages\Webhook( - urls: [$recipient['address']], - payload: [ - 'subject' => $payload['subject'] ?? '', - 'body' => $payload['body'] ?? '', - 'template' => $payload['template'] ?? '', - 'params' => $payload['templateParams'] ?? [], - 'project' => \is_array($payload['project'] ?? null) ? ($payload['project']['$id'] ?? null) : null, - 'deduplicationKey' => $payload['deduplicationKey'] ?? '', - 'events' => $payload['events'] ?? [], - ], - signingSecret: $recipient['signatureKey'] ?? null, - ); - - $result = $adapter->send($message); - $this->captured = $adapter->captured; - - if (($result['deliveredTo'] ?? 0) === 0) { - throw new \Exception('Webhook delivery failed'); - } - return null; - } - }; - - $payload = [ - 'project' => ['$id' => 'project-x'], - 'recipients' => [ - [ - 'address' => 'https://hooks.example.test/in', - 'channel' => NOTIFICATION_TYPE_WEBHOOK, - 'signatureKey' => 'tenant-secret', - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => 'user-h', - 'resourceInternalId' => 'user-h-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-x', - 'parentResourceInternalId' => 'project-internal-x', - ], - ], - 'subject' => 'Heads up', - 'body' => 'webhook body', - 'deduplicationKey' => 'happy-webhook', - ]; - - $worker->action($this->buildMessage($payload), $this->project, $this->registry, $this->database, $this->log); - - $this->assertCount(1, $worker->captured, 'adapter must POST exactly once'); - $request = $worker->captured[0]; - - $this->assertSame('POST', $request['method']); - $this->assertSame('https://hooks.example.test/in', $request['url']); - - $sent = \json_decode($request['body'], true); - $this->assertSame('Heads up', $sent['subject']); - $this->assertSame('webhook body', $sent['body']); - - $headerLine = \implode("\n", $request['headers']); - $this->assertStringContainsString('Content-Type: application/json', $headerLine); - $this->assertStringContainsString('X-Appwrite-Webhook-Signature: sha256=', $headerLine); - - // Verify the HMAC matches the signing secret on the recipient struct. - $signature = null; - $timestamp = null; - foreach ($request['headers'] as $header) { - if (\str_starts_with($header, 'X-Appwrite-Webhook-Signature: ')) { - $signature = \substr($header, \strlen('X-Appwrite-Webhook-Signature: ')); - } elseif (\str_starts_with($header, 'X-Appwrite-Webhook-Timestamp: ')) { - $timestamp = \substr($header, \strlen('X-Appwrite-Webhook-Timestamp: ')); - } - } - $this->assertNotNull($signature); - $this->assertNotNull($timestamp); - $expected = 'sha256=' . \hash_hmac('sha256', $timestamp . '.' . $request['body'], 'tenant-secret'); - $this->assertSame($expected, $signature); - - // Action loop must persist exactly one webhook alert row AFTER the send. - $this->assertSame(1, $worker->persistAlertCalls); - $rows = $this->database->find('notifications', [ - Query::equal('messageId', [\md5('happy-webhook')]), - ]); - $this->assertCount(1, $rows); - $this->assertSame(NOTIFICATION_TYPE_WEBHOOK, $rows[0]->getAttribute('channel')); - $this->assertFalse($rows[0]->getAttribute('read')); - } -} diff --git a/tests/unit/Platform/Workers/RegistrationTest.php b/tests/unit/Platform/Workers/RegistrationTest.php deleted file mode 100644 index 81b87199c2..0000000000 --- a/tests/unit/Platform/Workers/RegistrationTest.php +++ /dev/null @@ -1,30 +0,0 @@ -assertInstanceOf(Mails::class, $service->getAction('mails')); - $this->assertInstanceOf(Notifications::class, $service->getAction('notifications')); - } - - public function testEntrypointDoesNotAliasMailsToNotifications(): void - { - $contents = \file_get_contents(__DIR__ . '/../../../../app/worker.php'); - - $this->assertIsString($contents); - $this->assertStringNotContainsString("mails' ? 'notifications'", $contents); - $this->assertStringContainsString('\'workerName\' => strtolower($workerName)', $contents); - } -} diff --git a/tests/unit/Platform/Workers/WebhooksTest.php b/tests/unit/Platform/Workers/WebhooksTest.php deleted file mode 100644 index 356db9f146..0000000000 --- a/tests/unit/Platform/Workers/WebhooksTest.php +++ /dev/null @@ -1,283 +0,0 @@ -createPlatformDatabase(); - $this->seedOwnerUser($database); - - $publisher = new MockPublisher(); - $publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications')); - $worker = new Webhooks(); - - $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); - - $payload = $events[0]; - $this->assertSame('project-1', $payload['project']['$id']); - $this->assertSame('project-internal-1', $payload['project']['$sequence']); - $this->assertSame('Webhook deliveries have been paused', $payload['subject']); - $this->assertSame('Webhook "Payments" has been paused after 10 failed delivery attempts.', $payload['preview']); - $this->assertSame('webhook:webhook-1:paused:2026-01-01T00:00:00.000+00:00', $payload['deduplicationKey']); - $this->assertSame( - \realpath(__DIR__ . '/../../../../app/config/locale/templates/email-base-styled.tpl'), - \realpath($payload['bodyTemplate']) - ); - $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->assertStringNotContainsString('{{', (string) $payload['body']); - $this->assertSame(APP_NAME, $payload['variables']['platform']); - $this->assertSame(APP_EMAIL_LOGO_URL, $payload['variables']['logoUrl']); - $this->assertCount(2, $payload['recipients']); - $this->assertSame([ - 'address' => 'user-1', - 'channel' => NOTIFICATION_TYPE_CONSOLE, - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => 'user-1', - 'resourceInternalId' => '101', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-1', - 'parentResourceInternalId' => 'project-internal-1', - ], $payload['recipients'][0]); - $this->assertSame([ - 'address' => 'owner@example.test', - 'channel' => NOTIFICATION_TYPE_EMAIL, - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => 'user-1', - 'resourceInternalId' => '101', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-1', - 'parentResourceInternalId' => 'project-internal-1', - ], $payload['recipients'][1]); - } - - public function testSendAlertPersonalizesBodyPerOwner(): void - { - $database = $this->createPlatformDatabase(); - $this->seedOwnerUser($database); - $database->createDocument('memberships', new Document([ - '$id' => 'membership-3', - 'teamInternalId' => 'team-internal-1', - 'userId' => 'user-3', - 'roles' => 'owner', - ])); - $database->createDocument('users', new Document([ - '$id' => 'user-3', - '$sequence' => 103, - 'email' => 'grace@example.test', - 'name' => 'Grace Hopper', - ])); - - $publisher = new MockPublisher(); - $publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications')); - $worker = new Webhooks(); - - $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(2, $events); - - $bodies = []; - foreach ($events as $event) { - foreach ($event['recipients'] as $recipient) { - if ($recipient['channel'] === NOTIFICATION_TYPE_EMAIL) { - $bodies[$recipient['address']] = $event['body']; - } - } - } - - $this->assertArrayHasKey('owner@example.test', $bodies); - $this->assertArrayHasKey('grace@example.test', $bodies); - $this->assertStringContainsString('Ada Lovelace', (string) $bodies['owner@example.test']); - $this->assertStringNotContainsString('Grace Hopper', (string) $bodies['owner@example.test']); - $this->assertStringContainsString('Grace Hopper', (string) $bodies['grace@example.test']); - $this->assertStringNotContainsString('Ada Lovelace', (string) $bodies['grace@example.test']); - } - - public function testSendAlertDeduplicationKeyChangesPerPauseCycle(): void - { - $database = $this->createPlatformDatabase(); - $this->seedOwnerUser($database); - $publisher = new MockPublisher(); - $publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications')); - $worker = new Webhooks(); - $project = new Document([ - '$id' => 'project-1', - '$sequence' => 'project-internal-1', - 'name' => 'Production', - 'teamInternalId' => 'team-internal-1', - 'region' => 'fra', - ]); - - foreach (['2026-01-01T00:00:00.000+00:00', '2026-01-02T00:00:00.000+00:00'] as $updatedAt) { - $worker->sendAlert( - attempts: 10, - statusCode: 500, - webhook: new Document([ - '$id' => 'webhook-1', - '$updatedAt' => $updatedAt, - 'name' => 'Payments', - 'url' => 'https://example.test/webhook', - ]), - project: $project, - dbForPlatform: $database, - publisherForNotifications: $publisherForNotifications, - plan: [] - ); - } - - $events = $publisher->getEvents('v1-notifications'); - - $this->assertCount(2, $events); - $this->assertSame('webhook:webhook-1:paused:2026-01-01T00:00:00.000+00:00', $events[0]['deduplicationKey']); - $this->assertSame('webhook:webhook-1:paused:2026-01-02T00:00:00.000+00:00', $events[1]['deduplicationKey']); - } - - #[DataProvider('ownerRoleProvider')] - public function testOwnerRoleDetectionAcceptsArrayAndCommaStringRoles(mixed $roles, bool $expected): void - { - $method = new \ReflectionMethod(Webhooks::class, 'hasOwnerRole'); - $membership = new Document([ - '$id' => 'membership-1', - 'roles' => $roles, - ]); - - $this->assertSame($expected, $method->invoke(null, $membership)); - } - - public static function ownerRoleProvider(): \Iterator - { - yield 'array owner' => [['owner'], true]; - yield 'array mixed case owner' => [['Owner'], true]; - yield 'comma string owner' => ['developer, owner', true]; - yield 'project-scoped owner string not recognized' => [['project-project-1-owner'], false]; - yield 'mixed case project-scoped owner string not recognized' => [['Project-Project-1-Owner'], false]; - yield 'comma string project-scoped owner not recognized' => ['developer, project-project-1-owner', false]; - yield 'other project owner' => [['project-project-2-owner'], false]; - yield 'non owner' => [['developer'], false]; - yield 'invalid roles' => [null, false]; - } - - private function createPlatformDatabase(): Database - { - $authorization = new Authorization(); - $authorization->addRole(Role::any()->toString()); - - $database = new Database(new Memory(), new Cache(new NoCache())); - $database - ->setAuthorization($authorization) - ->setDatabase('webhookTests') - ->setNamespace('webhook_' . \uniqid()); - - $permissions = [ - Permission::create(Role::any()), - Permission::read(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ]; - - $database->create(); - $database->createCollection('memberships', [], [], $permissions, false); - $database->createAttribute('memberships', 'teamInternalId', Database::VAR_STRING, 255, true); - $database->createAttribute('memberships', 'userId', Database::VAR_STRING, 255, true); - $database->createAttribute('memberships', 'roles', Database::VAR_STRING, 1024, true); - $database->createCollection('users', [], [], $permissions, false); - $database->createAttribute('users', 'email', Database::VAR_STRING, 320, false); - $database->createAttribute('users', 'name', Database::VAR_STRING, 256, false); - - return $database; - } - - private function seedOwnerUser(Database $database): void - { - $database->createDocument('memberships', new Document([ - '$id' => 'membership-1', - 'teamInternalId' => 'team-internal-1', - 'userId' => 'user-1', - 'roles' => 'owner', - ])); - $database->createDocument('memberships', new Document([ - '$id' => 'membership-2', - 'teamInternalId' => 'team-internal-1', - 'userId' => 'user-2', - 'roles' => 'developer', - ])); - $database->createDocument('users', new Document([ - '$id' => 'user-1', - '$sequence' => 101, - 'email' => 'owner@example.test', - 'name' => 'Ada Lovelace', - ])); - $database->createDocument('users', new Document([ - '$id' => 'user-2', - '$sequence' => 102, - 'email' => 'developer@example.test', - 'name' => 'Developer User', - ])); - } -} diff --git a/tests/unit/Utopia/Messaging/Adapter/CapturingWebhook.php b/tests/unit/Utopia/Messaging/Adapter/CapturingWebhook.php deleted file mode 100644 index 093a3cffb7..0000000000 --- a/tests/unit/Utopia/Messaging/Adapter/CapturingWebhook.php +++ /dev/null @@ -1,34 +0,0 @@ -, body: string, timeout: int}> - */ - public array $captured = []; - - /** @var array{statusCode: int, response: string|null, error: string|null} */ - public array $response = ['statusCode' => 200, 'response' => 'OK', 'error' => null]; - - protected function dispatch(string $method, string $url, array $headers, string $body, int $timeout): array - { - $this->captured[] = [ - 'method' => $method, - 'url' => $url, - 'headers' => $headers, - 'body' => $body, - 'timeout' => $timeout, - ]; - return $this->response; - } -} diff --git a/tests/unit/Utopia/Messaging/Adapter/ConsoleTest.php b/tests/unit/Utopia/Messaging/Adapter/ConsoleTest.php deleted file mode 100644 index 9f066c51ab..0000000000 --- a/tests/unit/Utopia/Messaging/Adapter/ConsoleTest.php +++ /dev/null @@ -1,282 +0,0 @@ -authorization = new Authorization(); - $this->authorization->addRole(Role::any()->toString()); - - $this->database = new Database(new Memory(), new Cache(new NoCache())); - $this->database - ->setAuthorization($this->authorization) - ->setDatabase('alertsTests') - ->setNamespace('alerts_' . \uniqid()); - - $this->database->create(); - $this->database->createCollection('notifications', [], [], [Permission::create(Role::any()), Permission::read(Role::any())], false); - $this->database->createAttribute('notifications', 'messageId', Database::VAR_STRING, 255, false); - $this->database->createAttribute('notifications', 'recipientHash', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'type', Database::VAR_STRING, 64, false, 'info'); - $this->database->createAttribute('notifications', 'channel', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'projectId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'projectInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'resourceType', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'resourceId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'resourceInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'parentResourceType', Database::VAR_STRING, 64, true); - $this->database->createAttribute('notifications', 'parentResourceId', Database::VAR_STRING, 255, true); - $this->database->createAttribute('notifications', 'parentResourceInternalId', Database::VAR_ID, 0, true); - $this->database->createAttribute('notifications', 'title', Database::VAR_STRING, 256, true); - $this->database->createAttribute('notifications', 'body', Database::VAR_STRING, 16384, true); - $this->database->createAttribute('notifications', 'read', Database::VAR_BOOLEAN, 0, false, false); - $this->database->createAttribute('notifications', 'firstSeen', Database::VAR_DATETIME, 0, false); - $this->database->createAttribute('notifications', 'lastSeen', Database::VAR_DATETIME, 0, false); - } - - protected function tearDown(): void - { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); - } - - /** - * Mirrors the per-recipient `$id` derivation in - * Appwrite\Utopia\Messaging\Adapter\Console::process(). - */ - private function alertId(string $messageId, string $address, string $resourceType, string $resourceId): string - { - $key = $address - . ':' . $resourceType - . ':' . $resourceId - . ':' . $resourceId . '-internal' - . ':projects:project-1:project-internal-1'; - return \substr($messageId, 0, 19) . '_' . \substr(\md5($key), 0, 16); - } - - /** - * @return array{address: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} - */ - private function recipient(string $address, string $resourceId, string $resourceType = RESOURCE_TYPE_USERS): array - { - return [ - 'address' => $address, - 'resourceType' => $resourceType, - 'resourceId' => $resourceId, - 'resourceInternalId' => $resourceId . '-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-1', - 'parentResourceInternalId' => 'project-internal-1', - ]; - } - - public function testWritesAlertWithCorrectSchema(): void - { - $message = new ConsoleMessage( - recipients: [$this->recipient('user-1', 'user-1')], - title: 'Hello', - body: 'World', - type: 'info', - messageId: ID::custom('msg-aaa'), - projectId: 'project-1', - projectInternalId: 'project-internal-1', - ); - - $adapter = new Console($this->database); - $result = $adapter->send($message); - - $this->assertSame(1, $result['deliveredTo']); - - $stored = $this->database->getDocument('notifications', $this->alertId('msg-aaa', 'user-1', RESOURCE_TYPE_USERS, 'user-1')); - $this->assertFalse($stored->isEmpty()); - $this->assertSame('msg-aaa', $stored->getAttribute('messageId')); - $this->assertSame('console', $stored->getAttribute('channel')); - $this->assertSame('project-1', $stored->getAttribute('projectId')); - $this->assertSame('project-internal-1', $stored->getAttribute('projectInternalId')); - $this->assertSame(RESOURCE_TYPE_USERS, $stored->getAttribute('resourceType')); - $this->assertSame('user-1', $stored->getAttribute('resourceId')); - $this->assertSame('user-1-internal', $stored->getAttribute('resourceInternalId')); - $this->assertSame(RESOURCE_TYPE_PROJECTS, $stored->getAttribute('parentResourceType')); - $this->assertSame('project-1', $stored->getAttribute('parentResourceId')); - $this->assertSame('project-internal-1', $stored->getAttribute('parentResourceInternalId')); - $this->assertSame('Hello', $stored->getAttribute('title')); - $this->assertSame('World', $stored->getAttribute('body')); - $this->assertSame('info', $stored->getAttribute('type')); - $this->assertFalse($stored->getAttribute('read')); - $this->assertNull($stored->getAttribute('firstSeen')); - $this->assertNull($stored->getAttribute('lastSeen')); - } - - public function testUserPermissionsScopedToRecipient(): void - { - $message = new ConsoleMessage( - recipients: [$this->recipient('user-2', 'user-2')], - title: 'Title', - body: 'Body', - messageId: ID::custom('msg-perms-user'), - projectId: 'project-1', - projectInternalId: 'project-internal-1', - ); - - (new Console($this->database))->send($message); - - $stored = $this->database->getDocument('notifications', $this->alertId('msg-perms-user', 'user-2', RESOURCE_TYPE_USERS, 'user-2')); - $permissions = $stored->getPermissions(); - - $this->assertContains(Permission::read(Role::user('user-2')), $permissions); - $this->assertContains(Permission::update(Role::user('user-2')), $permissions); - $this->assertContains(Permission::delete(Role::user('user-2')), $permissions); - } - - public function testTeamRecipientGrantsTeamReadAndOwnerWrite(): void - { - $message = new ConsoleMessage( - recipients: [$this->recipient('team-9', 'team-9', RESOURCE_TYPE_TEAMS)], - title: 'Heads up', - body: '...', - messageId: ID::custom('msg-team'), - projectId: 'project-1', - projectInternalId: 'project-internal-1', - ); - - (new Console($this->database))->send($message); - - $stored = $this->database->getDocument('notifications', $this->alertId('msg-team', 'team-9', RESOURCE_TYPE_TEAMS, 'team-9')); - $permissions = $stored->getPermissions(); - - $this->assertContains(Permission::read(Role::team('team-9')), $permissions); - $this->assertContains(Permission::update(Role::team('team-9', 'owner')), $permissions); - $this->assertContains(Permission::delete(Role::team('team-9', 'owner')), $permissions); - $this->assertContains(Permission::read(Role::team('team-9', 'project-project-1-owner')), $permissions); - $this->assertContains(Permission::update(Role::team('team-9', 'project-project-1-owner')), $permissions); - $this->assertContains(Permission::delete(Role::team('team-9', 'project-project-1-owner')), $permissions); - } - - public function testMultiRecipientWithSameMessageIdGeneratesDistinctIds(): void - { - $message = new ConsoleMessage( - recipients: [ - $this->recipient('a', 'a'), - $this->recipient('b', 'b'), - ], - title: 'Heads up', - body: 'multi', - messageId: ID::custom('same-msg'), - projectId: 'project-1', - projectInternalId: 'project-internal-1', - ); - - $adapter = new Console($this->database); - $result = $adapter->send($message); - - $this->assertSame(2, $result['deliveredTo']); - - $idA = $this->alertId('same-msg', 'a', RESOURCE_TYPE_USERS, 'a'); - $idB = $this->alertId('same-msg', 'b', RESOURCE_TYPE_USERS, 'b'); - - $this->assertNotSame($idA, $idB, 'recipient suffixes must be distinct'); - - $rowA = $this->database->getDocument('notifications', $idA); - $rowB = $this->database->getDocument('notifications', $idB); - $this->assertFalse($rowA->isEmpty(), 'first recipient row must exist'); - $this->assertFalse($rowB->isEmpty(), 'second recipient row must exist'); - - $this->assertSame('same-msg', $rowA->getAttribute('messageId')); - $this->assertSame('same-msg', $rowB->getAttribute('messageId')); - $this->assertSame('a', $rowA->getAttribute('resourceId')); - $this->assertSame('b', $rowB->getAttribute('resourceId')); - - $this->assertMatchesRegularExpression('/^same-msg_[0-9a-f]{16}$/', $idA); - $this->assertMatchesRegularExpression('/^same-msg_[0-9a-f]{16}$/', $idB); - } - - public function testRejectsForeignMessageType(): void - { - $adapter = new Console($this->database); - $this->expectException(\Exception::class); - $this->expectExceptionMessage('Invalid message type.'); - - // ConsoleMessage extends nothing; pass an unrelated Message implementation - $adapter->send(new WebhookMessage(urls: ['https://example.test'], payload: [])); - } - - /** - * Reviewer C4: a `DuplicateException` thrown by `createDocument` must be - * treated as a SUCCESSFUL delivery, not a failure. The adapter previously - * lumped Duplicate into the generic Throwable catch, which surfaced as a - * per-recipient `error` and caused the worker to throw, re-queueing the - * notification and never marking the duplicate as delivered. - */ - public function testConsoleAdapterTreatsDuplicateAsDelivered(): void - { - $userId = 'user-dup'; - $messageId = 'msg-dup'; - $documentId = $this->alertId($messageId, $userId, RESOURCE_TYPE_USERS, $userId); - - // Pre-insert an alert with the SAME id the adapter will compute. The - // adapter's createDocument will hit the primary-key DuplicateException - // and must treat it as a successful (idempotent) send. - $this->database->createDocument('notifications', new Document([ - '$id' => $documentId, - '$permissions' => [Permission::read(Role::any())], - 'messageId' => $messageId, - 'recipientHash' => \substr(\md5($userId . ':' . RESOURCE_TYPE_USERS . ':' . $userId . ':' . $userId . '-internal:projects:project-1:project-internal-1'), 0, 16), - 'channel' => 'console', - 'projectId' => 'project-x', - 'projectInternalId' => 'project-internal-x', - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => $userId, - 'resourceInternalId' => $userId . '-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project-1', - 'parentResourceInternalId' => 'project-internal-1', - 'title' => 'pre-existing', - 'body' => 'pre-existing', - ])); - - $message = new ConsoleMessage( - recipients: [$this->recipient($userId, $userId)], - title: 'Same alert resent', - body: 'b', - messageId: ID::custom($messageId), - projectId: 'project-x', - projectInternalId: 'project-internal-x', - ); - - $adapter = new Console($this->database); - $result = $adapter->send($message); - - $this->assertSame(1, $result['deliveredTo'], 'duplicate must count as a successful delivery'); - $this->assertCount(1, $result['results']); - $this->assertSame('success', $result['results'][0]['status'] ?? '', 'duplicate must report success status'); - $this->assertSame('', $result['results'][0]['error'] ?? 'unset', 'duplicate must not surface a per-recipient error'); - - // Still exactly ONE row: the pre-existing one. The adapter must not - // overwrite it nor create a sibling. - $rows = $this->database->find('notifications'); - $this->assertCount(1, $rows); - $this->assertSame($documentId, $rows[0]->getId()); - $this->assertSame('pre-existing', $rows[0]->getAttribute('title'), 'duplicate path must not overwrite existing row'); - } -} diff --git a/tests/unit/Utopia/Messaging/Adapter/WebhookTest.php b/tests/unit/Utopia/Messaging/Adapter/WebhookTest.php deleted file mode 100644 index 9edd6b7d0c..0000000000 --- a/tests/unit/Utopia/Messaging/Adapter/WebhookTest.php +++ /dev/null @@ -1,180 +0,0 @@ - 'Hello', - 'body' => 'World', - 'recipient' => 'ops@example.test', - 'metadata' => ['foo' => 'bar'], - ]; - - $message = new WebhookMessage( - urls: ['https://hooks.example.test/notify'], - payload: $payload, - ); - - $result = $adapter->send($message); - - $this->assertSame(1, $result['deliveredTo']); - $this->assertCount(1, $adapter->captured); - - $request = $adapter->captured[0]; - $this->assertSame('POST', $request['method']); - $this->assertSame('https://hooks.example.test/notify', $request['url']); - - $sent = \json_decode($request['body'], true); - $this->assertSame($payload, $sent); - - $headerLine = \implode("\n", $request['headers']); - $this->assertStringContainsString('Content-Type: application/json', $headerLine); - $this->assertStringContainsString('X-Appwrite-Webhook-Timestamp:', $headerLine); - } - - public function testSigningSecretProducesHmacSha256Signature(): void - { - $adapter = new CapturingWebhook(); - $payload = ['subject' => 'Signed', 'body' => 'B']; - $secret = 'super-secret'; - - $message = new WebhookMessage( - urls: ['https://hooks.example.test/signed'], - payload: $payload, - signingSecret: $secret, - ); - - $adapter->send($message); - - $headers = $adapter->captured[0]['headers']; - $body = $adapter->captured[0]['body']; - - $timestamp = null; - $signature = null; - foreach ($headers as $header) { - if (\str_starts_with($header, 'X-Appwrite-Webhook-Timestamp: ')) { - $timestamp = \substr($header, \strlen('X-Appwrite-Webhook-Timestamp: ')); - } elseif (\str_starts_with($header, 'X-Appwrite-Webhook-Signature: ')) { - $signature = \substr($header, \strlen('X-Appwrite-Webhook-Signature: ')); - } - } - - $this->assertNotNull($timestamp, 'timestamp header must be present'); - $this->assertNotNull($signature, 'signature header must be present when secret is set'); - $this->assertStringStartsWith('sha256=', $signature); - - $expected = 'sha256=' . \hash_hmac('sha256', $timestamp . '.' . $body, $secret); - $this->assertSame($expected, $signature); - } - - public function testNoSecretLeavesPayloadUnsigned(): void - { - $adapter = new CapturingWebhook(); - $message = new WebhookMessage( - urls: ['https://hooks.example.test/unsigned'], - payload: ['x' => 1], - signingSecret: null, - ); - - $adapter->send($message); - - $headerLine = \implode("\n", $adapter->captured[0]['headers']); - $this->assertStringNotContainsString('X-Appwrite-Webhook-Signature', $headerLine); - } - - public function testEmptySecretIsTreatedAsUnsigned(): void - { - $adapter = new CapturingWebhook(); - $message = new WebhookMessage( - urls: ['https://hooks.example.test/empty-secret'], - payload: ['x' => 1], - signingSecret: '', - ); - - $adapter->send($message); - - $headerLine = \implode("\n", $adapter->captured[0]['headers']); - $this->assertStringNotContainsString('X-Appwrite-Webhook-Signature', $headerLine); - } - - public function testTwoXxIsSuccess(): void - { - $adapter = new CapturingWebhook(); - $adapter->response = ['statusCode' => 204, 'response' => '', 'error' => null]; - $message = new WebhookMessage(urls: ['https://hooks.example.test/ok'], payload: []); - - $result = $adapter->send($message); - - $this->assertSame(1, $result['deliveredTo']); - } - - public function testNonTwoXxSurfacesError(): void - { - $adapter = new CapturingWebhook(); - $adapter->response = ['statusCode' => 503, 'response' => 'Server', 'error' => null]; - $message = new WebhookMessage(urls: ['https://hooks.example.test/fail'], payload: []); - - $result = $adapter->send($message); - - $this->assertSame(0, $result['deliveredTo']); - $error = $result['results'][0]['error'] ?? null; - $this->assertSame('HTTP 503', $error); - } - - public function testCurlErrorSurfacesAsResultError(): void - { - $adapter = new CapturingWebhook(); - $adapter->response = ['statusCode' => 0, 'response' => null, 'error' => 'connection refused']; - $message = new WebhookMessage(urls: ['https://hooks.example.test/down'], payload: []); - - $result = $adapter->send($message); - - $this->assertSame(0, $result['deliveredTo']); - $this->assertSame('connection refused', $result['results'][0]['error']); - } - - public function testCustomHeadersForwarded(): void - { - $adapter = new CapturingWebhook(); - $message = new WebhookMessage( - urls: ['https://hooks.example.test/with-headers'], - payload: [], - headers: ['X-Custom' => 'value'], - ); - - $adapter->send($message); - - $headerLine = \implode("\n", $adapter->captured[0]['headers']); - $this->assertStringContainsString('X-Custom: value', $headerLine); - } - - public function testRejectsForeignMessageType(): void - { - $adapter = new CapturingWebhook(); - $this->expectException(\Exception::class); - $this->expectExceptionMessage('Invalid message type.'); - - $adapter->send(new \Appwrite\Utopia\Messaging\Messages\Console( - recipients: [[ - 'address' => 'u', - 'resourceType' => RESOURCE_TYPE_USERS, - 'resourceId' => 'u', - 'resourceInternalId' => 'u-internal', - 'parentResourceType' => RESOURCE_TYPE_PROJECTS, - 'parentResourceId' => 'project', - 'parentResourceInternalId' => 'project-internal', - ]], - title: 't', - body: 'b', - )); - } -}