diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 67affddd20..789fce6d71 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -3932,6 +3932,8 @@ Http::put('/v1/account/recovery') $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); + $sessions = $profile->getAttribute('sessions', []); + $profile = $dbForProject->updateDocument('users', $profile->getId(), new Document( [ 'password' => $newPassword, @@ -3944,6 +3946,14 @@ Http::put('/v1/account/recovery') $user->setAttributes($profile->getArrayCopy()); + $invalidate = $project->getAttribute('auths', default: [])['invalidateSessions'] ?? false; + if ($invalidate) { + foreach ($sessions as $session) { + /** @var Document $session */ + $dbForProject->deleteDocument('sessions', $session->getId()); + } + } + $recoveryDocument = $dbForProject->getDocument('tokens', $verifiedToken->getId()); /** diff --git a/app/controllers/api/users.php b/app/controllers/api/users.php index c8ea66ea51..19cff6aa01 100644 --- a/app/controllers/api/users.php +++ b/app/controllers/api/users.php @@ -591,7 +591,7 @@ Http::post('/v1/users/:userId/targets') ->label('audits.event', 'target.create') ->label('audits.resource', 'target/response.$id') ->label('event', 'users.[userId].targets.[targetId].create') - ->label('scope', 'targets.write') + ->label('scope', 'users.write') ->label('sdk', new Method( namespace: 'users', group: 'targets', @@ -852,7 +852,7 @@ Http::get('/v1/users/:userId/prefs') Http::get('/v1/users/:userId/targets/:targetId') ->desc('Get user target') ->groups(['api', 'users']) - ->label('scope', 'targets.read') + ->label('scope', 'users.read') ->label('sdk', new Method( namespace: 'users', group: 'targets', @@ -1078,7 +1078,7 @@ Http::get('/v1/users/:userId/logs') Http::get('/v1/users/:userId/targets') ->desc('List user targets') ->groups(['api', 'users']) - ->label('scope', 'targets.read') + ->label('scope', 'users.read') ->label('sdk', new Method( namespace: 'users', group: 'targets', @@ -1843,7 +1843,7 @@ Http::patch('/v1/users/:userId/targets/:targetId') ->label('audits.event', 'target.update') ->label('audits.resource', 'target/{response.$id}') ->label('event', 'users.[userId].targets.[targetId].update') - ->label('scope', 'targets.write') + ->label('scope', 'users.write') ->label('sdk', new Method( namespace: 'users', group: 'targets', @@ -2661,7 +2661,7 @@ Http::delete('/v1/users/:userId/targets/:targetId') ->label('audits.event', 'target.delete') ->label('audits.resource', 'target/{request.$targetId}') ->label('event', 'users.[userId].targets.[targetId].delete') - ->label('scope', 'targets.write') + ->label('scope', 'users.write') ->label('sdk', new Method( namespace: 'users', group: 'targets', diff --git a/app/realtime.php b/app/realtime.php index ce2dc41e54..c99e4c0857 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -657,50 +657,58 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $userId = $event['userId']; if ($realtime->hasSubscriber($projectId, 'user:' . $userId)) { - $connection = array_key_first(reset($realtime->subscriptions[$projectId]['user:' . $userId])); - $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); + $connections = []; + foreach ($realtime->subscriptions[$projectId]['user:' . $userId] as $byConnection) { + foreach (\array_keys($byConnection) as $connectionId) { + $connections[$connectionId] = true; + } + } + $consoleDatabase = getConsoleDB(); $project = $consoleDatabase->getAuthorization()->skip(fn () => $consoleDatabase->getDocument('projects', $projectId)); $database = getProjectDB($project); /** @var User $user */ $user = $database->getDocument('users', $userId); - $roles = $user->getRoles($database->getAuthorization()); - $authorization = $realtime->connections[$connection]['authorization'] ?? null; - $previousUserId = $realtime->connections[$connection]['userId'] ?? ''; - $meta = $realtime->getSubscriptionMetadata($connection); + foreach (\array_keys($connections) as $connection) { + $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); + $authorization = $realtime->connections[$connection]['authorization'] ?? null; + $previousUserId = $realtime->connections[$connection]['userId'] ?? ''; - $realtime->unsubscribe($connection); + $meta = $realtime->getSubscriptionMetadata($connection); - foreach ($meta as $subscriptionId => $subscription) { - $queries = Query::parseQueries($subscription['queries'] ?? []); - $channels = Realtime::rebindAccountChannels( - $subscription['channels'] ?? [], - $previousUserId, - $userId - ); - $realtime->subscribe( - $projectId, - $connection, - $subscriptionId, - $roles, - $channels, - $queries, - $userId - ); - } + $realtime->unsubscribe($connection); - // Restore authorization after subscribe - if ($authorization !== null) { - $realtime->connections[$connection]['authorization'] = $authorization; - } + foreach ($meta as $subscriptionId => $subscription) { + $queries = Query::parseQueries($subscription['queries'] ?? []); + $channels = Realtime::rebindAccountChannels( + $subscription['channels'] ?? [], + $previousUserId, + $userId + ); + $realtime->subscribe( + $projectId, + $connection, + $subscriptionId, + $roles, + $channels, + $queries, + $userId + ); + } - $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); - $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; - if ($subscriptionDelta !== 0) { - $register->get('telemetry.workerSubscriptionCounter')->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); + // Restore authorization after subscribe + if ($authorization !== null) { + $realtime->connections[$connection]['authorization'] = $authorization; + } + + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; + if ($subscriptionDelta !== 0) { + $register->get('telemetry.workerSubscriptionCounter')->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); + } } } } diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Image/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Image/Get.php index 77ff9dd8ce..315202d4d5 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Image/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Image/Get.php @@ -3,6 +3,7 @@ namespace Appwrite\Platform\Modules\Avatars\Http\Image; use Appwrite\Extend\Exception; +use Appwrite\Network\Validator\PublicHostname; use Appwrite\Platform\Modules\Avatars\Http\Action; use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; @@ -69,10 +70,19 @@ class Get extends Action throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing'); } - $domain = new Domain(\parse_url($url, PHP_URL_HOST)); + $host = \parse_url($url, PHP_URL_HOST) ?? ''; - if (!$domain->isKnown()) { - throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); + $isIpLiteral = \filter_var(\trim($host, '[]'), FILTER_VALIDATE_IP) !== false; + if (!$isIpLiteral) { + $domain = new Domain($host); + if (!$domain->isKnown()) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); + } + } + + $hostnameValidator = new PublicHostname(); + if (!$hostnameValidator->isValid($host)) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED, $hostnameValidator->getDescription()); } $client = new Client(); diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Screenshots/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Screenshots/Get.php index 9b2e92efe5..51d4df2a49 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Screenshots/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Screenshots/Get.php @@ -3,6 +3,7 @@ namespace Appwrite\Platform\Modules\Avatars\Http\Screenshots; use Appwrite\Extend\Exception; +use Appwrite\Network\Validator\PublicHostname; use Appwrite\Platform\Modules\Avatars\Http\Action; use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; @@ -95,10 +96,19 @@ class Get extends Action throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing'); } - $domain = new Domain(\parse_url($url, PHP_URL_HOST)); + $host = \parse_url($url, PHP_URL_HOST) ?? ''; - if (!$domain->isKnown()) { - throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); + $isIpLiteral = \filter_var(\trim($host, '[]'), FILTER_VALIDATE_IP) !== false; + if (!$isIpLiteral) { + $domain = new Domain($host); + if (!$domain->isKnown()) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); + } + } + + $hostnameValidator = new PublicHostname(); + if (!$hostnameValidator->isValid($host)) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED, $hostnameValidator->getDescription()); } $client = new Client(); diff --git a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php index 1d4a8dd689..f04f7c3807 100644 --- a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php +++ b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php @@ -297,9 +297,10 @@ class Builds extends Action $templateReferenceValue = $template->getAttribute('referenceValue', ''); $templateRootDirectory = $template->getAttribute('rootDirectory', ''); - $templateRootDirectory = \rtrim($templateRootDirectory, '/'); - $templateRootDirectory = \ltrim($templateRootDirectory, '.'); - $templateRootDirectory = \ltrim($templateRootDirectory, '/'); + $templateRootDirectory = \trim($templateRootDirectory, '/'); + if ($templateRootDirectory !== '' && \preg_match('#(^|/)\.\.(/|$)#', $templateRootDirectory)) { + throw new \Exception('Invalid template root directory'); + } if (! empty($templateRepositoryName) && ! empty($templateOwnerName) && ! empty($templateReferenceType) && ! empty($templateReferenceValue)) { $stdout = ''; @@ -362,9 +363,10 @@ class Builds extends Action // VCS and VCS+Temaplte $tmpDirectory = '/tmp/builds/' . $deploymentId . '/code'; $rootDirectory = $resource->getAttribute('providerRootDirectory', ''); - $rootDirectory = \rtrim($rootDirectory, '/'); - $rootDirectory = \ltrim($rootDirectory, '.'); - $rootDirectory = \ltrim($rootDirectory, '/'); + $rootDirectory = \trim($rootDirectory, '/'); + if ($rootDirectory !== '' && \preg_match('#(^|/)\.\.(/|$)#', $rootDirectory)) { + throw new \Exception('Invalid root directory'); + } $owner = $github->getOwnerName($providerInstallationId); $repositoryName = $github->getRepositoryName($providerRepositoryId); @@ -420,9 +422,10 @@ class Builds extends Action $templateReferenceValue = $template->getAttribute('referenceValue', ''); $templateRootDirectory = $template->getAttribute('rootDirectory', ''); - $templateRootDirectory = \rtrim($templateRootDirectory, '/'); - $templateRootDirectory = \ltrim($templateRootDirectory, '.'); - $templateRootDirectory = \ltrim($templateRootDirectory, '/'); + $templateRootDirectory = \trim($templateRootDirectory, '/'); + if ($templateRootDirectory !== '' && \preg_match('#(^|/)\.\.(/|$)#', $templateRootDirectory)) { + throw new \Exception('Invalid template root directory'); + } if (! empty($templateRepositoryName) && ! empty($templateOwnerName) && ! empty($templateReferenceType) && ! empty($templateReferenceValue)) { // Clone template repo @@ -443,7 +446,8 @@ class Builds extends Action Console::execute('rsync -av --exclude \'.git\' ' . \escapeshellarg($tmpTemplateDirectory . '/' . $templateRootDirectory . '/') . ' ' . \escapeshellarg($tmpDirectory . '/' . $rootDirectory), '', $stdout, $stderr); // Commit and push - $exit = Console::execute('git config --global user.email ' . \escapeshellarg(APP_VCS_GITHUB_EMAIL) . ' && git config --global user.name ' . \escapeshellarg(APP_VCS_GITHUB_USERNAME) . ' && cd ' . \escapeshellarg($tmpDirectory) . ' && git checkout -b ' . \escapeshellarg($branchName) . ' && git add . && git commit -m "Create ' . \escapeshellarg($resource->getAttribute('name', '')) . ' function" && git push origin ' . \escapeshellarg($branchName), '', $stdout, $stderr); + $commitMessage = \escapeshellarg('Create ' . $resource->getAttribute('name', '') . ' function'); + $exit = Console::execute('git config --global user.email ' . \escapeshellarg(APP_VCS_GITHUB_EMAIL) . ' && git config --global user.name ' . \escapeshellarg(APP_VCS_GITHUB_USERNAME) . ' && cd ' . \escapeshellarg($tmpDirectory) . ' && git checkout -b ' . \escapeshellarg($branchName) . ' && git add . && git commit -m ' . $commitMessage . ' && git push origin ' . \escapeshellarg($branchName), '', $stdout, $stderr); if ($exit !== 0) { throw new \Exception('Unable to push code repository: ' . $stderr); diff --git a/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Get.php b/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Get.php index 556f6de52c..0a856bb5a8 100644 --- a/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Get.php +++ b/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Get.php @@ -70,6 +70,10 @@ class Get extends Action throw new Exception(Exception::MEMBERSHIP_NOT_FOUND); } + if ($membership->getAttribute('teamInternalId') !== $team->getSequence()) { + throw new Exception(Exception::TEAM_MEMBERSHIP_MISMATCH); + } + // Default should be "false", but existing projects already rely on this being "true" $membershipsPrivacy = [ 'userName' => $project->getAttribute('auths', [])['membershipsUserName'] ?? true, diff --git a/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Update.php b/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Update.php index 2198531e64..0d2f1e40b4 100644 --- a/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Update.php +++ b/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Update.php @@ -78,6 +78,10 @@ class Update extends Action throw new Exception(Exception::MEMBERSHIP_NOT_FOUND); } + if ($membership->getAttribute('teamInternalId') !== $team->getSequence()) { + throw new Exception(Exception::TEAM_MEMBERSHIP_MISMATCH); + } + $profile = $dbForProject->getDocument('users', $membership->getAttribute('userId')); if ($profile->isEmpty()) { throw new Exception(Exception::USER_NOT_FOUND); diff --git a/src/Appwrite/Platform/Workers/Webhooks.php b/src/Appwrite/Platform/Workers/Webhooks.php index 973e487de5..48f12d3ee9 100644 --- a/src/Appwrite/Platform/Workers/Webhooks.php +++ b/src/Appwrite/Platform/Workers/Webhooks.php @@ -6,6 +6,7 @@ use Appwrite\Event\Message\Mail as MailMessage; use Appwrite\Event\Message\Usage as UsageMessage; use Appwrite\Event\Publisher\Mail as MailPublisher; use Appwrite\Event\Publisher\Usage as UsagePublisher; +use Appwrite\Network\Validator\PublicHostname; use Appwrite\Template\Template; use Appwrite\Usage\Context as UsageContext; use Exception; @@ -101,6 +102,16 @@ class Webhooks extends Action } $url = \rawurldecode($webhook->getAttribute('url')); + + if (System::getEnv('_APP_ENV', 'development') === 'production') { + $host = \parse_url($url, PHP_URL_HOST) ?? ''; + $hostnameValidator = new PublicHostname(); + if (!$hostnameValidator->isValid($host)) { + $this->errors[] = 'Webhook target ' . $host . ' rejected: ' . $hostnameValidator->getDescription(); + return; + } + } + $signatureKey = $webhook->getAttribute('signatureKey'); $signature = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); $httpUser = $webhook->getAttribute('httpUser');