appwrite/app/controllers/shared/api.php

861 lines
36 KiB
PHP
Raw Normal View History

2019-05-09 06:54:39 +00:00
<?php
2019-10-01 04:57:41 +00:00
2021-01-11 21:52:05 +00:00
use Appwrite\Auth\Auth;
use Appwrite\Auth\Key;
2024-03-01 02:08:30 +00:00
use Appwrite\Auth\MFA\Type\TOTP;
2022-05-26 11:51:08 +00:00
use Appwrite\Event\Audit;
2024-02-20 11:40:55 +00:00
use Appwrite\Event\Build;
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 10:51:49 +00:00
use Appwrite\Event\Database as EventDatabase;
2022-05-26 11:51:08 +00:00
use Appwrite\Event\Delete;
2022-04-04 06:30:07 +00:00
use Appwrite\Event\Event;
2022-11-15 18:13:17 +00:00
use Appwrite\Event\Func;
use Appwrite\Event\Messaging;
2024-11-04 15:20:43 +00:00
use Appwrite\Event\Realtime;
2025-01-30 04:53:53 +00:00
use Appwrite\Event\StatsUsage;
2024-11-04 15:05:54 +00:00
use Appwrite\Event\Webhook;
2024-03-06 17:34:21 +00:00
use Appwrite\Extend\Exception;
2024-03-07 23:30:23 +00:00
use Appwrite\Extend\Exception as AppwriteException;
use Appwrite\SDK\Method;
2022-05-26 11:51:08 +00:00
use Appwrite\Utopia\Request;
2024-03-06 17:34:21 +00:00
use Appwrite\Utopia\Response;
2019-11-29 18:23:29 +00:00
use Utopia\Abuse\Abuse;
2024-03-06 17:34:21 +00:00
use Utopia\App;
use Utopia\Cache\Adapter\Filesystem;
use Utopia\Cache\Cache;
2024-03-06 17:34:21 +00:00
use Utopia\Config\Config;
2022-05-26 11:51:08 +00:00
use Utopia\Database\Database;
2022-08-31 08:52:55 +00:00
use Utopia\Database\DateTime;
2021-10-07 15:35:17 +00:00
use Utopia\Database\Document;
use Utopia\Database\Helpers\Role;
2024-03-06 17:34:21 +00:00
use Utopia\Database\Validator\Authorization;
2025-01-29 14:13:58 +00:00
use Utopia\Queue\Publisher;
2024-04-01 11:02:47 +00:00
use Utopia\System\System;
2024-04-01 11:08:46 +00:00
use Utopia\Validator\WhiteList;
2019-11-29 18:23:29 +00:00
2022-08-16 12:28:30 +00:00
$parseLabel = function (string $label, array $responsePayload, array $requestParams, Document $user) {
preg_match_all('/{(.*?)}/', $label, $matches);
foreach ($matches[1] ?? [] as $pos => $match) {
$find = $matches[0][$pos];
$parts = explode('.', $match);
if (count($parts) !== 2) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, "The server encountered an error while parsing the label: $label. Please create an issue on GitHub to allow us to investigate further https://github.com/appwrite/appwrite/issues/new/choose");
2022-08-16 12:28:30 +00:00
}
$namespace = $parts[0] ?? '';
$replace = $parts[1] ?? '';
$params = match ($namespace) {
'user' => (array)$user,
'request' => $requestParams,
default => $responsePayload,
};
if (array_key_exists($replace, $params)) {
$label = \str_replace($find, $params[$replace], $label);
}
}
return $label;
};
2019-11-29 18:23:29 +00:00
2025-01-04 07:25:20 +00:00
$eventDatabaseListener = function (Document $project, Document $document, Response $response, Event $queueForEvents, Func $queueForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime) {
2024-11-04 15:20:43 +00:00
// Only trigger events for user creation with the database listener.
if ($document->getCollection() !== 'users') {
2024-11-01 15:24:29 +00:00
return;
2024-10-30 18:18:37 +00:00
}
2024-11-01 16:29:34 +00:00
$queueForEvents
2024-11-05 14:17:41 +00:00
->setEvent('users.[userId].create')
2024-11-01 16:29:34 +00:00
->setParam('userId', $document->getId())
->setPayload($response->output($document, Response::MODEL_USER));
2024-11-04 15:05:54 +00:00
// Trigger functions, webhooks, and realtime events
2024-11-04 15:20:43 +00:00
$queueForFunctions
->from($queueForEvents)
->trigger();
/** Trigger webhooks events only if a project has them enabled */
2025-01-17 11:48:19 +00:00
if (!empty($project->getAttribute('webhooks'))) {
$queueForWebhooks
->from($queueForEvents)
->trigger();
2024-11-04 15:20:43 +00:00
}
/** Trigger realtime events only for non console events */
if ($queueForEvents->getProject()->getId() !== 'console') {
$queueForRealtime
->from($queueForEvents)
->trigger();
}
2024-10-29 10:51:40 +00:00
};
2023-10-25 07:39:59 +00:00
2025-01-30 04:53:53 +00:00
$usageDatabaseListener = function (string $event, Document $document, StatsUsage $queueForStatsUsage) {
2023-10-25 07:39:59 +00:00
$value = 1;
2024-11-12 06:43:36 +00:00
2025-05-08 09:08:23 +00:00
switch ($event) {
case Database::EVENT_DOCUMENT_DELETE:
$value = -1;
break;
case Database::EVENT_DOCUMENTS_DELETE:
$value = -1 * $document->getAttribute('modified', 0);
break;
case Database::EVENT_DOCUMENTS_CREATE:
$value = $document->getAttribute('modified', 0);
break;
case Database::EVENT_DOCUMENTS_UPSERT:
$value = $document->getAttribute('created', 0);
break;
2024-12-02 07:43:19 +00:00
}
2023-10-25 07:39:59 +00:00
switch (true) {
case $document->getCollection() === 'teams':
$queueForStatsUsage->addMetric(METRIC_TEAMS, $value); // per project
2023-05-23 13:43:03 +00:00
break;
2023-10-25 07:39:59 +00:00
case $document->getCollection() === 'users':
$queueForStatsUsage->addMetric(METRIC_USERS, $value); // per project
2023-10-25 07:39:59 +00:00
if ($event === Database::EVENT_DOCUMENT_DELETE) {
$queueForStatsUsage->addReduce($document);
2023-10-25 07:39:59 +00:00
}
2022-10-30 05:14:46 +00:00
break;
2023-10-25 07:39:59 +00:00
case $document->getCollection() === 'sessions': // sessions
$queueForStatsUsage->addMetric(METRIC_SESSIONS, $value); //per project
2022-10-30 05:14:46 +00:00
break;
2023-10-25 07:39:59 +00:00
case $document->getCollection() === 'databases': // databases
$queueForStatsUsage->addMetric(METRIC_DATABASES, $value); // per project
2023-10-25 07:39:59 +00:00
if ($event === Database::EVENT_DOCUMENT_DELETE) {
$queueForStatsUsage->addReduce($document);
2023-10-25 07:39:59 +00:00
}
2023-05-23 13:43:03 +00:00
break;
2023-10-25 07:39:59 +00:00
case str_starts_with($document->getCollection(), 'database_') && !str_contains($document->getCollection(), 'collection'): //collections
$parts = explode('_', $document->getCollection());
$databaseInternalId = $parts[1] ?? 0;
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addMetric(METRIC_COLLECTIONS, $value) // per project
2025-02-12 07:34:38 +00:00
->addMetric(str_replace('{databaseInternalId}', $databaseInternalId, METRIC_DATABASE_ID_COLLECTIONS), $value);
2023-10-25 07:39:59 +00:00
if ($event === Database::EVENT_DOCUMENT_DELETE) {
$queueForStatsUsage->addReduce($document);
2023-10-15 17:41:09 +00:00
}
2023-05-23 13:43:03 +00:00
break;
2023-10-25 07:39:59 +00:00
case str_starts_with($document->getCollection(), 'database_') && str_contains($document->getCollection(), '_collection_'): //documents
$parts = explode('_', $document->getCollection());
$databaseInternalId = $parts[1] ?? 0;
$collectionInternalId = $parts[3] ?? 0;
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addMetric(METRIC_DOCUMENTS, $value) // per project
->addMetric(str_replace('{databaseInternalId}', $databaseInternalId, METRIC_DATABASE_ID_DOCUMENTS), $value) // per database
->addMetric(str_replace(['{databaseInternalId}', '{collectionInternalId}'], [$databaseInternalId, $collectionInternalId], METRIC_DATABASE_ID_COLLECTION_ID_DOCUMENTS), $value); // per collection
break;
case $document->getCollection() === 'buckets': //buckets
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addMetric(METRIC_BUCKETS, $value); // per project
if ($event === Database::EVENT_DOCUMENT_DELETE) {
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addReduce($document);
}
break;
case str_starts_with($document->getCollection(), 'bucket_'): // files
$parts = explode('_', $document->getCollection());
$bucketInternalId = $parts[1];
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addMetric(METRIC_FILES, $value) // per project
->addMetric(METRIC_FILES_STORAGE, $document->getAttribute('sizeOriginal') * $value) // per project
->addMetric(str_replace('{bucketInternalId}', $bucketInternalId, METRIC_BUCKET_ID_FILES), $value) // per bucket
->addMetric(str_replace('{bucketInternalId}', $bucketInternalId, METRIC_BUCKET_ID_FILES_STORAGE), $document->getAttribute('sizeOriginal') * $value); // per bucket
break;
case $document->getCollection() === 'functions':
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addMetric(METRIC_FUNCTIONS, $value); // per project
if ($event === Database::EVENT_DOCUMENT_DELETE) {
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addReduce($document);
2023-10-15 17:41:09 +00:00
}
2023-05-23 13:43:03 +00:00
break;
2023-10-25 07:39:59 +00:00
case $document->getCollection() === 'deployments':
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addMetric(METRIC_DEPLOYMENTS, $value) // per project
->addMetric(METRIC_DEPLOYMENTS_STORAGE, $document->getAttribute('size') * $value) // per project
->addMetric(str_replace(['{resourceType}', '{resourceInternalId}'], [$document->getAttribute('resourceType'), $document->getAttribute('resourceInternalId')], METRIC_FUNCTION_ID_DEPLOYMENTS), $value) // per function
2023-10-25 07:39:59 +00:00
->addMetric(str_replace(['{resourceType}', '{resourceInternalId}'], [$document->getAttribute('resourceType'), $document->getAttribute('resourceInternalId')], METRIC_FUNCTION_ID_DEPLOYMENTS_STORAGE), $document->getAttribute('size') * $value);
break;
default:
break;
2022-10-30 05:14:46 +00:00
}
};
App::init()
->groups(['api'])
->inject('utopia')
->inject('request')
->inject('dbForPlatform')
2024-11-20 04:29:57 +00:00
->inject('dbForProject')
->inject('queueForAudits')
->inject('project')
->inject('user')
->inject('session')
->inject('servers')
->inject('mode')
->inject('team')
->inject('apiKey')
->action(function (App $utopia, Request $request, Database $dbForPlatform, Database $dbForProject, Audit $queueForAudits, Document $project, Document $user, ?Document $session, array $servers, string $mode, Document $team, ?Key $apiKey) {
$route = $utopia->getRoute();
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
2024-07-23 22:47:46 +00:00
$roles = Config::getParam('roles', []);
$role = $user->isEmpty()
? Role::guests()->toString()
: Role::users()->toString();
2024-07-23 19:49:11 +00:00
$scopes = $roles[$role]['scopes'];
2024-05-06 09:55:59 +00:00
// API Key authentication
2024-05-14 11:58:31 +00:00
if (!empty($apiKey)) {
2024-02-20 11:45:11 +00:00
if (!$user->isEmpty()) {
throw new Exception(Exception::USER_API_KEY_AND_SESSION_SET);
}
2025-02-12 08:22:08 +00:00
if ($apiKey->isExpired()) {
throw new Exception(Exception::PROJECT_KEY_EXPIRED);
2024-05-16 08:39:15 +00:00
}
2024-05-14 11:58:31 +00:00
2025-02-12 07:34:38 +00:00
$role = $apiKey->getRole();
$scopes = $apiKey->getScopes();
2025-02-12 07:34:38 +00:00
// Disable authorization checks for API keys
Authorization::setDefaultStatus(false);
2025-02-12 07:34:38 +00:00
if ($apiKey->getRole() === Auth::USER_ROLE_APPS) {
2025-02-12 08:25:53 +00:00
$user = new Document([
'$id' => '',
'status' => true,
'type' => Auth::ACTIVITY_TYPE_APP,
'email' => 'app.' . $project->getId() . '@service.' . $request->getHostname(),
'password' => '',
'name' => $apiKey->getName(),
]);
2024-05-06 08:35:27 +00:00
2025-02-12 07:34:38 +00:00
$queueForAudits->setUser($user);
}
if ($apiKey->getType() === API_KEY_STANDARD) {
$dbKey = $project->find(
key: 'secret',
find: $request->getHeader('x-appwrite-key', ''),
subject: 'keys'
);
2024-05-06 09:55:59 +00:00
2025-04-15 22:50:53 +00:00
if (!$dbKey) {
throw new Exception(Exception::USER_UNAUTHORIZED);
}
2024-05-06 09:55:59 +00:00
2025-04-15 22:50:53 +00:00
$accessedAt = $dbKey->getAttribute('accessedAt', '');
2024-05-06 09:55:59 +00:00
2025-04-15 22:50:53 +00:00
if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_KEY_ACCESS)) > $accessedAt) {
$dbKey->setAttribute('accessedAt', DateTime::now());
$dbForPlatform->updateDocument('keys', $dbKey->getId(), $dbKey);
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
}
2024-05-06 08:35:27 +00:00
2025-04-15 22:50:53 +00:00
$sdkValidator = new WhiteList($servers, true);
$sdk = $request->getHeader('x-sdk-name', 'UNKNOWN');
2025-04-15 22:50:53 +00:00
if ($sdkValidator->isValid($sdk)) {
$sdks = $dbKey->getAttribute('sdks', []);
2024-05-06 09:55:59 +00:00
2025-04-15 22:50:53 +00:00
if (!in_array($sdk, $sdks)) {
$sdks[] = $sdk;
$dbKey->setAttribute('sdks', $sdks);
2025-04-15 22:50:53 +00:00
/** Update access time as well */
$dbKey->setAttribute('accessedAt', Datetime::now());
$dbForPlatform->updateDocument('keys', $dbKey->getId(), $dbKey);
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
}
}
2025-04-15 22:50:53 +00:00
$queueForAudits->setUser($user);
}
2025-02-12 07:34:38 +00:00
} // Admin User Authentication
2024-09-24 01:19:05 +00:00
elseif (($project->getId() === 'console' && !$team->isEmpty() && !$user->isEmpty()) || ($project->getId() !== 'console' && !$user->isEmpty() && $mode === APP_MODE_ADMIN)) {
$teamId = $team->getId();
2024-07-23 19:49:11 +00:00
$adminRoles = [];
$memberships = $user->getAttribute('memberships', []);
foreach ($memberships as $membership) {
2024-07-23 22:47:46 +00:00
if ($membership->getAttribute('confirm', false) === true && $membership->getAttribute('teamId') === $teamId) {
2024-07-23 19:49:11 +00:00
$adminRoles = $membership->getAttribute('roles', []);
break;
}
}
2024-07-23 19:49:11 +00:00
if (empty($adminRoles)) {
throw new Exception(Exception::USER_UNAUTHORIZED);
}
$scopes = []; // Reset scope if admin
2024-08-21 05:51:37 +00:00
foreach ($adminRoles as $role) {
2024-07-23 22:47:46 +00:00
$scopes = \array_merge($scopes, $roles[$role]['scopes']);
}
2024-10-08 07:54:40 +00:00
Authorization::setDefaultStatus(false); // Cancel security segmentation for admin users.
2024-07-23 19:49:11 +00:00
}
2024-07-23 19:54:52 +00:00
2024-07-23 19:49:11 +00:00
$scopes = \array_unique($scopes);
2024-10-08 07:54:40 +00:00
Authorization::setRole($role);
foreach (Auth::getRoles($user) as $authRole) {
Authorization::setRole($authRole);
}
// Update project last activity
2024-11-20 04:29:57 +00:00
if (!$project->isEmpty() && $project->getId() !== 'console') {
$accessedAt = $project->getAttribute('accessedAt', '');
if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_PROJECT_ACCESS)) > $accessedAt) {
$project->setAttribute('accessedAt', DateTime::now());
Authorization::skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $project));
2024-11-20 04:29:57 +00:00
}
}
// Update user last activity
2024-11-26 08:59:03 +00:00
if (!empty($user->getId())) {
2024-11-20 04:29:57 +00:00
$accessedAt = $user->getAttribute('accessedAt', '');
if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_USER_ACCESS)) > $accessedAt) {
$user->setAttribute('accessedAt', DateTime::now());
if (APP_MODE_ADMIN !== $mode) {
$dbForProject->updateDocument('users', $user->getId(), $user);
} else {
$dbForPlatform->updateDocument('users', $user->getId(), $user);
2024-11-20 04:29:57 +00:00
}
}
}
2024-12-16 05:59:01 +00:00
/**
* @var ?Method $method
2024-12-16 05:59:01 +00:00
*/
$method = $route->getLabel('sdk', false);
2025-03-27 08:03:28 +00:00
// Take the first method if there's more than one,
// namespace can not differ between methods on the same route
if (\is_array($method)) {
2025-01-10 05:23:04 +00:00
$method = $method[0];
}
2024-12-16 05:59:01 +00:00
if (!empty($method)) {
$namespace = $method->getNamespace();
if (
2024-12-16 05:59:01 +00:00
array_key_exists($namespace, $project->getAttribute('services', []))
&& !$project->getAttribute('services', [])[$namespace]
&& !(Auth::isPrivilegedUser(Authorization::getRoles()) || Auth::isAppUser(Authorization::getRoles()))
) {
throw new Exception(Exception::GENERAL_SERVICE_DISABLED);
}
}
// Do now allow access if scope is not allowed
2024-07-23 19:49:11 +00:00
$scope = $route->getLabel('scope', 'none');
if (!\in_array($scope, $scopes)) {
throw new Exception(Exception::GENERAL_UNAUTHORIZED_SCOPE, $user->getAttribute('email', 'User') . ' (role: ' . \strtolower($roles[$role]['label']) . ') missing scope (' . $scope . ')');
}
// Do not allow access to blocked accounts
if (false === $user->getAttribute('status')) { // Account is blocked
throw new Exception(Exception::USER_BLOCKED);
}
if ($user->getAttribute('reset')) {
throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED);
}
2024-04-17 09:10:33 +00:00
$mfaEnabled = $user->getAttribute('mfa', false);
$hasVerifiedEmail = $user->getAttribute('emailVerification', false);
$hasVerifiedPhone = $user->getAttribute('phoneVerification', false);
$hasVerifiedAuthenticator = TOTP::getAuthenticatorFromUser($user)?->getAttribute('verified') ?? false;
$hasMoreFactors = $hasVerifiedEmail || $hasVerifiedPhone || $hasVerifiedAuthenticator;
$minimumFactors = ($mfaEnabled && $hasMoreFactors) ? 2 : 1;
if (!in_array('mfa', $route->getGroups())) {
if ($session && \count($session->getAttribute('factors', [])) < $minimumFactors) {
2024-04-17 09:10:33 +00:00
throw new Exception(Exception::USER_MORE_FACTORS_REQUIRED);
}
}
});
2022-07-22 06:00:42 +00:00
App::init()
2022-08-02 01:10:48 +00:00
->groups(['api'])
2022-07-22 06:00:42 +00:00
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('user')
2025-01-29 14:13:58 +00:00
->inject('publisher')
2022-12-20 16:11:30 +00:00
->inject('queueForEvents')
->inject('queueForMessaging')
2022-12-20 16:11:30 +00:00
->inject('queueForAudits')
->inject('queueForDeletes')
->inject('queueForDatabase')
2024-02-20 11:40:55 +00:00
->inject('queueForBuilds')
2025-01-30 04:53:53 +00:00
->inject('queueForStatsUsage')
2022-07-22 06:00:42 +00:00
->inject('dbForProject')
2024-12-20 14:44:50 +00:00
->inject('timelimit')
2022-07-22 06:00:42 +00:00
->inject('mode')
->inject('apiKey')
2025-04-03 02:44:29 +00:00
->inject('plan')
->action(function (App $utopia, Request $request, Response $response, Document $project, Document $user, Publisher $publisher, Event $queueForEvents, Messaging $queueForMessaging, Audit $queueForAudits, Delete $queueForDeletes, EventDatabase $queueForDatabase, Build $queueForBuilds, StatsUsage $queueForStatsUsage, Database $dbForProject, callable $timelimit, string $mode, ?Key $apiKey, array $plan) use ($usageDatabaseListener, $eventDatabaseListener) {
2022-07-22 06:00:42 +00:00
2023-02-19 11:04:12 +00:00
$route = $utopia->getRoute();
2022-07-22 06:00:42 +00:00
2024-03-04 22:12:54 +00:00
if (
array_key_exists('rest', $project->getAttribute('apis', []))
&& !$project->getAttribute('apis', [])['rest']
&& !(Auth::isPrivilegedUser(Authorization::getRoles()) || Auth::isAppUser(Authorization::getRoles()))
) {
throw new AppwriteException(AppwriteException::GENERAL_API_DISABLED);
}
/*
2022-07-22 06:00:42 +00:00
* Abuse Check
*/
2022-08-11 23:53:52 +00:00
$abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}');
$timeLimitArray = [];
2021-06-07 05:17:29 +00:00
2022-07-22 06:00:42 +00:00
$abuseKeyLabel = (!is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel;
2021-06-07 05:17:29 +00:00
2022-08-11 23:53:52 +00:00
foreach ($abuseKeyLabel as $abuseKey) {
$start = $request->getContentRangeStart();
$end = $request->getContentRangeEnd();
2024-12-20 14:44:50 +00:00
$timeLimit = $timelimit($abuseKey, $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600));
2022-08-11 23:53:52 +00:00
$timeLimit
2024-02-12 01:18:19 +00:00
->setParam('{projectId}', $project->getId())
2023-05-23 13:43:03 +00:00
->setParam('{userId}', $user->getId())
->setParam('{userAgent}', $request->getUserAgent(''))
->setParam('{ip}', $request->getIP())
->setParam('{url}', $request->getHostname() . $route->getPath())
->setParam('{method}', $request->getMethod())
->setParam('{chunkId}', (int)($start / ($end + 1 - $start)));
2022-08-11 23:53:52 +00:00
$timeLimitArray[] = $timeLimit;
}
2021-06-07 05:17:29 +00:00
2022-07-22 06:00:42 +00:00
$closestLimit = null;
2021-06-07 05:17:29 +00:00
2022-07-22 06:00:42 +00:00
$roles = Authorization::getRoles();
$isPrivilegedUser = Auth::isPrivilegedUser($roles);
$isAppUser = Auth::isAppUser($roles);
2021-06-07 05:17:29 +00:00
2022-07-22 06:00:42 +00:00
foreach ($timeLimitArray as $timeLimit) {
foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys
if (!empty($value)) {
$timeLimit->setParam('{param-' . $key . '}', (\is_array($value)) ? \json_encode($value) : $value);
}
}
2021-06-07 05:17:29 +00:00
2022-07-22 06:00:42 +00:00
$abuse = new Abuse($timeLimit);
$remaining = $timeLimit->remaining();
$limit = $timeLimit->limit();
2024-12-20 14:44:50 +00:00
$time = $timeLimit->time() + $route->getLabel('abuse-time', 3600);
2022-07-22 06:00:42 +00:00
if ($limit && ($remaining < $closestLimit || is_null($closestLimit))) {
$closestLimit = $remaining;
2022-07-22 06:00:42 +00:00
$response
->addHeader('X-RateLimit-Limit', $limit)
->addHeader('X-RateLimit-Remaining', $remaining)
->addHeader('X-RateLimit-Reset', $time);
2021-02-28 18:36:13 +00:00
}
2021-06-07 05:17:29 +00:00
2024-04-01 11:02:47 +00:00
$enabled = System::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled';
2022-07-22 06:00:42 +00:00
if (
$enabled // Abuse is enabled
&& !$isAppUser // User is not API key
&& !$isPrivilegedUser // User is not an admin
&& $abuse->check() // Route is rate-limited
) {
2022-08-08 14:44:07 +00:00
throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED);
2021-02-28 18:36:13 +00:00
}
}
2021-01-05 12:22:20 +00:00
2022-11-16 05:30:57 +00:00
/*
* Background Jobs
*/
2022-12-20 16:11:30 +00:00
$queueForEvents
2022-07-22 06:00:42 +00:00
->setEvent($route->getLabel('event', ''))
->setProject($project)
2022-08-11 13:47:53 +00:00
->setUser($user);
2022-04-04 06:30:07 +00:00
2022-12-20 16:11:30 +00:00
$queueForAudits
2022-07-22 06:00:42 +00:00
->setMode($mode)
->setUserAgent($request->getUserAgent(''))
->setIP($request->getIP())
2025-01-03 10:00:55 +00:00
->setHostname($request->getHostname())
2022-09-04 08:23:24 +00:00
->setEvent($route->getLabel('audits.event', ''))
->setProject($project);
2025-01-21 06:37:03 +00:00
/* If a session exists, use the user associated with the session */
if (!$user->isEmpty()) {
2025-01-21 06:41:20 +00:00
$userClone = clone $user;
2025-01-14 08:17:01 +00:00
// $user doesn't support `type` and can cause unintended effects.
2025-01-21 06:41:20 +00:00
$userClone->setAttribute('type', Auth::ACTIVITY_TYPE_USER);
$queueForAudits->setUser($userClone);
}
2021-02-28 18:36:13 +00:00
if (!empty($apiKey) && !empty($apiKey->getDisabledMetrics())) {
foreach ($apiKey->getDisabledMetrics() as $key) {
$queueForStatsUsage->disableMetric($key);
}
}
2022-12-20 16:11:30 +00:00
$queueForDeletes->setProject($project);
$queueForDatabase->setProject($project);
2024-02-20 11:40:55 +00:00
$queueForBuilds->setProject($project);
2024-02-20 12:06:35 +00:00
$queueForMessaging->setProject($project);
2022-08-09 11:57:33 +00:00
2024-11-05 13:35:35 +00:00
// Clone the queues, to prevent events triggered by the database listener
2024-11-04 15:05:54 +00:00
// from overwriting the events that are supposed to be triggered in the shutdown hook.
2025-01-29 14:13:58 +00:00
$queueForEventsClone = new Event($publisher);
$queueForFunctions = new Func($publisher);
$queueForWebhooks = new Webhook($publisher);
2024-11-05 14:50:32 +00:00
$queueForRealtime = new Realtime();
2024-11-01 15:24:29 +00:00
2023-10-25 07:39:59 +00:00
$dbForProject
2025-01-30 04:53:53 +00:00
->on(Database::EVENT_DOCUMENT_CREATE, 'calculate-usage', fn ($event, $document) => $usageDatabaseListener($event, $document, $queueForStatsUsage))
->on(Database::EVENT_DOCUMENT_DELETE, 'calculate-usage', fn ($event, $document) => $usageDatabaseListener($event, $document, $queueForStatsUsage))
->on(Database::EVENT_DOCUMENTS_CREATE, 'calculate-usage', fn ($event, $document) => $usageDatabaseListener($event, $document, $queueForStatsUsage))
->on(Database::EVENT_DOCUMENTS_DELETE, 'calculate-usage', fn ($event, $document) => $usageDatabaseListener($event, $document, $queueForStatsUsage))
2025-05-08 09:57:20 +00:00
->on(Database::EVENT_DOCUMENTS_UPSERT, 'calculate-usage', fn ($event, $document) => $usageDatabaseListener($event, $document, $queueForStatsUsage))
2024-11-05 13:35:35 +00:00
->on(Database::EVENT_DOCUMENT_CREATE, 'create-trigger-events', fn ($event, $document) => $eventDatabaseListener(
$project,
2024-11-05 13:35:35 +00:00
$document,
$response,
$queueForEventsClone->from($queueForEvents),
2024-11-05 14:50:32 +00:00
$queueForFunctions->from($queueForEvents),
$queueForWebhooks->from($queueForEvents),
$queueForRealtime->from($queueForEvents)
2024-11-05 13:35:35 +00:00
));
2022-10-17 07:10:18 +00:00
2022-08-09 11:57:33 +00:00
$useCache = $route->getLabel('cache', false);
if ($useCache) {
2025-04-03 02:44:29 +00:00
$route = $utopia->match($request);
$isImageTransformation = $route->getPath() === '/v1/storage/buckets/:bucketId/files/:fileId/preview';
$isDisabled = isset($plan['imageTransformations']) && $plan['imageTransformations'] === -1 && !Auth::isPrivilegedUser(Authorization::getRoles());
$key = $request->cacheIdentifier();
$cacheLog = Authorization::skip(fn () => $dbForProject->getDocument('cache', $key));
2022-08-15 13:55:11 +00:00
$cache = new Cache(
new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())
);
2022-08-09 11:57:33 +00:00
$timestamp = 60 * 60 * 24 * 30;
$data = $cache->load($key, $timestamp);
if (!empty($data) && !$cacheLog->isEmpty()) {
2025-04-11 14:52:19 +00:00
$parts = explode('/', $cacheLog->getAttribute('resourceType', ''));
$type = $parts[0] ?? null;
2025-04-03 02:44:29 +00:00
if ($type === 'bucket' && (!$isImageTransformation || !$isDisabled)) {
$bucketId = $parts[1] ?? null;
$bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));
if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAppUser && !$isPrivilegedUser)) {
throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);
}
$fileSecurity = $bucket->getAttribute('fileSecurity', false);
$validator = new Authorization(Database::PERMISSION_READ);
$valid = $validator->isValid($bucket->getRead());
if (!$fileSecurity && !$valid) {
throw new Exception(Exception::USER_UNAUTHORIZED);
}
$parts = explode('/', $cacheLog->getAttribute('resource'));
$fileId = $parts[1] ?? null;
if ($fileSecurity && !$valid) {
$file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);
} else {
$file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));
}
if ($file->isEmpty()) {
throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);
}
//Do not update transformedAt if it's a console user
if (!Auth::isPrivilegedUser(Authorization::getRoles())) {
$transformedAt = $file->getAttribute('transformedAt', '');
if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_PROJECT_ACCESS)) > $transformedAt) {
$file->setAttribute('transformedAt', DateTime::now());
Authorization::skip(fn () => $dbForProject->updateDocument('bucket_' . $file->getAttribute('bucketInternalId'), $file->getId(), $file));
}
2025-01-28 14:49:55 +00:00
}
}
2022-08-09 13:43:37 +00:00
$response
->addHeader('Cache-Control', sprintf('private, max-age=%d', $timestamp))
2022-08-09 13:43:37 +00:00
->addHeader('X-Appwrite-Cache', 'hit')
2025-04-03 02:44:29 +00:00
->setContentType($cacheLog->getAttribute('mimeType'));
if (!$isImageTransformation || !$isDisabled) {
$response->send($data);
}
2022-08-09 13:43:37 +00:00
} else {
$response
->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
->addHeader('Pragma', 'no-cache')
->addHeader('Expires', '0')
2025-02-12 07:34:38 +00:00
->addHeader('X-Appwrite-Cache', 'miss');
2022-08-09 13:43:37 +00:00
}
}
2022-07-22 06:00:42 +00:00
});
App::init()
->groups(['session'])
->inject('user')
->inject('request')
->action(function (Document $user, Request $request) {
if (\str_contains($request->getURI(), 'oauth2')) {
return;
}
if (!$user->isEmpty()) {
throw new Exception(Exception::USER_SESSION_ALREADY_EXISTS);
}
});
2023-05-23 13:43:03 +00:00
/**
* Limit user session
*
* Delete older sessions if the number of sessions have crossed
* the session limit set for the project
*/
App::shutdown()
->groups(['session'])
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('dbForProject')
->action(function (App $utopia, Request $request, Response $response, Document $project, Database $dbForProject) {
$sessionLimit = $project->getAttribute('auths', [])['maxSessions'] ?? APP_LIMIT_USER_SESSIONS_DEFAULT;
$session = $response->getPayload();
$userId = $session['userId'] ?? '';
if (empty($userId)) {
return;
}
$user = $dbForProject->getDocument('users', $userId);
if ($user->isEmpty()) {
return;
}
$sessions = $user->getAttribute('sessions', []);
$count = \count($sessions);
if ($count <= $sessionLimit) {
return;
}
for ($i = 0; $i < ($count - $sessionLimit); $i++) {
$session = array_shift($sessions);
$dbForProject->deleteDocument('sessions', $session->getId());
}
2023-12-14 13:32:06 +00:00
$dbForProject->purgeCachedDocument('users', $userId);
2023-05-23 13:43:03 +00:00
});
2022-07-22 06:00:42 +00:00
App::shutdown()
2022-08-02 01:10:48 +00:00
->groups(['api'])
2022-07-22 06:00:42 +00:00
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('user')
2022-12-20 16:11:30 +00:00
->inject('queueForEvents')
->inject('queueForAudits')
2025-01-30 04:53:53 +00:00
->inject('queueForStatsUsage')
2022-12-20 16:11:30 +00:00
->inject('queueForDeletes')
->inject('queueForDatabase')
2024-02-20 11:40:55 +00:00
->inject('queueForBuilds')
2024-02-20 12:06:35 +00:00
->inject('queueForMessaging')
2022-11-16 10:33:11 +00:00
->inject('queueForFunctions')
2024-11-04 15:05:54 +00:00
->inject('queueForWebhooks')
->inject('queueForRealtime')
->inject('dbForProject')
2025-02-17 13:02:29 +00:00
->action(function (App $utopia, Request $request, Response $response, Document $project, Document $user, Event $queueForEvents, Audit $queueForAudits, StatsUsage $queueForStatsUsage, Delete $queueForDeletes, EventDatabase $queueForDatabase, Build $queueForBuilds, Messaging $queueForMessaging, Func $queueForFunctions, Event $queueForWebhooks, Realtime $queueForRealtime, Database $dbForProject) use ($parseLabel) {
2022-08-09 11:57:33 +00:00
2022-08-07 15:09:37 +00:00
$responsePayload = $response->getPayload();
2022-07-22 06:00:42 +00:00
2024-11-04 15:20:43 +00:00
if (!empty($queueForEvents->getEvent())) {
if (empty($queueForEvents->getPayload())) {
$queueForEvents->setPayload($responsePayload);
}
$queueForFunctions
->from($queueForEvents)
->trigger();
2021-02-28 18:36:13 +00:00
2024-11-04 15:20:43 +00:00
if ($project->getId() !== 'console') {
$queueForRealtime
->from($queueForEvents)
->trigger();
}
2025-01-04 07:25:20 +00:00
/** Trigger webhooks events only if a project has them enabled
2025-01-04 07:21:50 +00:00
* A future optimisation is to only trigger webhooks if the webhook is "enabled"
* But it might have performance implications on the API due to the number of webhooks etc.
* Some profiling is needed to see if this is a problem.
*/
2025-01-17 11:48:19 +00:00
if (!empty($project->getAttribute('webhooks'))) {
$queueForWebhooks
->from($queueForEvents)
->trigger();
}
2024-11-04 15:20:43 +00:00
}
2024-11-04 15:05:54 +00:00
2023-02-19 11:04:12 +00:00
$route = $utopia->getRoute();
2022-08-14 19:27:43 +00:00
$requestParams = $route->getParamsValues();
2022-08-08 12:19:41 +00:00
2022-08-17 14:29:22 +00:00
/**
* Audit labels
*/
2022-08-16 12:28:30 +00:00
$pattern = $route->getLabel('audits.resource', null);
if (!empty($pattern)) {
$resource = $parseLabel($pattern, $responsePayload, $requestParams, $user);
if (!empty($resource) && $resource !== $pattern) {
2022-12-20 16:11:30 +00:00
$queueForAudits->setResource($resource);
2022-08-07 14:30:47 +00:00
}
2022-08-07 15:49:30 +00:00
}
2022-08-13 08:02:00 +00:00
if (!$user->isEmpty()) {
2025-01-21 06:41:20 +00:00
$userClone = clone $user;
2025-01-14 08:17:01 +00:00
// $user doesn't support `type` and can cause unintended effects.
2025-01-21 06:41:20 +00:00
$userClone->setAttribute('type', Auth::ACTIVITY_TYPE_USER);
$queueForAudits->setUser($userClone);
} elseif ($queueForAudits->getUser() === null || $queueForAudits->getUser()->isEmpty()) {
/**
* User in the request is empty, and no user was set for auditing previously.
* This indicates:
* - No API Key was used.
* - No active session exists.
*
* Therefore, we consider this an anonymous request and create a relevant user.
*/
$user = new Document([
'$id' => '',
'status' => true,
2025-01-14 12:15:49 +00:00
'type' => Auth::ACTIVITY_TYPE_GUEST,
'email' => 'guest.' . $project->getId() . '@service.' . $request->getHostname(),
'password' => '',
2025-01-14 12:15:49 +00:00
'name' => 'Guest',
]);
2023-10-01 17:39:26 +00:00
$queueForAudits->setUser($user);
2021-03-11 16:28:03 +00:00
}
2021-10-07 15:35:17 +00:00
if (!empty($queueForAudits->getResource()) && !$queueForAudits->getUser()->isEmpty()) {
2022-08-16 12:28:30 +00:00
/**
* audits.payload is switched to default true
* in order to auto audit payload for all endpoints
*/
$pattern = $route->getLabel('audits.payload', true);
if (!empty($pattern)) {
2022-12-20 16:11:30 +00:00
$queueForAudits->setPayload($responsePayload);
2022-08-16 12:28:30 +00:00
}
2022-12-20 16:11:30 +00:00
foreach ($queueForEvents->getParams() as $key => $value) {
$queueForAudits->setParam($key, $value);
2021-02-28 18:36:13 +00:00
}
2022-12-20 16:11:30 +00:00
$queueForAudits->trigger();
2022-04-18 16:21:45 +00:00
}
2021-10-07 15:35:17 +00:00
2022-12-20 16:11:30 +00:00
if (!empty($queueForDeletes->getType())) {
$queueForDeletes->trigger();
}
2021-10-07 15:35:17 +00:00
2022-12-20 16:11:30 +00:00
if (!empty($queueForDatabase->getType())) {
$queueForDatabase->trigger();
2022-07-22 06:00:42 +00:00
}
2021-10-07 15:35:17 +00:00
2024-02-20 11:40:55 +00:00
if (!empty($queueForBuilds->getType())) {
$queueForBuilds->trigger();
}
2024-02-20 12:06:35 +00:00
if (!empty($queueForMessaging->getType())) {
2024-02-20 13:20:09 +00:00
$queueForMessaging->trigger();
2024-02-20 12:06:35 +00:00
}
// Cache label
2022-08-16 15:02:17 +00:00
$useCache = $route->getLabel('cache', false);
if ($useCache) {
$resource = $resourceType = null;
2022-08-09 13:43:37 +00:00
$data = $response->getPayload();
2022-08-16 15:02:17 +00:00
if (!empty($data['payload'])) {
$pattern = $route->getLabel('cache.resource', null);
if (!empty($pattern)) {
$resource = $parseLabel($pattern, $responsePayload, $requestParams, $user);
}
2022-08-15 09:05:41 +00:00
$pattern = $route->getLabel('cache.resourceType', null);
if (!empty($pattern)) {
$resourceType = $parseLabel($pattern, $responsePayload, $requestParams, $user);
}
$key = $request->cacheIdentifier();
$signature = md5($data['payload']);
$cacheLog = Authorization::skip(fn () => $dbForProject->getDocument('cache', $key));
2022-08-31 08:52:55 +00:00
$accessedAt = $cacheLog->getAttribute('accessedAt', '');
$now = DateTime::now();
2022-08-16 15:02:17 +00:00
if ($cacheLog->isEmpty()) {
Authorization::skip(fn () => $dbForProject->createDocument('cache', new Document([
2024-03-06 17:34:21 +00:00
'$id' => $key,
'resource' => $resource,
2024-03-07 16:16:39 +00:00
'resourceType' => $resourceType,
'mimeType' => $response->getContentType(),
2024-03-06 17:34:21 +00:00
'accessedAt' => $now,
'signature' => $signature,
2022-08-09 13:43:37 +00:00
])));
2022-08-31 13:11:23 +00:00
} elseif (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_CACHE_UPDATE)) > $accessedAt) {
$cacheLog->setAttribute('accessedAt', $now);
2022-08-09 13:43:37 +00:00
Authorization::skip(fn () => $dbForProject->updateDocument('cache', $cacheLog->getId(), $cacheLog));
2022-08-16 15:02:17 +00:00
}
2022-08-14 15:01:34 +00:00
2022-08-16 15:02:17 +00:00
if ($signature !== $cacheLog->getAttribute('signature')) {
$cache = new Cache(
new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())
);
$cache->save($key, $data['payload']);
2022-08-16 15:02:17 +00:00
}
2022-08-15 12:16:32 +00:00
}
}
2023-10-25 07:39:59 +00:00
if ($project->getId() !== 'console') {
2024-04-25 01:23:01 +00:00
if (!Auth::isPrivilegedUser(Authorization::getRoles())) {
2023-10-25 07:39:59 +00:00
$fileSize = 0;
$file = $request->getFiles('file');
if (!empty($file)) {
$fileSize = (\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size'];
}
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->addMetric(METRIC_NETWORK_REQUESTS, 1)
->addMetric(METRIC_NETWORK_INBOUND, $request->getSize() + $fileSize)
->addMetric(METRIC_NETWORK_OUTBOUND, $response->getSize());
2022-08-17 10:55:01 +00:00
}
2025-01-30 04:53:53 +00:00
$queueForStatsUsage
2023-10-25 07:39:59 +00:00
->setProject($project)
->trigger();
2022-07-22 06:00:42 +00:00
}
});
App::init()
->groups(['usage'])
->action(function () {
2024-04-01 11:02:47 +00:00
if (System::getEnv('_APP_USAGE_STATS', 'enabled') !== 'enabled') {
throw new Exception(Exception::GENERAL_USAGE_DISABLED);
}
});