chore: remove dev keys

Remove the dev key routes, model, query validator, scopes, CORS header,
spec security scheme, and the request/realtime handling that let a dev
key bypass abuse limits, CSRF, and origin/redirect validation.

Drop the devKeys collection and project attribute from the platform
schema; V25 deletes both from existing installs.
This commit is contained in:
harsh mahajan committed 2026-09-15 13:59:46 +05:30
1 parent 49f852e8ec
commit 4ad7a8d23b
30 files changed
+33 -841

No files matched your search

-112
View File
@@ -287,17 +287,6 @@ $platformCollections = [
'array' => false,
'filters' => ['subQueryKeys'],
],
[
'$id' => ID::custom('devKeys'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 16384,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => ['subQueryDevKeys'],
],
[
'$id' => ID::custom('search'),
'type' => Database::VAR_STRING,
@@ -818,107 +807,6 @@ $platformCollections = [
],
],
'devKeys' => [
'$collection' => ID::custom(Database::METADATA),
'$id' => ID::custom('devKeys'),
'name' => 'Dev keys',
'attributes' => [
[
'$id' => ID::custom('projectInternalId'),
'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' => 0,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('name'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => true,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('secret'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => 512, // var_dump of \bin2hex(\random_bytes(128)) => string(256) doubling for encryption
'signed' => true,
'required' => true,
'default' => null,
'array' => false,
'filters' => ['encrypt'],
],
[
'$id' => ID::custom('expire'),
'type' => Database::VAR_DATETIME,
'format' => '',
'size' => 0,
'signed' => false,
'required' => false,
'default' => null,
'array' => false,
'filters' => ['datetime'],
],
[
'$id' => ID::custom('accessedAt'),
'type' => Database::VAR_DATETIME,
'format' => '',
'size' => 0,
'signed' => false,
'required' => false,
'default' => null,
'array' => false,
'filters' => ['datetime'],
],
[
'$id' => ID::custom('sdks'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => true,
'default' => null,
'array' => true,
'filters' => [],
],
],
'indexes' => [
[
'$id' => ID::custom('_key_project'),
'type' => Database::INDEX_KEY,
'attributes' => ['projectInternalId'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => '_key_accessedAt',
'type' => Database::INDEX_KEY,
'attributes' => ['accessedAt'],
'lengths' => [],
'orders' => [],
],
],
],
'webhooks' => [
'$collection' => ID::custom(Database::METADATA),
'$id' => ID::custom('webhooks'),
-1
View File
@@ -18,7 +18,6 @@ return [
// Appwrite
'X-Appwrite-Project',
'X-Appwrite-Key',
'X-Appwrite-Dev-Key',
'X-Appwrite-Locale',
'X-Appwrite-Mode',
'X-Appwrite-JWT',
-5
View File
@@ -1251,11 +1251,6 @@ return [
'description' => 'An API key cannot be created from a request authorized with an API key. Authenticate with a session instead. To create a short-lived key from a server, use the ephemeral key endpoint.',
'code' => 403,
],
Exception::DEV_KEY_GONE => [
'name' => Exception::DEV_KEY_GONE,
'description' => 'Dev key creation is no longer available.',
'code' => 410,
],
Exception::PLATFORM_NOT_FOUND => [
'name' => Exception::PLATFORM_NOT_FOUND,
'description' => 'Platform with the requested ID could not be found.',
-2
View File
@@ -94,8 +94,6 @@ $admins = [
'keys.write',
'organization.projects.keys.read',
'organization.projects.keys.write',
'devKeys.read',
'devKeys.write',
'webhooks.read',
'webhooks.write',
'project.read',
-11
View File
@@ -21,15 +21,4 @@ return [
"Access to create, update, and delete organization projects' API keys",
"category" => "Projects",
],
"devKeys.read" => [
"description" => 'Access to read project\'s development keys',
"category" => "Other",
"deprecated" => true,
],
"devKeys.write" => [
"description" =>
"Access to create, update, and delete project\'s development keys",
"category" => "Other",
"deprecated" => true,
],
];
+3 -4
View File
@@ -1499,7 +1499,6 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
->inject('response')
->inject('project')
->inject('redirectValidator')
->inject('devKey')
->inject('user')
->inject('dbForProject')
->inject('geo')
@@ -1512,7 +1511,7 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
->inject('domainVerification')
->inject('cookieDomain')
->inject('authorization')
->action(function (string $provider, string $code, string $state, string $error, string $error_description, Request $request, Response $response, Document $project, Validator $redirectValidator, Document $devKey, User $user, Database $dbForProject, Geo $geo, Database $dbForPlatform, Event $queueForEvents, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, array $plan, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) use ($oauthDefaultSuccess, $oauthDefaultFailure) {
->action(function (string $provider, string $code, string $state, string $error, string $error_description, Request $request, Response $response, Document $project, Validator $redirectValidator, User $user, Database $dbForProject, Geo $geo, Database $dbForPlatform, Event $queueForEvents, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, array $plan, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) use ($oauthDefaultSuccess, $oauthDefaultFailure) {
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https';
$port = $request->getPort();
$callbackBase = $protocol . '://' . $request->getHostname();
@@ -1573,11 +1572,11 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
}
}
if ($devKey->isEmpty() && !$redirectValidator->isValid($state['success'])) {
if (!$redirectValidator->isValid($state['success'])) {
throw new Exception(Exception::PROJECT_INVALID_SUCCESS_URL);
}
if ($devKey->isEmpty() && !empty($state['failure']) && !$redirectValidator->isValid($state['failure'])) {
if (!empty($state['failure']) && !$redirectValidator->isValid($state['failure'])) {
throw new Exception(Exception::PROJECT_INVALID_FAILURE_URL);
}
$failure = [];
+5 -9
View File
@@ -897,7 +897,6 @@ Http::init()
->inject('platform')
->inject('getIsResourceBlocked')
->inject('previewHostname')
->inject('devKey')
->inject('apiKey')
->inject('cors')
->inject('authorization')
@@ -905,7 +904,7 @@ Http::init()
->inject('executionsRetentionCount')
->inject('lock')
->inject('params')
->action(function (Http $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Document $project, Database $dbForPlatform, callable $getProjectDB, Locale $locale, array $localeCodes, Geo $geo, Event $queueForEvents, Bus $bus, Executor $executor, array $platform, callable $getIsResourceBlocked, string $previewHostname, Document $devKey, ?Key $apiKey, Cors $cors, Authorization $authorization, DeletePublisher $publisherForDeletes, int $executionsRetentionCount, Lock $lock, array $params) {
->action(function (Http $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Document $project, Database $dbForPlatform, callable $getProjectDB, Locale $locale, array $localeCodes, Geo $geo, Event $queueForEvents, Bus $bus, Executor $executor, array $platform, callable $getIsResourceBlocked, string $previewHostname, ?Key $apiKey, Cors $cors, Authorization $authorization, DeletePublisher $publisherForDeletes, int $executionsRetentionCount, Lock $lock, array $params) {
/*
* Appwrite Router
*/
@@ -1061,9 +1060,8 @@ Http::init()
->inject('request')
->inject('response')
->inject('cors')
->inject('devKey')
->inject('originValidator')
->action(function (Request $request, Response $response, Cors $cors, Document $devKey, Validator $originValidator) {
->action(function (Request $request, Response $response, Cors $cors, Validator $originValidator) {
// CORS headers
foreach ($cors->headers($request->getOrigin()) as $name => $value) {
$response->addHeader($name, $value);
@@ -1081,7 +1079,7 @@ Http::init()
// Application level CSRF protection
$origin = $request->getOrigin();
if (empty($origin) || !$devKey->isEmpty() || !empty($request->getHeaderLine('x-appwrite-key'))) {
if (empty($origin) || !empty($request->getHeaderLine('x-appwrite-key'))) {
return;
}
$route = $request->getRoute();
@@ -1217,14 +1215,13 @@ Http::options()
->inject('platform')
->inject('previewHostname')
->inject('project')
->inject('devKey')
->inject('apiKey')
->inject('cors')
->inject('authorization')
->inject('publisherForDeletes')
->inject('executionsRetentionCount')
->inject('lock')
->action(function (Http $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Database $dbForPlatform, callable $getProjectDB, Event $queueForEvents, Bus $bus, Executor $executor, Geo $geo, callable $getIsResourceBlocked, array $platform, string $previewHostname, Document $project, Document $devKey, ?Key $apiKey, Cors $cors, Authorization $authorization, DeletePublisher $publisherForDeletes, int $executionsRetentionCount, Lock $lock) {
->action(function (Http $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Database $dbForPlatform, callable $getProjectDB, Event $queueForEvents, Bus $bus, Executor $executor, Geo $geo, callable $getIsResourceBlocked, array $platform, string $previewHostname, Document $project, ?Key $apiKey, Cors $cors, Authorization $authorization, DeletePublisher $publisherForDeletes, int $executionsRetentionCount, Lock $lock) {
/*
* Appwrite Router
*/
@@ -1261,9 +1258,8 @@ Http::error()
->inject('response')
->inject('project')
->inject('bus')
->inject('devKey')
->inject('authorization')
->action(function (Throwable $error, Http $utopia, Request $request, Response $response, Document $project, Bus $bus, Document $devKey, Authorization $authorization) {
->action(function (Throwable $error, Http $utopia, Request $request, Response $response, Document $project, Bus $bus, Authorization $authorization) {
$version = System::getEnv('_APP_VERSION', 'UNKNOWN');
$route = $utopia->match($request)?->route;
$class = \get_class($error);
+2 -4
View File
@@ -540,17 +540,15 @@ Http::init()
->inject('project')
->inject('user')
->inject('timelimit')
->inject('devKey')
->inject('authorization')
->action(function (Route $route, Request $request, Response $response, Document $project, User $user, callable $timelimit, Document $devKey, Authorization $authorization) {
->action(function (Route $route, Request $request, Response $response, Document $project, User $user, callable $timelimit, Authorization $authorization) {
$response->setUser($user);
$request->setUser($user);
$roles = $authorization->getRoles();
$shouldCheckAbuse = System::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled'
&& ! $user->isKey($roles)
&& ! $user->isPrivileged($roles)
&& $devKey->isEmpty();
&& ! $user->isPrivileged($roles);
$abuseLimit = $route->getLabel('abuse-limit', 0);
$increasedLimitProjects = \array_filter(\array_map('trim', \explode(',', System::getEnv('_APP_OPTIONS_ABUSE_INCREASED_LIMIT_PROJECTS', ''))));
-1
View File
@@ -49,7 +49,6 @@ const APP_PROJECTS_SUBQUERIES = [
'subQueryWebhooks',
'subQueryPlatforms',
'subQueryBlocks',
'subQueryDevKeys',
];
const APP_USERS_SUBQUERIES = [
-14
View File
@@ -153,20 +153,6 @@ Database::addFilter(
}
);
Database::addFilter(
'subQueryDevKeys',
function (mixed $value) {
return;
},
function (mixed $value, Document $document, Database $database) {
return $database->getAuthorization()->skip(fn () => $database
->find('devKeys', [
Query::equal('projectInternalId', [$document->getSequence()]),
Query::limit(APP_LIMIT_SUBQUERY),
]));
}
);
Database::addFilter(
'subQueryWebhooks',
function (mixed $value) {
-3
View File
@@ -72,7 +72,6 @@ use Appwrite\Utopia\Response\Model\Deployment;
use Appwrite\Utopia\Response\Model\DetectionFramework;
use Appwrite\Utopia\Response\Model\DetectionRuntime;
use Appwrite\Utopia\Response\Model\DetectionVariable;
use Appwrite\Utopia\Response\Model\DevKey;
use Appwrite\Utopia\Response\Model\Document as ModelDocument;
use Appwrite\Utopia\Response\Model\Embedding;
use Appwrite\Utopia\Response\Model\EphemeralKey;
@@ -278,7 +277,6 @@ Response::setModel(new BaseList('Executions List', Response::MODEL_EXECUTION_LIS
Response::setModel(new BaseList('Projects List', Response::MODEL_PROJECT_LIST, 'projects', Response::MODEL_PROJECT, true, true));
Response::setModel(new BaseList('Webhooks List', Response::MODEL_WEBHOOK_LIST, 'webhooks', Response::MODEL_WEBHOOK, true, true));
Response::setModel(new BaseList('API Keys List', Response::MODEL_KEY_LIST, 'keys', Response::MODEL_KEY, true, true));
Response::setModel(new BaseList('Dev Keys List', Response::MODEL_DEV_KEY_LIST, 'devKeys', Response::MODEL_DEV_KEY, true, false));
Response::setModel(new BaseList('Auth Providers List', Response::MODEL_AUTH_PROVIDER_LIST, 'platforms', Response::MODEL_AUTH_PROVIDER, true, false));
Response::setModel(new BaseList('Countries List', Response::MODEL_COUNTRY_LIST, 'countries', Response::MODEL_COUNTRY));
Response::setModel(new BaseList('Continents List', Response::MODEL_CONTINENT_LIST, 'continents', Response::MODEL_CONTINENT));
@@ -420,7 +418,6 @@ Response::setModel(new ProjectProtocol());
Response::setModel(new Webhook());
Response::setModel(new Key());
Response::setModel(new EphemeralKey());
Response::setModel(new DevKey());
Response::setModel(new MockNumber());
Response::setModel(new OAuth2GitHub());
Response::setModel(new OAuth2Discord());
+3 -57
View File
@@ -16,8 +16,6 @@ use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\DI\Container;
use Utopia\System\System;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
/**
* Register the minimal per-connection resources required by realtime.
@@ -112,52 +110,6 @@ return function (Container $container): void {
return $rule;
};
$findDevKey = static function (Request $request, Document $project, array $servers, Authorization $authorization) use ($getDbForPlatform): Document {
$devKey = $request->getHeaderLine('x-appwrite-dev-key', $request->getParam('devKey', ''));
$key = $project->find('secret', $devKey, 'devKeys');
if (!$key) {
return new Document([]);
}
$expire = $key->getAttribute('expire');
if (!empty($expire) && $expire < DatabaseDateTime::formatTz(DatabaseDateTime::now())) {
return new Document([]);
}
$dbForPlatform = $getDbForPlatform($authorization);
$accessedAt = $key->getAttribute('accessedAt', 0);
if (empty($accessedAt) || DatabaseDateTime::formatTz(DatabaseDateTime::addSeconds(new \DateTime(), -APP_KEY_ACCESS)) > $accessedAt) {
$key->setAttribute('accessedAt', DatabaseDateTime::now());
$authorization->skip(fn () => $dbForPlatform->updateDocument('devKeys', $key->getId(), new Document([
'accessedAt' => $key->getAttribute('accessedAt'),
])));
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
}
$sdkValidator = new WhiteList($servers, true);
$sdk = \strtolower($request->getHeaderLine('x-sdk-name', 'UNKNOWN'));
if ($sdk !== 'unknown' && $sdkValidator->isValid($sdk)) {
$sdks = $key->getAttribute('sdks', []);
if (!\in_array($sdk, $sdks, true)) {
$sdks[] = $sdk;
$key->setAttribute('sdks', $sdks);
$key->setAttribute('accessedAt', DatabaseDateTime::now());
$key = $authorization->skip(fn () => $dbForPlatform->updateDocument('devKeys', $key->getId(), new Document([
'sdks' => $key->getAttribute('sdks'),
'accessedAt' => $key->getAttribute('accessedAt'),
])));
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
}
}
return $key;
};
$container->set('authorization', function () {
return new Authorization();
}, []);
@@ -174,13 +126,7 @@ return function (Container $container): void {
return $authorization->skip(fn () => $dbForPlatform->getDocument('projects', $projectId));
}, ['request', 'console', 'authorization']);
$container->set('originValidator', function (array $platform, Request $request, Document $project, array $servers, Authorization $authorization) use ($findDevKey, $findRule) {
$devKey = $findDevKey($request, $project, $servers, $authorization);
if (!$devKey->isEmpty()) {
return new URL();
}
$container->set('originValidator', function (array $platform, Request $request, Document $project, Authorization $authorization) use ($findRule) {
$allowedHostnames = [...($platform['hostnames'] ?? [])];
$consoleHostnames = \array_filter(\array_map('trim', \explode(',', System::getEnv('_APP_CONSOLE_HOSTNAMES', ''))));
@@ -211,7 +157,7 @@ return function (Container $container): void {
}
return new Origin(\array_unique($allowedHostnames), \array_unique($allowedSchemes));
}, ['platform', 'request', 'project', 'servers', 'authorization']);
}, ['platform', 'request', 'project', 'authorization']);
$container->set('user', function (Request $request, Document $project, Document $console, Authorization $authorization) use ($getMode, $getDbForPlatform, $getDbForProject) {
$mode = $getMode($request, $project);
@@ -344,7 +290,7 @@ return function (Container $container): void {
return new Document();
}
// Query params mirror the header fallback pattern used by ?project= and ?devKey=,
// Query params mirror the header fallback pattern used by ?project=,
// allowing Console to embed impersonation in direct file/image URLs where headers cannot be set.
$impersonateUserId = $request->getHeaderLine('x-appwrite-impersonate-user-id', (string)($request->getParam('impersonateuserid', '') ?: $request->getParam('impersonateUserId', '')));
$impersonateEmail = $request->getHeaderLine('x-appwrite-impersonate-user-email', (string)($request->getParam('impersonateemail', '') ?: $request->getParam('impersonateEmail', '')));
+7 -72
View File
@@ -59,8 +59,6 @@ use Utopia\Storage\Device;
use Utopia\System\System;
use Utopia\Telemetry\Adapter as Telemetry;
use Utopia\Usage\Tenant as UsageTenant;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
/**
* Register per-request resources on the given container.
@@ -146,7 +144,7 @@ return function (Container $context): void {
return new Document();
}
// Query params mirror the header fallback pattern used by ?project= and ?devKey=,
// Query params mirror the header fallback pattern used by ?project=,
// allowing Console to embed impersonation in direct file/image URLs where headers cannot be set.
$impersonateUserId = $request->getHeaderLine('x-appwrite-impersonate-user-id', (string)($request->getParam('impersonateuserid', '') ?: $request->getParam('impersonateUserId', '')));
$impersonateEmail = $request->getHeaderLine('x-appwrite-impersonate-user-email', (string)($request->getParam('impersonateemail', '') ?: $request->getParam('impersonateEmail', '')));
@@ -248,7 +246,7 @@ return function (Container $context): void {
/**
* List of allowed request hostnames for the request.
*/
$context->set('allowedHostnames', function (array $platform, Document $project, Document $rule, Document $devKey, Request $request) {
$context->set('allowedHostnames', function (array $platform, Document $project, Document $rule, Request $request) {
$allowed = [...($platform['hostnames'] ?? [])];
/* Add platform configured hostnames */
@@ -258,11 +256,6 @@ return function (Container $context): void {
$allowed = [...$allowed, ...$hostnames];
}
/* Add the request hostname if a dev key is found */
if (! $devKey->isEmpty()) {
$allowed[] = $request->getHostname();
}
$originHostname = parse_url($request->getOrigin(), PHP_URL_HOST);
$refererHostname = parse_url($request->getReferer(), PHP_URL_HOST);
@@ -281,13 +274,8 @@ return function (Container $context): void {
$allowed[] = $rule->getAttribute('domain', '');
}
/* Allow the request origin if a dev key is found */
if (! $devKey->isEmpty() && ! empty($hostname)) {
$allowed[] = $hostname;
}
return array_unique($allowed);
}, ['platform', 'project', 'rule', 'devKey', 'request']);
}, ['platform', 'project', 'rule', 'request']);
/**
* List of allowed request schemes for the request.
@@ -422,18 +410,14 @@ return function (Container $context): void {
$context->set(
'originValidator',
fn (Document $devKey, array $allowedHostnames, array $allowedSchemes) => $devKey->isEmpty()
? new Origin($allowedHostnames, $allowedSchemes)
: new URL(),
['devKey', 'allowedHostnames', 'allowedSchemes']
fn (array $allowedHostnames, array $allowedSchemes) => new Origin($allowedHostnames, $allowedSchemes),
['allowedHostnames', 'allowedSchemes']
);
$context->set(
'redirectValidator',
fn (Document $devKey, array $allowedHostnames, array $allowedSchemes) => $devKey->isEmpty()
? new Redirect($allowedHostnames, $allowedSchemes)
: new URL(),
['devKey', 'allowedHostnames', 'allowedSchemes']
fn (array $allowedHostnames, array $allowedSchemes) => new Redirect($allowedHostnames, $allowedSchemes),
['allowedHostnames', 'allowedSchemes']
);
$context->set('user', function (string $mode, Document $project, Document $console, Request $request, Response $response, Database $dbForProject, Database $dbForPlatform, Store $store, Token $proofForToken, $authorization) {
@@ -944,55 +928,6 @@ return function (Container $context): void {
return $requestTimestamp;
}, ['request']);
$context->set('devKey', function (Request $request, Document $project, array $servers, Database $dbForPlatform, Authorization $authorization) {
$devKey = $request->getHeaderLine('x-appwrite-dev-key', $request->getParam('devKey', ''));
// Check if given key match project's development keys
$key = $project->find('secret', $devKey, 'devKeys');
if (! $key) {
return new Document([]);
}
// check expiration
$expire = $key->getAttribute('expire');
if (! empty($expire) && $expire < DatabaseDateTime::formatTz(DatabaseDateTime::now())) {
return new Document([]);
}
// update access time
$accessedAt = $key->getAttribute('accessedAt', 0);
if (empty($accessedAt) || DatabaseDateTime::formatTz(DatabaseDateTime::addSeconds(new \DateTime(), -APP_KEY_ACCESS)) > $accessedAt) {
$key->setAttribute('accessedAt', DatabaseDateTime::now());
$authorization->skip(fn () => $dbForPlatform->updateDocument('devKeys', $key->getId(), new Document([
'accessedAt' => $key->getAttribute('accessedAt')
])));
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
}
// add sdk to key
$sdkValidator = new WhiteList($servers, true);
$sdk = \strtolower($request->getHeaderLine('x-sdk-name', 'UNKNOWN'));
if ($sdk !== 'unknown' && $sdkValidator->isValid($sdk)) {
$sdks = $key->getAttribute('sdks', []);
if (! in_array($sdk, $sdks)) {
$sdks[] = $sdk;
$key->setAttribute('sdks', $sdks);
/** Update access time as well */
$key->setAttribute('accessedAt', DatabaseDateTime::now());
$key = $authorization->skip(fn () => $dbForPlatform->updateDocument('devKeys', $key->getId(), new Document([
'sdks' => $key->getAttribute('sdks'),
'accessedAt' => $key->getAttribute('accessedAt')
])));
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
}
}
return $key;
}, ['request', 'project', 'servers', 'dbForPlatform', 'authorization']);
$context->set('team', function (Document $project, Database $dbForPlatform, Http $utopia, Request $request, Authorization $authorization, string $projectIdFromPath) {
$teamInternalId = '';
if ($project->getId() !== 'console') {
-3
View File
@@ -343,9 +343,6 @@ class Exception extends \Exception
public const string KEY_ALREADY_EXISTS = 'key_already_exists';
public const string KEY_CREATION_DENIED = 'key_creation_denied';
/** Dev Keys */
public const string DEV_KEY_GONE = 'dev_key_gone';
/** Variables */
public const string VARIABLE_NOT_FOUND = 'variable_not_found';
public const string VARIABLE_ALREADY_EXISTS = 'variable_already_exists';
-14
View File
@@ -76,9 +76,6 @@ class V22 extends Migration
case '_metadata':
$this->createCollection('sites');
$this->createCollection('resourceTokens');
if ($projectInternalId === 'console') {
$this->createCollection('devKeys');
}
break;
case 'identities':
$attributes = [
@@ -92,17 +89,6 @@ class V22 extends Migration
}
$this->dbForProject->purgeCachedCollection($id);
break;
case 'projects':
try {
$attributes = [
'devKeys',
];
$this->createAttributesFromCollection($this->dbForProject, $id, $attributes);
} catch (\Throwable $th) {
Console::warning('Failed to create attributes "' . \implode(', ', $attributes) . "\" in collection {$id}: {$th->getMessage()}");
}
$this->dbForProject->purgeCachedCollection($id);
break;
case 'rules':
$attributes = [
'type',
+12
View File
@@ -72,6 +72,18 @@ class V25 extends Migration
} catch (Throwable $th) {
Console::warning("Failed to create index \"_key_accessedAt\" from {$id}: {$th->getMessage()}");
}
try {
$this->dbForProject->deleteAttribute($id, 'devKeys');
} catch (Throwable $th) {
Console::warning("Failed to delete attribute \"devKeys\" from {$id}: {$th->getMessage()}");
}
try {
$this->dbForProject->deleteCollection('devKeys');
} catch (Throwable $th) {
Console::warning("Failed to delete collection \"devKeys\": {$th->getMessage()}");
}
}
$this->dbForProject->purgeCachedCollection($id);
break;
@@ -1,44 +0,0 @@
<?php
namespace Appwrite\Platform\Modules\Projects\Http\DevKeys;
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Datetime as DatetimeValidator;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Create extends Action
{
use HTTP;
public static function getName()
{
return 'createDevKey';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/projects/:projectId/dev-keys')
->desc('Create dev key')
->groups(['api', 'projects'])
->label('scope', 'devKeys.write')
->param('projectId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForProject'])
->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('expire', null, new DatetimeValidator(), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format.', false)
->inject('user')
->inject('response')
->inject('dbForPlatform')
->callback($this->action(...));
}
public function action(string $projectId, string $name, ?string $expire, Document $user, Response $response, Database $dbForPlatform)
{
throw new Exception(Exception::DEV_KEY_GONE);
}
}
@@ -1,76 +0,0 @@
<?php
namespace Appwrite\Platform\Modules\Projects\Http\DevKeys;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Delete extends Action
{
use HTTP;
public static function getName()
{
return 'deleteDevKey';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_DELETE)
->setHttpPath('/v1/projects/:projectId/dev-keys/:keyId')
->desc('Delete dev key')
->groups(['api', 'projects'])
->label('scope', 'devKeys.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'devKeys',
name: 'deleteDevKey',
description: <<<EOT
Delete a project\'s dev key by its unique ID. Once deleted, the key will no longer allow bypassing of rate limits and better logging of errors.
EOT,
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_NOCONTENT,
model: Response::MODEL_NONE
)
],
contentType: ContentType::NONE
))
->param('projectId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForProject'])
->param('keyId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForPlatform')
->callback($this->action(...));
}
public function action(string $projectId, string $keyId, Response $response, Database $dbForPlatform)
{
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$key = $dbForPlatform->getDocument('devKeys', $keyId);
if ($key->isEmpty() || $key->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$dbForPlatform->deleteDocument('devKeys', $key->getId());
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response->noContent();
}
}
@@ -1,72 +0,0 @@
<?php
namespace Appwrite\Platform\Modules\Projects\Http\DevKeys;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Get extends Action
{
use HTTP;
public static function getName()
{
return 'getDevKey';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/projects/:projectId/dev-keys/:keyId')
->desc('Get dev key')
->groups(['api', 'projects'])
->label('scope', 'devKeys.read')
->label('sdk', new Method(
namespace: 'projects',
group: 'devKeys',
name: 'getDevKey',
description: <<<EOT
Get a project\'s dev key by its unique ID. Dev keys are project specific and allow you to bypass rate limits and get better error logging during development.
EOT,
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_DEV_KEY
)
],
contentType: ContentType::JSON
))
->param('projectId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForProject'])
->param('keyId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForPlatform')
->callback($this->action(...));
}
public function action(string $projectId, string $keyId, Response $response, Database $dbForPlatform)
{
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$key = $dbForPlatform->getDocument('devKeys', $keyId);
if ($key->isEmpty() || $key->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$response->dynamic($key, Response::MODEL_DEV_KEY);
}
}
@@ -1,83 +0,0 @@
<?php
namespace Appwrite\Platform\Modules\Projects\Http\DevKeys;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Datetime as DatetimeValidator;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateDevKey';
}
public function __construct()
{
$this->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/projects/:projectId/dev-keys/:keyId')
->desc('Update dev key')
->groups(['api', 'projects'])
->label('scope', 'devKeys.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'devKeys',
name: 'updateDevKey',
description: <<<EOT
Update a project\'s dev key by its unique ID. Use this endpoint to update a project\'s dev key name or expiration time.'
EOT,
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_DEV_KEY
)
],
contentType: ContentType::JSON
))
->param('projectId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForProject'])
->param('keyId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForProject'])
->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('expire', null, new DatetimeValidator(), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format.')
->inject('response')
->inject('dbForPlatform')
->callback($this->action(...));
}
public function action(string $projectId, string $keyId, string $name, ?string $expire, Response $response, Database $dbForPlatform)
{
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$key = $dbForPlatform->getDocument('devKeys', $keyId);
if ($key->isEmpty() || $key->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$key
->setAttribute('name', $name)
->setAttribute('expire', $expire);
$dbForPlatform->updateDocument('devKeys', $key->getId(), new Document(['name' => $name, 'expire' => $expire]));
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response->dynamic($key, Response::MODEL_DEV_KEY);
}
}
@@ -1,83 +0,0 @@
<?php
namespace Appwrite\Platform\Modules\Projects\Http\DevKeys;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\Queries\DevKeys;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Query as QueryException;
use Utopia\Database\Query;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class XList extends Action
{
use HTTP;
public static function getName()
{
return 'listDevKeys';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/projects/:projectId/dev-keys')
->desc('List dev keys')
->groups(['api', 'projects'])
->label('scope', 'devKeys.read')
->label('sdk', new Method(
namespace: 'projects',
group: 'devKeys',
name: 'listDevKeys',
description: <<<EOT
List all the project\'s dev keys. Dev keys are project specific and allow you to bypass rate limits and get better error logging during development.'
EOT,
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_DEV_KEY_LIST
)
],
contentType: ContentType::JSON
))
->param('projectId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForProject'])
->param('queries', [], new DevKeys(), '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(', ', DevKeys::ALLOWED_ATTRIBUTES), true)
->inject('response')
->inject('dbForPlatform')
->callback($this->action(...));
}
public function action(string $projectId, ?array $queries, Response $response, Database $dbForPlatform)
{
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
try {
$queries = Query::parseQueries($queries);
} catch (QueryException $e) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage());
}
$queries[] = Query::equal('projectInternalId', [$project->getSequence()]);
$keys = $dbForPlatform->find('devKeys', $queries);
$response->dynamic(new Document([
'devKeys' => $keys,
'total' => count($keys),
]), Response::MODEL_DEV_KEY_LIST);
}
}
@@ -2,11 +2,6 @@
namespace Appwrite\Platform\Modules\Projects\Services;
use Appwrite\Platform\Modules\Projects\Http\DevKeys\Create as CreateDevKey;
use Appwrite\Platform\Modules\Projects\Http\DevKeys\Delete as DeleteDevKey;
use Appwrite\Platform\Modules\Projects\Http\DevKeys\Get as GetDevKey;
use Appwrite\Platform\Modules\Projects\Http\DevKeys\Update as UpdateDevKey;
use Appwrite\Platform\Modules\Projects\Http\DevKeys\XList as ListDevKeys;
use Appwrite\Platform\Modules\Projects\Http\Projects\Create as CreateProject;
use Appwrite\Platform\Modules\Projects\Http\Projects\Team\Update as UpdateProjectTeam;
use Appwrite\Platform\Modules\Projects\Http\Projects\Update as UpdateProject;
@@ -23,12 +18,6 @@ class Http extends Service
public function __construct()
{
$this->type = Service::TYPE_HTTP;
$this->addAction(CreateDevKey::getName(), new CreateDevKey());
$this->addAction(UpdateDevKey::getName(), new UpdateDevKey());
$this->addAction(GetDevKey::getName(), new GetDevKey());
$this->addAction(ListDevKeys::getName(), new ListDevKeys());
$this->addAction(DeleteDevKey::getName(), new DeleteDevKey());
$this->addAction(CreateProject::getName(), new CreateProject());
$this->addAction(UpdateProject::getName(), new UpdateProject());
$this->addAction(ListProjects::getName(), new ListProjects());
-18
View File
@@ -171,12 +171,6 @@ class Specs extends Action
'description' => 'The user session to authenticate with',
'in' => 'header',
],
'DevKey' => [
'type' => 'apiKey',
'name' => 'X-Appwrite-Dev-Key',
'description' => 'Your secret dev API key',
'in' => 'header',
],
'Cookie' => [
'type' => 'apiKey',
'name' => 'Cookie',
@@ -261,12 +255,6 @@ class Specs extends Action
'description' => 'The user agent string of the client that made the request',
'in' => 'header',
],
'DevKey' => [
'type' => 'apiKey',
'name' => 'X-Appwrite-Dev-Key',
'description' => 'Your secret dev API key',
'in' => 'header',
],
'Cookie' => [
'type' => 'apiKey',
'name' => 'Cookie',
@@ -357,12 +345,6 @@ class Specs extends Action
'description' => 'The user session to authenticate with',
'in' => 'header',
],
'DevKey' => [
'type' => 'apiKey',
'name' => 'X-Appwrite-Dev-Key',
'description' => 'Your secret dev API key',
'in' => 'header',
],
'ImpersonateUserId' => [
'type' => 'apiKey',
'name' => 'X-Appwrite-Impersonate-User-Id',
@@ -1,20 +0,0 @@
<?php
namespace Appwrite\Utopia\Database\Validator\Queries;
class DevKeys extends Base
{
public const ALLOWED_ATTRIBUTES = [
'accessedAt',
'expire',
];
/**
* Expression constructor
*
*/
public function __construct()
{
parent::__construct('devKeys', self::ALLOWED_ATTRIBUTES);
}
}
-2
View File
@@ -255,8 +255,6 @@ class Response extends SwooleResponse
public const MODEL_KEY = 'key';
public const MODEL_KEY_LIST = 'keyList';
public const MODEL_EPHEMERAL_KEY = 'ephemeralKey';
public const MODEL_DEV_KEY = 'devKey';
public const MODEL_DEV_KEY_LIST = 'devKeyList';
public const MODEL_MOCK_NUMBER = 'mockNumber';
public const MODEL_MOCK_NUMBER_LIST = 'mockNumberList';
public const MODEL_POLICY_LIST = 'policyList';
@@ -21,8 +21,6 @@ class V19 extends Filter
Response::MODEL_PROXY_RULE_LIST => $this->handleList($content, 'rules', fn ($item) => $this->parseProxyRule($item)),
Response::MODEL_MIGRATION => $this->parseMigration($content),
Response::MODEL_MIGRATION_LIST => $this->handleList($content, 'migrations', fn ($item) => $this->parseMigration($item)),
Response::MODEL_PROJECT => $this->parseProject($content),
Response::MODEL_PROJECT_LIST => $this->handleList($content, 'projects', fn ($item) => $this->parseProject($item)),
Response::MODEL_PROVIDER_REPOSITORY => $this->parseProviderRepository($content),
Response::MODEL_TEMPLATE_VARIABLE => $this->parseTemplateVariable($content),
Response::MODEL_VARIABLE => $this->parseVariable($content),
@@ -77,12 +75,6 @@ class V19 extends Filter
return $content;
}
protected function parseProject(array $content)
{
unset($content['devKeys']);
return $content;
}
protected function parseProviderRepository(array $content)
{
unset($content['runtime']);
@@ -1,84 +0,0 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;
class DevKey extends Model
{
public function __construct()
{
$this
->addRule('$id', [
'type' => self::TYPE_STRING,
'description' => 'Key ID.',
'default' => '',
'example' => '5e5ea5c16897e',
])
->addRule('$createdAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Key creation date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('$updatedAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Key update date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('name', [
'type' => self::TYPE_STRING,
'description' => 'Key name.',
'default' => '',
'example' => 'Dev API Key',
])
->addRule('expire', [
'type' => self::TYPE_DATETIME,
'description' => 'Key expiration date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('secret', [
'type' => self::TYPE_STRING,
'description' => 'Secret key.',
'default' => '',
'example' => '919c2d18fb5d4...a2ae413da83346ad2',
])
->addRule('accessedAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Most recent access date in ISO 8601 format. This attribute is only updated again after ' . APP_KEY_ACCESS / 60 / 60 . ' hours.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE
])
->addRule('sdks', [
'type' => self::TYPE_STRING,
'description' => 'List of SDK user agents that used this key.',
'default' => null,
'example' => 'appwrite:flutter',
'array' => true
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'DevKey';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_DEV_KEY;
}
}
@@ -50,15 +50,6 @@ class Project extends Model
'example' => 'fra',
])
// Resource: Dev Keys
->addRule('devKeys', [
'type' => Response::MODEL_DEV_KEY,
'description' => 'Deprecated since 1.9.5: List of dev keys.',
'default' => [],
'example' => new \stdClass(),
'array' => true,
])
// Resource: SMTP
->addRule('smtpEnabled', [
'type' => self::TYPE_BOOLEAN,
@@ -6309,24 +6309,6 @@ final class ProjectsConsoleClientTest extends Scope
$this->assertEquals(404, $response['headers']['status-code']);
}
public function testCreateDevKeyGone(): void
{
$id = $this->setupProject([
'projectId' => ID::unique(),
'name' => 'Dev Key Gone Project',
]);
$response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/dev-keys', array_merge([
'content-type' => 'application/json',
], $this->getHeaders()), [
'name' => 'Dev Key',
'expire' => DateTime::addSeconds(new \DateTime(), 3600),
]);
$this->assertEquals(410, $response['headers']['status-code']);
$this->assertEquals(Exception::DEV_KEY_GONE, $response['body']['type']);
}
public function testProjectLabels(): void
{
// Setup: Prepare team
+1 -1
View File
@@ -2961,7 +2961,7 @@ trait UsersBase
}
/**
* Test impersonation via URL query params — mirrors the ?project= and ?devKey= pattern.
* Test impersonation via URL query params — mirrors the ?project= pattern.
* Allows Console to embed impersonation in direct file/image URLs where headers cannot be set.
*/
public function testImpersonateByQueryParams(): void