diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ca756e5710..f3c96096c4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -221,6 +221,7 @@ jobs:
{ name: 'Notifications', runner: runner4, functional: true, processes: null },
{ name: 'Migrations', runner: runner4, functional: true, processes: 1, documentsdb: true },
{ name: 'Project', runner: runner4, functional: true, processes: null },
+ { name: 'Organization', runner: runner4, functional: true, processes: null },
{ name: 'Presences', runner: runner4, functional: true, processes: null },
];
core.setOutput('services', JSON.stringify(services));
diff --git a/app/config/onboarding.php b/app/config/onboarding.php
index 21a105b878..316ff88cb2 100644
--- a/app/config/onboarding.php
+++ b/app/config/onboarding.php
@@ -13,7 +13,8 @@ return [
'project.createWindowsPlatform' => true,
'project.createLinuxPlatform' => true,
// Connect — API key
- 'project.createKey' => true,
+ 'project.createKey' => true, // TODO: Remove with the project-scoped keys endpoints
+ 'organization.createProjectKey' => true,
// Auth
'users.create' => true,
diff --git a/app/config/roles.php b/app/config/roles.php
index fe952b59bd..d3394b05cf 100644
--- a/app/config/roles.php
+++ b/app/config/roles.php
@@ -92,6 +92,8 @@ $admins = [
'projects.write',
'keys.read',
'keys.write',
+ 'organization.projects.keys.read',
+ 'organization.projects.keys.write',
'devKeys.read',
'devKeys.write',
'webhooks.read',
diff --git a/app/config/scopes/organization.php b/app/config/scopes/organization.php
index d74452f259..0a85dee1b0 100644
--- a/app/config/scopes/organization.php
+++ b/app/config/scopes/organization.php
@@ -12,6 +12,15 @@ return [
"Access to create, update, and delete organization projects",
"category" => "Projects",
],
+ "organization.projects.keys.read" => [
+ "description" => 'Access to read organization projects\' API keys',
+ "category" => "Projects",
+ ],
+ "organization.projects.keys.write" => [
+ "description" =>
+ "Access to create, update, and delete organization projects' API keys",
+ "category" => "Projects",
+ ],
"devKeys.read" => [
"description" => 'Access to read project\'s development keys',
"category" => "Other",
diff --git a/app/config/scopes/project.php b/app/config/scopes/project.php
index 941e236660..4739f91ed6 100644
--- a/app/config/scopes/project.php
+++ b/app/config/scopes/project.php
@@ -17,6 +17,8 @@ return [
'description' => 'Access to read project usage metrics',
'category' => 'Project',
],
+ // TODO: Remove keys.read and keys.write from project key scopes once the Console, CLI and SDKs
+ // manage project keys through the Organization API (organization.projects.keys.*)
"keys.read" => [
"description" =>
"Access to read project\'s keys",
diff --git a/app/controllers/shared/api.php b/app/controllers/shared/api.php
index c13e9a02af..22f3663ab2 100644
--- a/app/controllers/shared/api.php
+++ b/app/controllers/shared/api.php
@@ -1190,7 +1190,7 @@ Http::shutdown()
* cannot suppress RequestCompleted or usage metrics on the same request.
*/
$statusCode = $response->getStatusCode();
- if ($statusCode < 200 || $statusCode >= 300 || $project->getId() === 'console') {
+ if ($statusCode < 200 || $statusCode >= 300) {
return;
}
@@ -1228,6 +1228,19 @@ Http::shutdown()
return;
}
+ // Organization routes act on the project named in the path, not on the console project.
+ if ($project->getId() === 'console') {
+ $projectId = (string) ($route->getParamsValues()['projectId'] ?? '');
+ if ($projectId === '') {
+ return;
+ }
+
+ $project = $authorization->skip(fn () => $dbForPlatform->getDocument('projects', $projectId));
+ if ($project->isEmpty()) {
+ return;
+ }
+ }
+
$byMethod = $project->getAttribute('onboarding', []);
$status = \is_array($byMethod) ? ($byMethod[$method]['status'] ?? null) : null;
if ($status === ONBOARDING_STATUS_COMPLETED || $status === ONBOARDING_STATUS_SKIPPED) {
diff --git a/composer.json b/composer.json
index 8cd6a8178c..cc5bd749a5 100644
--- a/composer.json
+++ b/composer.json
@@ -96,7 +96,7 @@
"utopia-php/platform": "1.0.0-rc20",
"utopia-php/pools": "2.*",
"utopia-php/span": "^4.2",
- "utopia-php/queue": "^2.2.3",
+ "utopia-php/queue": "^2.2.4",
"utopia-php/servers": "0.4.*",
"utopia-php/registry": "0.5.*",
"utopia-php/storage": "^4.0",
diff --git a/composer.lock b/composer.lock
index bc78c7ddae..4029210f89 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "179b6295c070315f1d35007e2da5867d",
+ "content-hash": "c3061710f7b567210d14fb97e6744ef9",
"packages": [
{
"name": "adhocore/jwt",
@@ -4484,16 +4484,16 @@
},
{
"name": "utopia-php/queue",
- "version": "2.2.3",
+ "version": "2.2.4",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/queue.git",
- "reference": "9474bc419fef9680a60ebd7d6773b730402d7446"
+ "reference": "c6994fe68c58d48f303693dad2762d1f80d5bf97"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/utopia-php/queue/zipball/9474bc419fef9680a60ebd7d6773b730402d7446",
- "reference": "9474bc419fef9680a60ebd7d6773b730402d7446",
+ "url": "https://api.github.com/repos/utopia-php/queue/zipball/c6994fe68c58d48f303693dad2762d1f80d5bf97",
+ "reference": "c6994fe68c58d48f303693dad2762d1f80d5bf97",
"shasum": ""
},
"require": {
@@ -4544,9 +4544,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/queue/issues",
- "source": "https://github.com/utopia-php/queue/tree/2.2.3"
+ "source": "https://github.com/utopia-php/queue/tree/2.2.4"
},
- "time": "2026-09-11T10:05:23+00:00"
+ "time": "2026-09-11T17:50:20+00:00"
},
{
"name": "utopia-php/registry",
diff --git a/phpunit.xml b/phpunit.xml
index 65c4e31d0c..575340538c 100644
--- a/phpunit.xml
+++ b/phpunit.xml
@@ -39,6 +39,7 @@
./tests/e2e/Services/Migrations
./tests/e2e/Services/Notifications
./tests/e2e/Services/Project
+ ./tests/e2e/Services/Organization
./tests/e2e/Services/Advisor
./tests/e2e/Services/Usage
./tests/e2e/Services/Functions/FunctionsBase.php
diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Action.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Action.php
new file mode 100644
index 0000000000..c009f7d8b9
--- /dev/null
+++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Action.php
@@ -0,0 +1,36 @@
+getDocument('projects', $projectId);
+
+ if ($project->isEmpty() || $project->getId() === 'console') {
+ throw new Exception(Exception::PROJECT_NOT_FOUND);
+ }
+
+ if ($project->getAttribute('teamInternalId') !== $team->getSequence()) {
+ throw new Exception(Exception::PROJECT_NOT_FOUND);
+ }
+
+ if ($apiKey !== null && !$apiKey->isProjectCheckDisabled() && $apiKey->getProjectId() !== '' && $apiKey->getProjectId() !== $project->getId()) {
+ throw new Exception(Exception::USER_UNAUTHORIZED);
+ }
+
+ return $project;
+ }
+}
diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Create.php
new file mode 100644
index 0000000000..dbef9c87cc
--- /dev/null
+++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Create.php
@@ -0,0 +1,135 @@
+setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
+ ->setHttpPath('/v1/organization/projects/:projectId/keys')
+ ->desc('Create project key')
+ ->groups(['api', 'organization'])
+ ->label('scope', ['organization.projects.keys.write', 'keys.write'])
+ ->label('event', 'keys.[keyId].create')
+ ->label('audits.event', 'project.key.create')
+ ->label('audits.resource', 'project.key/{response.$id}')
+ ->label('sdk', new Method(
+ namespace: 'organization',
+ group: 'keys',
+ name: 'createProjectKey',
+ description: <<param('projectId', '', new UID(), 'Project unique ID.')
+ ->param('keyId', '', fn (Database $dbForPlatform) => new CustomId(false, $dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForPlatform'])
+ ->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
+ ->param('scopes', [], new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_SCOPES_SIZE), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_SCOPES_SIZE . ' scopes are allowed.', optional: false, enum: new Enum(name: 'ProjectKeyScopes'))
+ ->param('expire', null, new Nullable(new Datetime()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
+ ->inject('response')
+ ->inject('queueForEvents')
+ ->inject('dbForPlatform')
+ ->inject('team')
+ ->inject('authorization')
+ ->inject('apiKey')
+ ->inject('auditContext')
+ ->callback($this->action(...));
+ }
+
+ public function action(
+ string $projectId,
+ string $keyId,
+ string $name,
+ array $scopes,
+ ?string $expire,
+ Response $response,
+ QueueEvent $queueForEvents,
+ Database $dbForPlatform,
+ Document $team,
+ Authorization $authorization,
+ ?Key $apiKey,
+ AuditContext $auditContext,
+ ) {
+ // Dynamic supported for backwards compatibility
+ if ($apiKey !== null && \in_array($apiKey->getType(), [API_KEY_STANDARD, API_KEY_EPHEMERAL, 'dynamic'], true)) {
+ throw new Exception(Exception::KEY_CREATION_DENIED);
+ }
+
+ $project = $this->getProject($projectId, $team, $dbForPlatform, $apiKey);
+
+ // The request may run through the console project; events and audits belong to the resolved project
+ $queueForEvents->setProject($project);
+ $auditContext->project = $project;
+ $keyId = ($keyId == 'unique()') ? ID::unique() : $keyId;
+
+ $key = new Document([
+ '$id' => $keyId,
+ '$permissions' => [],
+ 'resourceInternalId' => $project->getSequence(),
+ 'resourceId' => $project->getId(),
+ 'resourceType' => 'projects',
+ 'name' => $name,
+ 'scopes' => $scopes,
+ 'expire' => $expire,
+ 'sdks' => [],
+ 'accessedAt' => null,
+ 'secret' => API_KEY_STANDARD . '_' . \bin2hex(\random_bytes(128)),
+ ]);
+
+ try {
+ $key = $authorization->skip(fn () => $dbForPlatform->createDocument('keys', $key));
+ } catch (DuplicateException) {
+ throw new Exception(Exception::KEY_ALREADY_EXISTS);
+ }
+
+ $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
+
+ $queueForEvents->setParam('keyId', $key->getId());
+
+ $response
+ ->setStatusCode(Response::STATUS_CODE_CREATED)
+ ->dynamic($key, Response::MODEL_KEY);
+ }
+}
diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Delete.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Delete.php
new file mode 100644
index 0000000000..122e09b7f7
--- /dev/null
+++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Delete.php
@@ -0,0 +1,100 @@
+setHttpMethod(Action::HTTP_REQUEST_METHOD_DELETE)
+ ->setHttpPath('/v1/organization/projects/:projectId/keys/:keyId')
+ ->desc('Delete project key')
+ ->groups(['api', 'organization'])
+ ->label('scope', ['organization.projects.keys.write', 'keys.write'])
+ ->label('event', 'keys.[keyId].delete')
+ ->label('audits.event', 'project.key.delete')
+ ->label('audits.resource', 'project.key/{request.keyId}')
+ ->label('sdk', new Method(
+ namespace: 'organization',
+ group: 'keys',
+ name: 'deleteProjectKey',
+ description: <<param('projectId', '', new UID(), 'Project unique ID.')
+ ->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID.', false, ['dbForPlatform'])
+ ->inject('response')
+ ->inject('dbForPlatform')
+ ->inject('queueForEvents')
+ ->inject('team')
+ ->inject('authorization')
+ ->inject('apiKey')
+ ->inject('auditContext')
+ ->callback($this->action(...));
+ }
+
+ public function action(
+ string $projectId,
+ string $keyId,
+ Response $response,
+ Database $dbForPlatform,
+ Event $queueForEvents,
+ Document $team,
+ Authorization $authorization,
+ ?Key $apiKey,
+ AuditContext $auditContext,
+ ) {
+ $project = $this->getProject($projectId, $team, $dbForPlatform, $apiKey);
+
+ // The request may run through the console project; events and audits belong to the resolved project
+ $queueForEvents->setProject($project);
+ $auditContext->project = $project;
+ $key = $authorization->skip(fn () => $dbForPlatform->getDocument('keys', $keyId));
+
+ if ($key->isEmpty() || $key->getAttribute('resourceType', '') !== 'projects' || $key->getAttribute('resourceInternalId', '') !== $project->getSequence()) {
+ throw new Exception(Exception::KEY_NOT_FOUND);
+ }
+
+ if (!$authorization->skip(fn () => $dbForPlatform->deleteDocument('keys', $key->getId()))) {
+ throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove document from DB');
+ }
+
+ $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
+
+ $queueForEvents->setParam('keyId', $key->getId());
+
+ $response->noContent();
+ }
+}
diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Ephemeral/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Ephemeral/Create.php
new file mode 100644
index 0000000000..c88ac87aa3
--- /dev/null
+++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Ephemeral/Create.php
@@ -0,0 +1,122 @@
+setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
+ ->setHttpPath('/v1/organization/projects/:projectId/keys/ephemeral')
+ ->desc('Create ephemeral project key')
+ ->groups(['api', 'organization'])
+ ->label('scope', ['organization.projects.keys.write', 'keys.write'])
+ ->label('event', 'keys.[keyId].create')
+ ->label('audits.event', 'project.key.create')
+ ->label('audits.resource', 'project.key/{response.$id}')
+ ->label('sdk', new Method(
+ namespace: 'organization',
+ group: 'keys',
+ name: 'createEphemeralProjectKey',
+ description: <<param('projectId', '', new UID(), 'Project unique ID.')
+ ->param('scopes', [], new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_SCOPES_SIZE), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_SCOPES_SIZE . ' scopes are allowed.', optional: false, enum: new Enum(name: 'ProjectKeyScopes'))
+ ->param('duration', null, new Range(1, 3600), 'Time in seconds before ephemeral key expires. Maximum duration is 3600 seconds.', optional: false, example: 600)
+ ->inject('response')
+ ->inject('queueForEvents')
+ ->inject('dbForPlatform')
+ ->inject('team')
+ ->inject('apiKey')
+ ->inject('auditContext')
+ ->callback($this->action(...));
+ }
+
+ public function action(
+ string $projectId,
+ array $scopes,
+ int $duration,
+ Response $response,
+ QueueEvent $queueForEvents,
+ Database $dbForPlatform,
+ Document $team,
+ ?Key $apiKey,
+ AuditContext $auditContext,
+ ) {
+ $project = $this->getProject($projectId, $team, $dbForPlatform, $apiKey);
+
+ // The request may run through the console project; events and audits belong to the resolved project
+ $queueForEvents->setProject($project);
+ $auditContext->project = $project;
+ $keyId = ID::unique();
+
+ $jwt = new JWT(System::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', $duration, 0);
+
+ $secret = $jwt->encode([
+ 'projectId' => $project->getId(),
+ 'scopes' => $scopes
+ ]);
+
+ $now = new \DateTime();
+ $expire = $now->add(new \DateInterval('PT' . $duration . 'S'))->format('Y-m-d\TH:i:s.u\Z');
+
+ $key = new Document([
+ '$id' => $keyId,
+ '$createdAt' => DatabaseDateTime::now(),
+ '$updatedAt' => DatabaseDateTime::now(),
+ 'name' => '',
+ 'scopes' => $scopes,
+ 'expire' => $expire,
+ 'sdks' => [],
+ 'accessedAt' => null,
+ 'secret' => API_KEY_EPHEMERAL . '_' . $secret,
+ ]);
+
+ $queueForEvents->setParam('keyId', $key->getId());
+
+ $response
+ ->setStatusCode(Response::STATUS_CODE_CREATED)
+ ->dynamic($key, Response::MODEL_EPHEMERAL_KEY);
+ }
+}
diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Get.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Get.php
new file mode 100644
index 0000000000..015bd72687
--- /dev/null
+++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Get.php
@@ -0,0 +1,78 @@
+setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
+ ->setHttpPath('/v1/organization/projects/:projectId/keys/:keyId')
+ ->desc('Get project key')
+ ->groups(['api', 'organization'])
+ ->label('scope', ['organization.projects.keys.read', 'keys.read'])
+ ->label('sdk', new Method(
+ namespace: 'organization',
+ group: 'keys',
+ name: 'getProjectKey',
+ description: <<param('projectId', '', new UID(), 'Project unique ID.')
+ ->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID.', false, ['dbForPlatform'])
+ ->inject('response')
+ ->inject('dbForPlatform')
+ ->inject('team')
+ ->inject('authorization')
+ ->inject('apiKey')
+ ->callback($this->action(...));
+ }
+
+ public function action(
+ string $projectId,
+ string $keyId,
+ Response $response,
+ Database $dbForPlatform,
+ Document $team,
+ Authorization $authorization,
+ ?Key $apiKey,
+ ) {
+ $project = $this->getProject($projectId, $team, $dbForPlatform, $apiKey);
+
+ $key = $authorization->skip(fn () => $dbForPlatform->getDocument('keys', $keyId));
+
+ if ($key->isEmpty() || $key->getAttribute('resourceType', '') !== 'projects' || $key->getAttribute('resourceInternalId', '') !== $project->getSequence()) {
+ throw new Exception(Exception::KEY_NOT_FOUND);
+ }
+
+ $response->dynamic($key, Response::MODEL_KEY);
+ }
+}
diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Update.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Update.php
new file mode 100644
index 0000000000..00b9abb46f
--- /dev/null
+++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/Update.php
@@ -0,0 +1,120 @@
+setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
+ ->setHttpPath('/v1/organization/projects/:projectId/keys/:keyId')
+ ->desc('Update project key')
+ ->groups(['api', 'organization'])
+ ->label('scope', ['organization.projects.keys.write', 'keys.write'])
+ ->label('event', 'keys.[keyId].update')
+ ->label('audits.event', 'project.key.update')
+ ->label('audits.resource', 'project.key/{response.$id}')
+ ->label('sdk', new Method(
+ namespace: 'organization',
+ group: 'keys',
+ name: 'updateProjectKey',
+ description: <<param('projectId', '', new UID(), 'Project unique ID.')
+ ->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID.', false, ['dbForPlatform'])
+ ->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
+ ->param('scopes', [], new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_SCOPES_SIZE), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_SCOPES_SIZE . ' scopes are allowed.', optional: false, enum: new Enum(name: 'ProjectKeyScopes'))
+ ->param('expire', null, new Nullable(new Datetime()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
+ ->inject('response')
+ ->inject('queueForEvents')
+ ->inject('dbForPlatform')
+ ->inject('team')
+ ->inject('authorization')
+ ->inject('apiKey')
+ ->inject('auditContext')
+ ->callback($this->action(...));
+ }
+
+ public function action(
+ string $projectId,
+ string $keyId,
+ string $name,
+ array $scopes,
+ ?string $expire,
+ Response $response,
+ QueueEvent $queueForEvents,
+ Database $dbForPlatform,
+ Document $team,
+ Authorization $authorization,
+ ?Key $apiKey,
+ AuditContext $auditContext,
+ ) {
+ $project = $this->getProject($projectId, $team, $dbForPlatform, $apiKey);
+
+ // The request may run through the console project; events and audits belong to the resolved project
+ $queueForEvents->setProject($project);
+ $auditContext->project = $project;
+ $key = $authorization->skip(fn () => $dbForPlatform->getDocument('keys', $keyId));
+
+ if ($key->isEmpty() || $key->getAttribute('resourceType', '') !== 'projects' || $key->getAttribute('resourceInternalId', '') !== $project->getSequence()) {
+ throw new Exception(Exception::KEY_NOT_FOUND);
+ }
+
+ $updates = new Document([
+ 'name' => $name,
+ 'scopes' => $scopes,
+ 'expire' => $expire,
+ ]);
+
+ try {
+ $key = $authorization->skip(fn () => $dbForPlatform->updateDocument('keys', $key->getId(), $updates));
+ } catch (Duplicate) {
+ throw new Exception(Exception::KEY_ALREADY_EXISTS);
+ }
+
+ $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
+
+ $queueForEvents->setParam('keyId', $key->getId());
+
+ $response->dynamic($key, Response::MODEL_KEY);
+ }
+}
diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/XList.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/XList.php
new file mode 100644
index 0000000000..71e3a213dd
--- /dev/null
+++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Keys/XList.php
@@ -0,0 +1,132 @@
+setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
+ ->setHttpPath('/v1/organization/projects/:projectId/keys')
+ ->desc('List project keys')
+ ->groups(['api', 'organization'])
+ ->label('scope', ['organization.projects.keys.read', 'keys.read'])
+ ->label('sdk', new Method(
+ namespace: 'organization',
+ group: 'keys',
+ name: 'listProjectKeys',
+ description: <<param('projectId', '', new UID(), 'Project unique ID.')
+ ->param('queries', [], new Keys(), '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(', ', Keys::ALLOWED_ATTRIBUTES), true)
+ ->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
+ ->inject('response')
+ ->inject('dbForPlatform')
+ ->inject('team')
+ ->inject('authorization')
+ ->inject('apiKey')
+ ->callback($this->action(...));
+ }
+
+ /**
+ * @param array $queries
+ */
+ public function action(
+ string $projectId,
+ array $queries,
+ bool $includeTotal,
+ Response $response,
+ Database $dbForPlatform,
+ Document $team,
+ Authorization $authorization,
+ ?Key $apiKey,
+ ) {
+ $project = $this->getProject($projectId, $team, $dbForPlatform, $apiKey);
+
+ try {
+ $queries = Query::parseQueries($queries);
+ } catch (QueryException $e) {
+ throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage());
+ }
+
+ // Backwards compatibility
+ if (\count(Query::getByType($queries, [Query::TYPE_LIMIT])) === 0) {
+ $queries[] = Query::limit(5000);
+ }
+
+ $queries[] = Query::equal('resourceType', ['projects']);
+ $queries[] = Query::equal('resourceInternalId', [$project->getSequence()]);
+
+ $cursor = Query::getCursorQueries($queries, false);
+ $cursor = \reset($cursor);
+
+ if ($cursor !== false) {
+ $validator = new Cursor();
+ if (!$validator->isValid($cursor)) {
+ throw new Exception(Exception::GENERAL_QUERY_INVALID, $validator->getDescription());
+ }
+
+ $keyId = $cursor->getValue();
+ $cursorDocument = $authorization->skip(fn () => $dbForPlatform->findOne('keys', [
+ Query::equal('$id', [$keyId]),
+ Query::equal('resourceType', ['projects']),
+ Query::equal('resourceInternalId', [$project->getSequence()]),
+ ]));
+
+ if ($cursorDocument->isEmpty()) {
+ throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Key '{$keyId}' for the 'cursor' value not found.");
+ }
+
+ $cursor->setValue($cursorDocument);
+ }
+
+ $filterQueries = Query::groupByType($queries)['filters'];
+
+ try {
+ $keys = $authorization->skip(fn () => $dbForPlatform->find('keys', $queries));
+ $total = $includeTotal ? $authorization->skip(fn () => $dbForPlatform->count('keys', $filterQueries, APP_LIMIT_COUNT)) : 0;
+ } catch (OrderException $e) {
+ throw new Exception(Exception::DATABASE_QUERY_ORDER_NULL, "The order attribute '{$e->getAttribute()}' had a null value. Cursor pagination requires all documents order attribute values are non-null.");
+ }
+
+ $response->dynamic(new Document([
+ 'keys' => $keys,
+ 'total' => $total,
+ ]), Response::MODEL_KEY_LIST);
+ }
+}
diff --git a/src/Appwrite/Platform/Modules/Organization/Services/Http.php b/src/Appwrite/Platform/Modules/Organization/Services/Http.php
index 49a8f7d832..ae2a0dd1c0 100644
--- a/src/Appwrite/Platform/Modules/Organization/Services/Http.php
+++ b/src/Appwrite/Platform/Modules/Organization/Services/Http.php
@@ -6,6 +6,12 @@ use Appwrite\Platform\Modules\Organization\Http\Init as Init;
use Appwrite\Platform\Modules\Organization\Http\Projects\Create as CreateProject;
use Appwrite\Platform\Modules\Organization\Http\Projects\Delete as DeleteProject;
use Appwrite\Platform\Modules\Organization\Http\Projects\Get as GetProject;
+use Appwrite\Platform\Modules\Organization\Http\Projects\Keys\Create as CreateProjectKey;
+use Appwrite\Platform\Modules\Organization\Http\Projects\Keys\Delete as DeleteProjectKey;
+use Appwrite\Platform\Modules\Organization\Http\Projects\Keys\Ephemeral\Create as CreateEphemeralProjectKey;
+use Appwrite\Platform\Modules\Organization\Http\Projects\Keys\Get as GetProjectKey;
+use Appwrite\Platform\Modules\Organization\Http\Projects\Keys\Update as UpdateProjectKey;
+use Appwrite\Platform\Modules\Organization\Http\Projects\Keys\XList as ListProjectKeys;
use Appwrite\Platform\Modules\Organization\Http\Projects\Update as UpdateProject;
use Appwrite\Platform\Modules\Organization\Http\Projects\XList as ListProjects;
use Utopia\Platform\Service;
@@ -25,5 +31,13 @@ class Http extends Service
$this->addAction(GetProject::getName(), new GetProject());
$this->addAction(UpdateProject::getName(), new UpdateProject());
$this->addAction(DeleteProject::getName(), new DeleteProject());
+
+ // Project keys
+ $this->addAction(CreateProjectKey::getName(), new CreateProjectKey());
+ $this->addAction(CreateEphemeralProjectKey::getName(), new CreateEphemeralProjectKey());
+ $this->addAction(ListProjectKeys::getName(), new ListProjectKeys());
+ $this->addAction(GetProjectKey::getName(), new GetProjectKey());
+ $this->addAction(UpdateProjectKey::getName(), new UpdateProjectKey());
+ $this->addAction(DeleteProjectKey::getName(), new DeleteProjectKey());
}
}
diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Create.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Create.php
index 20062b5aaf..2909f14c68 100644
--- a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Create.php
+++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Create.php
@@ -26,6 +26,10 @@ use Utopia\Validator\Nullable;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
+/**
+ * TODO: Remove once the Console, CLI and SDKs use the Organization API
+ * (/v1/organization/projects/:projectId/keys) instead of this project-scoped route.
+ */
class Create extends Base
{
use HTTP;
diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Delete.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Delete.php
index c5da673e22..70670e33a7 100644
--- a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Delete.php
+++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Delete.php
@@ -17,6 +17,10 @@ use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
+/**
+ * TODO: Remove once the Console, CLI and SDKs use the Organization API
+ * (/v1/organization/projects/:projectId/keys) instead of this project-scoped route.
+ */
class Delete extends Base
{
use HTTP;
diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Ephemeral/Create.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Ephemeral/Create.php
index 7edd4ed4e9..7a5ddaf34c 100644
--- a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Ephemeral/Create.php
+++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Ephemeral/Create.php
@@ -21,6 +21,10 @@ use Utopia\Validator\ArrayList;
use Utopia\Validator\Range;
use Utopia\Validator\WhiteList;
+/**
+ * TODO: Remove once the Console, CLI and SDKs use the Organization API
+ * (/v1/organization/projects/:projectId/keys) instead of this project-scoped route.
+ */
class Create extends Base
{
use HTTP;
diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Get.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Get.php
index e43c669e4f..fcb4e8b410 100644
--- a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Get.php
+++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Get.php
@@ -15,6 +15,10 @@ use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
+/**
+ * TODO: Remove once the Console, CLI and SDKs use the Organization API
+ * (/v1/organization/projects/:projectId/keys) instead of this project-scoped route.
+ */
class Get extends Base
{
use HTTP;
diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Update.php
index c7156fb66e..557c03c712 100644
--- a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Update.php
+++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/Update.php
@@ -24,6 +24,10 @@ use Utopia\Validator\Nullable;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
+/**
+ * TODO: Remove once the Console, CLI and SDKs use the Organization API
+ * (/v1/organization/projects/:projectId/keys) instead of this project-scoped route.
+ */
class Update extends Base
{
use HTTP;
diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/XList.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/XList.php
index d243e6f2c3..ffa5d62506 100644
--- a/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/XList.php
+++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Keys/XList.php
@@ -20,6 +20,10 @@ use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
+/**
+ * TODO: Remove once the Console, CLI and SDKs use the Organization API
+ * (/v1/organization/projects/:projectId/keys) instead of this project-scoped route.
+ */
class XList extends Base
{
use HTTP;
diff --git a/src/Appwrite/Platform/Modules/Project/Services/Http.php b/src/Appwrite/Platform/Modules/Project/Services/Http.php
index a003f4221c..5d07402d20 100644
--- a/src/Appwrite/Platform/Modules/Project/Services/Http.php
+++ b/src/Appwrite/Platform/Modules/Project/Services/Http.php
@@ -141,6 +141,7 @@ class Http extends Service
$this->addAction(UpdateVariable::getName(), new UpdateVariable());
// Keys
+ // TODO: Remove once the Console, CLI and SDKs use the Organization API instead
$this->addAction(CreateKey::getName(), new CreateKey());
$this->addAction(CreateEphemeralKey::getName(), new CreateEphemeralKey());
$this->addAction(ListKeys::getName(), new ListKeys());
diff --git a/src/Appwrite/Utopia/Request/Filters/V21.php b/src/Appwrite/Utopia/Request/Filters/V21.php
index 357f00cfdc..e000bbe331 100644
--- a/src/Appwrite/Utopia/Request/Filters/V21.php
+++ b/src/Appwrite/Utopia/Request/Filters/V21.php
@@ -72,6 +72,7 @@ class V21 extends Filter
$content = $this->fillWebhookid($content);
break;
case 'project.createKey':
+ case 'organization.createProjectKey':
$content = $this->fillKeyId($content);
break;
case 'project.createVariable':
diff --git a/src/Appwrite/Utopia/Request/Filters/V22.php b/src/Appwrite/Utopia/Request/Filters/V22.php
index 7e4c5b8e41..3c710c1e1c 100644
--- a/src/Appwrite/Utopia/Request/Filters/V22.php
+++ b/src/Appwrite/Utopia/Request/Filters/V22.php
@@ -81,6 +81,8 @@ class V22 extends Filter
break;
case 'project.createKey':
case 'project.updateKey':
+ case 'organization.createProjectKey':
+ case 'organization.updateProjectKey':
$content = $this->parseKeyScopes($content);
break;
case 'webhooks.create':
diff --git a/tests/e2e/Services/Console/ConsoleConsoleClientTest.php b/tests/e2e/Services/Console/ConsoleConsoleClientTest.php
index 802cb4bea7..597256be7c 100644
--- a/tests/e2e/Services/Console/ConsoleConsoleClientTest.php
+++ b/tests/e2e/Services/Console/ConsoleConsoleClientTest.php
@@ -196,6 +196,8 @@ final class ConsoleConsoleClientTest extends Scope
// Well-known scopes must be present
$this->assertContains('projects.read', $scopeIds);
$this->assertContains('projects.write', $scopeIds);
+ $this->assertContains('organization.projects.keys.read', $scopeIds);
+ $this->assertContains('organization.projects.keys.write', $scopeIds);
// Every scope has the expected shape
foreach ($response['body']['scopes'] as $scope) {
diff --git a/tests/e2e/Services/Console/ConsoleCustomServerTest.php b/tests/e2e/Services/Console/ConsoleCustomServerTest.php
index b3adc2b940..98550ccc3a 100644
--- a/tests/e2e/Services/Console/ConsoleCustomServerTest.php
+++ b/tests/e2e/Services/Console/ConsoleCustomServerTest.php
@@ -93,6 +93,8 @@ final class ConsoleCustomServerTest extends Scope
$scopeIds = \array_column($response['body']['scopes'], '$id');
$this->assertContains('projects.read', $scopeIds);
+ $this->assertContains('organization.projects.keys.read', $scopeIds);
+ $this->assertContains('organization.projects.keys.write', $scopeIds);
$projectsRead = null;
foreach ($response['body']['scopes'] as $scope) {
diff --git a/tests/e2e/Services/Organization/KeysBase.php b/tests/e2e/Services/Organization/KeysBase.php
new file mode 100644
index 0000000000..250723c975
--- /dev/null
+++ b/tests/e2e/Services/Organization/KeysBase.php
@@ -0,0 +1,1233 @@
+createKey(
+ ID::unique(),
+ 'My API Key',
+ ['users.read', 'users.write'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertNotEmpty($key['body']['$id']);
+ $this->assertSame('My API Key', $key['body']['name']);
+ $this->assertSame(['users.read', 'users.write'], $key['body']['scopes']);
+ $this->assertNotEmpty($key['body']['secret']);
+ $this->assertSame('', $key['body']['expire']);
+ $this->assertSame('', $key['body']['accessedAt']);
+ $this->assertSame([], $key['body']['sdks']);
+
+ $dateValidator = new DatetimeValidator();
+ $this->assertSame(true, $dateValidator->isValid($key['body']['$createdAt']));
+ $this->assertSame(true, $dateValidator->isValid($key['body']['$updatedAt']));
+
+ // Verify via GET
+ $get = $this->getKey($key['body']['$id']);
+ $this->assertSame(200, $get['headers']['status-code']);
+ $this->assertSame($key['body']['$id'], $get['body']['$id']);
+ $this->assertSame('My API Key', $get['body']['name']);
+ $this->assertSame(['users.read', 'users.write'], $get['body']['scopes']);
+
+ // Verify via LIST
+ $list = $this->listKeys(null, true);
+ $this->assertSame(200, $list['headers']['status-code']);
+ $this->assertGreaterThanOrEqual(1, $list['body']['total']);
+ $this->assertGreaterThanOrEqual(1, \count($list['body']['keys']));
+
+ // Cleanup
+ $this->deleteKey($key['body']['$id']);
+ }
+
+ public function testCreateKeyWithExpire(): void
+ {
+ $expire = '2030-01-01T00:00:00.000+00:00';
+
+ $key = $this->createKey(
+ ID::unique(),
+ 'Expiring Key',
+ ['users.read'],
+ $expire,
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertSame($expire, $key['body']['expire']);
+
+ // Verify via GET
+ $get = $this->getKey($key['body']['$id']);
+ $this->assertSame(200, $get['headers']['status-code']);
+ $this->assertSame($expire, $get['body']['expire']);
+
+ // Cleanup
+ $this->deleteKey($key['body']['$id']);
+ }
+
+ public function testCreateKeyWithEmptyScopes(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Empty Scopes Key',
+ [],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertSame([], $key['body']['scopes']);
+
+ // Cleanup
+ $this->deleteKey($key['body']['$id']);
+ }
+
+ public function testCreateKeyWithNullScopesV22BackwardCompat(): void
+ {
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ 'x-appwrite-response-format' => '1.9.0',
+ // Key creation is denied for key-authorized requests, so always use a console session
+ 'origin' => 'http://localhost',
+ 'cookie' => 'a_session_console=' . $this->getRoot()['session'],
+ 'x-appwrite-mode' => 'admin',
+ ];
+
+ $key = $this->client->call(Client::METHOD_POST, $this->keysPath(), $headers, [
+ 'keyId' => ID::unique(),
+ 'name' => 'V22 Compat Key',
+ 'scopes' => null,
+ ]);
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertSame([], $key['body']['scopes']);
+
+ // Cleanup
+ $this->deleteKey($key['body']['$id']);
+ }
+
+ public function testUpdateKeyWithNullScopesV22BackwardCompat(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'V22 Update Compat Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ 'x-appwrite-response-format' => '1.9.0',
+ ];
+ $headers = array_merge($headers, $this->getHeaders());
+
+ $updated = $this->client->call(Client::METHOD_PUT, $this->keysPath() . '/' . $keyId, $headers, [
+ 'name' => 'V22 Update Compat Key',
+ 'scopes' => null,
+ ]);
+
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame([], $updated['body']['scopes']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testCreateKeyWithoutAuthentication(): void
+ {
+ $response = $this->createKey(
+ ID::unique(),
+ 'No Auth Key',
+ ['users.read'],
+ null,
+ false
+ );
+
+ $this->assertSame(401, $response['headers']['status-code']);
+ }
+
+ public function testCreateKeyInvalidId(): void
+ {
+ $key = $this->createKey(
+ '!invalid-id!',
+ 'Invalid ID Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(400, $key['headers']['status-code']);
+ }
+
+ public function testCreateKeyMissingName(): void
+ {
+ $response = $this->createKey(
+ ID::unique(),
+ null,
+ ['users.read'],
+ );
+
+ $this->assertSame(400, $response['headers']['status-code']);
+ }
+
+ public function testCreateKeyInvalidScope(): void
+ {
+ $response = $this->createKey(
+ ID::unique(),
+ 'Invalid Scope Key',
+ ['invalid.scope'],
+ );
+
+ $this->assertSame(400, $response['headers']['status-code']);
+ }
+
+ public function testCreateKeyDuplicateId(): void
+ {
+ $keyId = ID::unique();
+
+ $key = $this->createKey(
+ $keyId,
+ 'Key Dup 1',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+
+ // Attempt to create with same ID
+ $duplicate = $this->createKey(
+ $keyId,
+ 'Key Dup 2',
+ ['users.write'],
+ );
+
+ $this->assertSame(409, $duplicate['headers']['status-code']);
+ $this->assertSame('key_already_exists', $duplicate['body']['type']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testCreateKeyCustomId(): void
+ {
+ $customId = 'my-custom-key-id';
+
+ $key = $this->createKey(
+ $customId,
+ 'Custom ID Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertSame($customId, $key['body']['$id']);
+
+ // Verify via GET
+ $get = $this->getKey($customId);
+ $this->assertSame(200, $get['headers']['status-code']);
+ $this->assertSame($customId, $get['body']['$id']);
+
+ // Cleanup
+ $this->deleteKey($customId);
+ }
+
+ public function testCreateKeyRequiresSession(): void
+ {
+ // A request authorized with a standard API key cannot create a key
+ $response = $this->client->call(Client::METHOD_POST, $this->keysPath(), [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ 'x-appwrite-key' => $this->getProject()['apiKey'],
+ ], [
+ 'keyId' => ID::unique(),
+ 'name' => 'Key Made By Key',
+ 'scopes' => ['users.read'],
+ ]);
+
+ $this->assertSame(403, $response['headers']['status-code']);
+ $this->assertSame('key_creation_denied', $response['body']['type']);
+
+ // A request authorized with an ephemeral key cannot create a key either
+ $ephemeral = $this->createEphemeralKey(['keys.read', 'keys.write'], 900);
+ $this->assertSame(201, $ephemeral['headers']['status-code']);
+
+ $response = $this->client->call(Client::METHOD_POST, $this->keysPath(), [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ 'x-appwrite-key' => $ephemeral['body']['secret'],
+ ], [
+ 'keyId' => ID::unique(),
+ 'name' => 'Key Made By Ephemeral Key',
+ 'scopes' => ['users.read'],
+ ]);
+
+ $this->assertSame(403, $response['headers']['status-code']);
+ $this->assertSame('key_creation_denied', $response['body']['type']);
+ }
+
+ // =========================================================================
+ // Create ephemeral key tests
+ // =========================================================================
+
+ public function testCreateEphemeralKey(): void
+ {
+ $duration = 900;
+
+ $key = $this->createEphemeralKey(
+ ['users.read', 'users.write'],
+ $duration,
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertNotEmpty($key['body']['$id']);
+ $this->assertSame('', $key['body']['name']);
+ $this->assertSame(['users.read', 'users.write'], $key['body']['scopes']);
+ $this->assertNotEmpty($key['body']['secret']);
+ $this->assertStringStartsWith(API_KEY_EPHEMERAL . '_', $key['body']['secret']);
+ $this->assertSame([], $key['body']['sdks']);
+ $this->assertSame('', $key['body']['accessedAt']);
+
+ $dateValidator = new DatetimeValidator();
+ $this->assertSame(true, $dateValidator->isValid($key['body']['$createdAt']));
+ $this->assertSame(true, $dateValidator->isValid($key['body']['$updatedAt']));
+ $this->assertSame(true, $dateValidator->isValid($key['body']['expire']));
+
+ // The key authenticates requests against the project it was issued for
+ $users = $this->client->call(Client::METHOD_GET, '/users', [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ 'x-appwrite-key' => $key['body']['secret'],
+ ]);
+
+ $this->assertSame(200, $users['headers']['status-code']);
+
+ $expireDt = new \DateTime($key['body']['expire']);
+ $now = new \DateTime();
+ $diff = $expireDt->getTimestamp() - $now->getTimestamp();
+ $this->assertGreaterThanOrEqual($duration - 10, $diff);
+ $this->assertLessThanOrEqual($duration + 10, $diff);
+ }
+
+ public function testCreateEphemeralKeyWithDuration(): void
+ {
+ $duration = 1800;
+
+ $key = $this->createEphemeralKey(
+ ['databases.read'],
+ $duration,
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertSame(['databases.read'], $key['body']['scopes']);
+
+ $expireDt = new \DateTime($key['body']['expire']);
+ $now = new \DateTime();
+ $diff = $expireDt->getTimestamp() - $now->getTimestamp();
+ $this->assertGreaterThanOrEqual($duration - 10, $diff);
+ $this->assertLessThanOrEqual($duration + 10, $diff);
+ }
+
+ public function testCreateEphemeralKeyWithEmptyScopes(): void
+ {
+ $key = $this->createEphemeralKey(
+ [],
+ 900,
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertSame([], $key['body']['scopes']);
+ }
+
+ public function testCreateEphemeralKeyWithoutAuthentication(): void
+ {
+ $response = $this->createEphemeralKey(
+ ['users.read'],
+ 900,
+ false
+ );
+
+ $this->assertSame(401, $response['headers']['status-code']);
+ }
+
+ public function testCreateEphemeralKeyMissingDuration(): void
+ {
+ $response = $this->createEphemeralKey(
+ ['users.read'],
+ );
+
+ $this->assertSame(400, $response['headers']['status-code']);
+ }
+
+ public function testCreateEphemeralKeyInvalidScope(): void
+ {
+ $response = $this->createEphemeralKey(
+ ['invalid.scope'],
+ 900,
+ );
+
+ $this->assertSame(400, $response['headers']['status-code']);
+ }
+
+ public function testCreateEphemeralKeyInvalidDuration(): void
+ {
+ $response = $this->createEphemeralKey(
+ ['users.read'],
+ 0,
+ );
+
+ $this->assertSame(400, $response['headers']['status-code']);
+
+ $response = $this->createEphemeralKey(
+ ['users.read'],
+ 3601,
+ );
+
+ $this->assertSame(400, $response['headers']['status-code']);
+ }
+
+ // =========================================================================
+ // Update key tests
+ // =========================================================================
+
+ public function testUpdateKey(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Original Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // Update name, scopes, and expire
+ $expire = '2031-06-15T12:00:00.000+00:00';
+ $updated = $this->updateKey($keyId, 'Updated Key', ['users.write', 'databases.read'], $expire);
+
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame($keyId, $updated['body']['$id']);
+ $this->assertSame('Updated Key', $updated['body']['name']);
+ $this->assertSame(['users.write', 'databases.read'], $updated['body']['scopes']);
+ $this->assertSame($expire, $updated['body']['expire']);
+
+ // Verify update persisted via GET
+ $get = $this->getKey($keyId);
+ $this->assertSame(200, $get['headers']['status-code']);
+ $this->assertSame('Updated Key', $get['body']['name']);
+ $this->assertSame(['users.write', 'databases.read'], $get['body']['scopes']);
+ $this->assertSame($expire, $get['body']['expire']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testUpdateKeyName(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Name Before',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ $updated = $this->updateKey($keyId, 'Name After', ['users.read']);
+
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame('Name After', $updated['body']['name']);
+ $this->assertSame(['users.read'], $updated['body']['scopes']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testUpdateKeyScopes(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Scopes Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ $updated = $this->updateKey($keyId, 'Scopes Key', ['databases.read', 'databases.write']);
+
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame(['databases.read', 'databases.write'], $updated['body']['scopes']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testUpdateKeySetExpire(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'No Expire Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $this->assertSame('', $key['body']['expire']);
+ $keyId = $key['body']['$id'];
+
+ $expire = '2032-12-31T23:59:59.000+00:00';
+ $updated = $this->updateKey($keyId, 'No Expire Key', ['users.read'], $expire);
+
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame($expire, $updated['body']['expire']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testUpdateKeyRemoveExpire(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Expire Key',
+ ['users.read'],
+ '2030-01-01T00:00:00.000+00:00',
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // Remove expire by setting to null
+ $updated = $this->updateKey($keyId, 'Expire Key', ['users.read'], null);
+
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame('', $updated['body']['expire']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testUpdateKeyWithoutAuthentication(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Auth Update Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // Attempt update without authentication
+ $response = $this->updateKey($keyId, 'Updated Name', ['users.read'], null, false);
+
+ $this->assertSame(401, $response['headers']['status-code']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testUpdateKeyNotFound(): void
+ {
+ $updated = $this->updateKey('non-existent-id', 'New Name', ['users.read']);
+
+ $this->assertSame(404, $updated['headers']['status-code']);
+ $this->assertSame('key_not_found', $updated['body']['type']);
+ }
+
+ public function testUpdateKeyInvalidScope(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Invalid Scope Update',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ $updated = $this->updateKey($keyId, 'Invalid Scope Update', ['invalid.scope']);
+
+ $this->assertSame(400, $updated['headers']['status-code']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ // =========================================================================
+ // Get key tests
+ // =========================================================================
+
+ public function testGetKey(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Get Test Key',
+ ['users.read', 'databases.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ $get = $this->getKey($keyId);
+
+ $this->assertSame(200, $get['headers']['status-code']);
+ $this->assertSame($keyId, $get['body']['$id']);
+ $this->assertSame('Get Test Key', $get['body']['name']);
+ $this->assertSame(['users.read', 'databases.read'], $get['body']['scopes']);
+ $this->assertNotEmpty($get['body']['secret']);
+ $this->assertSame('', $get['body']['expire']);
+ $this->assertSame('', $get['body']['accessedAt']);
+ $this->assertSame([], $get['body']['sdks']);
+
+ $dateValidator = new DatetimeValidator();
+ $this->assertSame(true, $dateValidator->isValid($get['body']['$createdAt']));
+ $this->assertSame(true, $dateValidator->isValid($get['body']['$updatedAt']));
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testGetKeyNotFound(): void
+ {
+ $get = $this->getKey('non-existent-id');
+
+ $this->assertSame(404, $get['headers']['status-code']);
+ $this->assertSame('key_not_found', $get['body']['type']);
+ }
+
+ public function testGetKeyWithoutAuthentication(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Auth Get Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // Attempt GET without authentication
+ $response = $this->getKey($keyId, false);
+
+ $this->assertSame(401, $response['headers']['status-code']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ // =========================================================================
+ // List keys tests
+ // =========================================================================
+
+ public function testListKeys(): void
+ {
+ // Create multiple keys
+ $key1 = $this->createKey(
+ ID::unique(),
+ 'List Key Alpha',
+ ['users.read'],
+ );
+ $this->assertSame(201, $key1['headers']['status-code']);
+
+ $key2 = $this->createKey(
+ ID::unique(),
+ 'List Key Beta',
+ ['databases.read'],
+ );
+ $this->assertSame(201, $key2['headers']['status-code']);
+
+ $key3 = $this->createKey(
+ ID::unique(),
+ 'List Key Gamma',
+ ['users.write'],
+ );
+ $this->assertSame(201, $key3['headers']['status-code']);
+
+ // List all
+ $list = $this->listKeys(null, true);
+
+ $this->assertSame(200, $list['headers']['status-code']);
+ $this->assertGreaterThanOrEqual(3, $list['body']['total']);
+ $this->assertGreaterThanOrEqual(3, \count($list['body']['keys']));
+ $this->assertIsArray($list['body']['keys']);
+
+ // Verify structure of returned keys
+ foreach ($list['body']['keys'] as $key) {
+ $this->assertArrayHasKey('$id', $key);
+ $this->assertArrayHasKey('$createdAt', $key);
+ $this->assertArrayHasKey('$updatedAt', $key);
+ $this->assertArrayHasKey('name', $key);
+ $this->assertArrayHasKey('scopes', $key);
+ $this->assertArrayHasKey('secret', $key);
+ $this->assertArrayHasKey('expire', $key);
+ $this->assertArrayHasKey('accessedAt', $key);
+ $this->assertArrayHasKey('sdks', $key);
+ }
+
+ // Cleanup
+ $this->deleteKey($key1['body']['$id']);
+ $this->deleteKey($key2['body']['$id']);
+ $this->deleteKey($key3['body']['$id']);
+ }
+
+ public function testListKeysWithLimit(): void
+ {
+ $key1 = $this->createKey(
+ ID::unique(),
+ 'Limit Key 1',
+ ['users.read'],
+ );
+ $this->assertSame(201, $key1['headers']['status-code']);
+
+ $key2 = $this->createKey(
+ ID::unique(),
+ 'Limit Key 2',
+ ['users.write'],
+ );
+ $this->assertSame(201, $key2['headers']['status-code']);
+
+ // List with limit 1
+ $list = $this->listKeys([
+ Query::limit(1)->toString(),
+ ], true);
+
+ $this->assertSame(200, $list['headers']['status-code']);
+ $this->assertCount(1, $list['body']['keys']);
+ $this->assertGreaterThanOrEqual(2, $list['body']['total']);
+
+ // Cleanup
+ $this->deleteKey($key1['body']['$id']);
+ $this->deleteKey($key2['body']['$id']);
+ }
+
+ public function testListKeysWithoutTotal(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'No Total Key',
+ ['users.read'],
+ );
+ $this->assertSame(201, $key['headers']['status-code']);
+
+ // List with total=false
+ $list = $this->listKeys(null, false);
+
+ $this->assertSame(200, $list['headers']['status-code']);
+ $this->assertSame(0, $list['body']['total']);
+ $this->assertGreaterThanOrEqual(1, \count($list['body']['keys']));
+
+ // Cleanup
+ $this->deleteKey($key['body']['$id']);
+ }
+
+ public function testListKeysCursorPagination(): void
+ {
+ $key1 = $this->createKey(
+ ID::unique(),
+ 'Cursor Key 1',
+ ['users.read'],
+ );
+ $this->assertSame(201, $key1['headers']['status-code']);
+
+ $key2 = $this->createKey(
+ ID::unique(),
+ 'Cursor Key 2',
+ ['users.write'],
+ );
+ $this->assertSame(201, $key2['headers']['status-code']);
+
+ // Get first page with limit 1
+ $page1 = $this->listKeys([
+ Query::limit(1)->toString(),
+ ], true);
+
+ $this->assertSame(200, $page1['headers']['status-code']);
+ $this->assertCount(1, $page1['body']['keys']);
+ $cursorId = $page1['body']['keys'][0]['$id'];
+
+ // Get next page using cursor
+ $page2 = $this->listKeys([
+ Query::limit(1)->toString(),
+ Query::cursorAfter(new Document(['$id' => $cursorId]))->toString(),
+ ], true);
+
+ $this->assertSame(200, $page2['headers']['status-code']);
+ $this->assertCount(1, $page2['body']['keys']);
+ $this->assertNotEquals($cursorId, $page2['body']['keys'][0]['$id']);
+
+ // Cleanup
+ $this->deleteKey($key1['body']['$id']);
+ $this->deleteKey($key2['body']['$id']);
+ }
+
+ public function testListKeysWithoutAuthentication(): void
+ {
+ $response = $this->listKeys(null, null, false);
+
+ $this->assertSame(401, $response['headers']['status-code']);
+ }
+
+ public function testListKeysInvalidCursor(): void
+ {
+ $list = $this->listKeys([
+ Query::cursorAfter(new Document(['$id' => 'non-existent-id']))->toString(),
+ ], true);
+
+ $this->assertSame(400, $list['headers']['status-code']);
+ }
+
+ // =========================================================================
+ // Delete key tests
+ // =========================================================================
+
+ public function testDeleteKey(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Delete Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // Verify it exists
+ $get = $this->getKey($keyId);
+ $this->assertSame(200, $get['headers']['status-code']);
+
+ // Delete
+ $delete = $this->deleteKey($keyId);
+ $this->assertSame(204, $delete['headers']['status-code']);
+ $this->assertEmpty($delete['body']);
+
+ // Verify it no longer exists
+ $get = $this->getKey($keyId);
+ $this->assertSame(404, $get['headers']['status-code']);
+ $this->assertSame('key_not_found', $get['body']['type']);
+ }
+
+ public function testDeleteKeyNotFound(): void
+ {
+ $delete = $this->deleteKey('non-existent-id');
+
+ $this->assertSame(404, $delete['headers']['status-code']);
+ $this->assertSame('key_not_found', $delete['body']['type']);
+ }
+
+ public function testDeleteKeyWithoutAuthentication(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Delete Auth Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // Attempt DELETE without authentication
+ $response = $this->deleteKey($keyId, false);
+
+ $this->assertSame(401, $response['headers']['status-code']);
+
+ // Verify it still exists
+ $get = $this->getKey($keyId);
+ $this->assertSame(200, $get['headers']['status-code']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testDeleteKeyRemovedFromList(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Delete List Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // Get list count before delete
+ $listBefore = $this->listKeys(null, true);
+ $this->assertSame(200, $listBefore['headers']['status-code']);
+ $countBefore = $listBefore['body']['total'];
+
+ // Delete
+ $delete = $this->deleteKey($keyId);
+ $this->assertSame(204, $delete['headers']['status-code']);
+
+ // Get list count after delete
+ $listAfter = $this->listKeys(null, true);
+ $this->assertSame(200, $listAfter['headers']['status-code']);
+ $this->assertSame($countBefore - 1, $listAfter['body']['total']);
+
+ // Verify the deleted key is not in the list
+ $ids = \array_column($listAfter['body']['keys'], '$id');
+ $this->assertNotContains($keyId, $ids);
+ }
+
+ public function testDeleteKeyDoubleDelete(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Double Delete Key',
+ ['users.read'],
+ );
+
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ // First delete succeeds
+ $delete = $this->deleteKey($keyId);
+ $this->assertSame(204, $delete['headers']['status-code']);
+
+ // Second delete returns 404
+ $delete = $this->deleteKey($keyId);
+ $this->assertSame(404, $delete['headers']['status-code']);
+ $this->assertSame('key_not_found', $delete['body']['type']);
+ }
+
+ // =========================================================================
+ // Organization scope tests
+ // =========================================================================
+
+ public function testListKeysWithOrganizationHeader(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Organization Header Key',
+ ['users.read'],
+ );
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ $headers = $this->getOrganizationHeaders($this->getTeamId());
+
+ /**
+ * Test for SUCCESS
+ */
+ $list = $this->client->call(Client::METHOD_GET, $this->keysPath(), $headers);
+
+ $this->assertSame(200, $list['headers']['status-code']);
+ $this->assertContains($keyId, \array_column($list['body']['keys'], '$id'));
+
+ $get = $this->client->call(Client::METHOD_GET, $this->keysPath() . '/' . $keyId, $headers);
+
+ $this->assertSame(200, $get['headers']['status-code']);
+ $this->assertSame('Organization Header Key', $get['body']['name']);
+
+ $updated = $this->client->call(Client::METHOD_PUT, $this->keysPath() . '/' . $keyId, $headers, [
+ 'name' => 'Organization Header Key Updated',
+ 'scopes' => ['users.read', 'users.write'],
+ ]);
+
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame('Organization Header Key Updated', $updated['body']['name']);
+
+ $created = $this->client->call(Client::METHOD_POST, $this->keysPath(), $headers, [
+ 'keyId' => ID::unique(),
+ 'name' => 'Organization Header Created Key',
+ 'scopes' => ['users.read'],
+ ]);
+
+ $this->assertSame(201, $created['headers']['status-code']);
+ $this->assertNotEmpty($created['body']['secret']);
+
+ $ephemeral = $this->client->call(Client::METHOD_POST, $this->keysPath() . '/ephemeral', $headers, [
+ 'scopes' => ['users.read'],
+ 'duration' => 900,
+ ]);
+
+ $this->assertSame(201, $ephemeral['headers']['status-code']);
+ $this->assertStringStartsWith(API_KEY_EPHEMERAL . '_', $ephemeral['body']['secret']);
+
+ $delete = $this->client->call(Client::METHOD_DELETE, $this->keysPath() . '/' . $created['body']['$id'], $headers);
+
+ $this->assertSame(204, $delete['headers']['status-code']);
+
+ /**
+ * Test for FAILURE - missing organization header
+ */
+ $list = $this->client->call(Client::METHOD_GET, $this->keysPath(), $this->getConsoleHeaders());
+
+ $this->assertSame(401, $list['headers']['status-code']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testListKeysFromOtherOrganization(): void
+ {
+ $key = $this->createKey(
+ ID::unique(),
+ 'Other Organization Key',
+ ['users.read'],
+ );
+ $this->assertSame(201, $key['headers']['status-code']);
+ $keyId = $key['body']['$id'];
+
+ $otherTeam = $this->createTeamFixture($this->getConsoleHeaders(), [
+ 'teamId' => ID::unique(),
+ 'name' => 'Other Organization',
+ ]);
+ $this->assertSame(200, $otherTeam['headers']['status-code']);
+
+ $headers = $this->getOrganizationHeaders($otherTeam['body']['$id']);
+
+ /**
+ * Test for FAILURE - project belongs to another organization
+ */
+ $list = $this->client->call(Client::METHOD_GET, $this->keysPath(), $headers);
+
+ $this->assertSame(404, $list['headers']['status-code']);
+ $this->assertSame('project_not_found', $list['body']['type']);
+
+ $get = $this->client->call(Client::METHOD_GET, $this->keysPath() . '/' . $keyId, $headers);
+
+ $this->assertSame(404, $get['headers']['status-code']);
+ $this->assertSame('project_not_found', $get['body']['type']);
+
+ $delete = $this->client->call(Client::METHOD_DELETE, $this->keysPath() . '/' . $keyId, $headers);
+
+ $this->assertSame(404, $delete['headers']['status-code']);
+ $this->assertSame('project_not_found', $delete['body']['type']);
+
+ // Verify the key still exists
+ $get = $this->getKey($keyId);
+ $this->assertSame(200, $get['headers']['status-code']);
+
+ // Cleanup
+ $this->deleteKey($keyId);
+ }
+
+ public function testListKeysWithSiblingProjectKey(): void
+ {
+ $sibling = $this->client->call(Client::METHOD_POST, '/projects', $this->getConsoleHeaders(), [
+ 'projectId' => ID::unique(),
+ 'name' => 'Sibling Project',
+ 'teamId' => $this->getTeamId(),
+ 'region' => System::getEnv('_APP_REGION', 'default'),
+ ]);
+ $this->assertSame(201, $sibling['headers']['status-code']);
+ $siblingId = $sibling['body']['$id'];
+
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ 'x-appwrite-key' => $this->getProject()['apiKey'],
+ ];
+
+ /**
+ * Test for SUCCESS - a project key reaches its own project
+ */
+ $list = $this->client->call(Client::METHOD_GET, $this->keysPath(), $headers);
+
+ $this->assertSame(200, $list['headers']['status-code']);
+
+ /**
+ * Test for FAILURE - a project key must not reach a sibling project of the same organization
+ */
+ $list = $this->client->call(Client::METHOD_GET, '/organization/projects/' . $siblingId . '/keys', $headers);
+
+ $this->assertSame(401, $list['headers']['status-code']);
+ $this->assertSame('user_unauthorized', $list['body']['type']);
+
+ // Cleanup
+ $delete = $this->client->call(Client::METHOD_DELETE, '/projects/' . $siblingId, $this->getConsoleHeaders());
+ $this->assertSame(204, $delete['headers']['status-code']);
+ }
+
+ // =========================================================================
+ // Helpers
+ // =========================================================================
+
+ protected function keysPath(): string
+ {
+ return '/organization/projects/' . $this->getProject()['$id'] . '/keys';
+ }
+
+ protected function getTeamId(): string
+ {
+ $project = $this->client->call(Client::METHOD_GET, '/projects/' . $this->getProject()['$id'], $this->getConsoleHeaders());
+
+ $this->assertSame(200, $project['headers']['status-code']);
+
+ return $project['body']['teamId'];
+ }
+
+ /**
+ * Console session headers for the console project.
+ */
+ protected function getConsoleHeaders(): array
+ {
+ return [
+ 'origin' => 'http://localhost',
+ 'content-type' => 'application/json',
+ 'cookie' => 'a_session_console=' . $this->getRoot()['session'],
+ 'x-appwrite-project' => 'console',
+ ];
+ }
+
+ /**
+ * Console session headers acting on behalf of an organization.
+ */
+ protected function getOrganizationHeaders(string $teamId): array
+ {
+ return array_merge($this->getConsoleHeaders(), [
+ 'x-appwrite-organization' => $teamId,
+ ]);
+ }
+
+ /**
+ * @param array|null $scopes
+ */
+ protected function createKey(string $keyId, ?string $name, ?array $scopes = null, ?string $expire = null, bool $authenticated = true): mixed
+ {
+ $params = [
+ 'keyId' => $keyId,
+ 'scopes' => $scopes,
+ ];
+
+ if ($name !== null) {
+ $params['name'] = $name;
+ }
+
+ if ($expire !== null) {
+ $params['expire'] = $expire;
+ }
+
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ ];
+
+ if ($authenticated) {
+ // Key creation is denied for key-authorized requests, so always use a console session
+ $headers = array_merge($headers, [
+ 'origin' => 'http://localhost',
+ 'cookie' => 'a_session_console=' . $this->getRoot()['session'],
+ 'x-appwrite-mode' => 'admin',
+ ]);
+ }
+
+ return $this->client->call(Client::METHOD_POST, $this->keysPath(), $headers, $params);
+ }
+
+ /**
+ * @param array|null $scopes
+ */
+ protected function updateKey(string $keyId, ?string $name = null, ?array $scopes = null, ?string $expire = null, bool $authenticated = true): mixed
+ {
+ $params = [];
+
+ if ($name !== null) {
+ $params['name'] = $name;
+ }
+
+ if ($scopes !== null) {
+ $params['scopes'] = $scopes;
+ }
+
+ if ($expire !== null) {
+ $params['expire'] = $expire;
+ }
+
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ ];
+
+ if ($authenticated) {
+ $headers = array_merge($headers, $this->getHeaders());
+ }
+
+ return $this->client->call(Client::METHOD_PUT, $this->keysPath() . '/' . $keyId, $headers, $params);
+ }
+
+ protected function getKey(string $keyId, bool $authenticated = true): mixed
+ {
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ ];
+
+ if ($authenticated) {
+ $headers = array_merge($headers, $this->getHeaders());
+ }
+
+ return $this->client->call(Client::METHOD_GET, $this->keysPath() . '/' . $keyId, $headers);
+ }
+
+ /**
+ * @param array|null $queries
+ */
+ protected function listKeys(?array $queries, ?bool $total, bool $authenticated = true): mixed
+ {
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ ];
+
+ if ($authenticated) {
+ $headers = array_merge($headers, $this->getHeaders());
+ }
+
+ return $this->client->call(Client::METHOD_GET, $this->keysPath(), $headers, [
+ 'queries' => $queries,
+ 'total' => $total,
+ ]);
+ }
+
+ protected function deleteKey(string $keyId, bool $authenticated = true): mixed
+ {
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ ];
+
+ if ($authenticated) {
+ $headers = array_merge($headers, $this->getHeaders());
+ }
+
+ return $this->client->call(Client::METHOD_DELETE, $this->keysPath() . '/' . $keyId, $headers);
+ }
+
+ /**
+ * @param array $scopes
+ */
+ protected function createEphemeralKey(array $scopes, ?int $duration = null, bool $authenticated = true): mixed
+ {
+ $params = [
+ 'scopes' => $scopes,
+ ];
+
+ if ($duration !== null) {
+ $params['duration'] = $duration;
+ }
+
+ $headers = [
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ ];
+
+ if ($authenticated) {
+ $headers = array_merge($headers, $this->getHeaders());
+ }
+
+ return $this->client->call(Client::METHOD_POST, $this->keysPath() . '/ephemeral', $headers, $params);
+ }
+}
diff --git a/tests/e2e/Services/Organization/KeysConsoleClientTest.php b/tests/e2e/Services/Organization/KeysConsoleClientTest.php
new file mode 100644
index 0000000000..8af40a80c3
--- /dev/null
+++ b/tests/e2e/Services/Organization/KeysConsoleClientTest.php
@@ -0,0 +1,16 @@
+client->call(
Client::METHOD_POST,
- '/project/keys/ephemeral',
+ '/organization/projects/' . $projectId . '/keys/ephemeral',
$serverHeaders,
[
'scopes' => ['users.read'],
diff --git a/tests/e2e/Services/Organization/ProjectsBase.php b/tests/e2e/Services/Organization/ProjectsBase.php
index e5792dc1f3..2434f68190 100644
--- a/tests/e2e/Services/Organization/ProjectsBase.php
+++ b/tests/e2e/Services/Organization/ProjectsBase.php
@@ -27,7 +27,7 @@ trait ProjectsBase
$team = $this->createTeamFixture(array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
- ], $this->getHeaders()), [
+ ], $this->getConsoleHeaders()), [
'teamId' => $teamId,
'name' => 'Organization Test',
]);
@@ -40,11 +40,22 @@ trait ProjectsBase
return self::$cachedOrganization;
}
+ /**
+ * Console session headers. Admin mode is rejected for the console project.
+ */
+ protected function getConsoleHeaders(): array
+ {
+ $headers = $this->getHeaders();
+ unset($headers['x-appwrite-mode']);
+
+ return $headers;
+ }
+
protected function getOrganizationHeaders(): array
{
$organization = $this->setupOrganization();
- return array_merge($this->getHeaders(), [
+ return array_merge($this->getConsoleHeaders(), [
'x-appwrite-organization' => $organization['teamId'],
]);
}
@@ -60,7 +71,7 @@ trait ProjectsBase
$project = null;
for ($i = 0; $i < 3; $i++) {
- $project = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $project = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -91,7 +102,7 @@ trait ProjectsBase
/**
* Test for SUCCESS
*/
- $response = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -105,28 +116,25 @@ trait ProjectsBase
$this->assertEquals('Organization Project Test', $response['body']['name']);
$this->assertEquals($teamId, $response['body']['teamId']);
$this->assertEquals(PROJECT_STATUS_ACTIVE, $response['body']['status']);
- $this->assertArrayHasKey('platforms', $response['body']);
- $this->assertArrayHasKey('webhooks', $response['body']);
- $this->assertArrayHasKey('keys', $response['body']);
/**
* Test for FAILURE - missing organization header
*/
- $response = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
- ], $this->getHeaders()), [
+ ], $this->getConsoleHeaders()), [
'projectId' => ID::unique(),
'name' => 'Organization Project Test',
'region' => System::getEnv('_APP_REGION', 'default'),
]);
- $this->assertEquals(404, $response['headers']['status-code']);
+ $this->assertEquals(401, $response['headers']['status-code']);
/**
* Test for FAILURE - empty name
*/
- $response = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -143,7 +151,7 @@ trait ProjectsBase
$organization = $this->setupOrganization();
$projectId = ID::unique();
- $response = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -157,7 +165,7 @@ trait ProjectsBase
/**
* Test for FAILURE - duplicate project ID
*/
- $response = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -179,7 +187,7 @@ trait ProjectsBase
/**
* Test for SUCCESS
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects/' . $projectId, array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects/' . $projectId, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -189,14 +197,11 @@ trait ProjectsBase
$this->assertEquals($projectId, $response['body']['$id']);
$this->assertEquals('Organization Project Test', $response['body']['name']);
$this->assertEquals(PROJECT_STATUS_ACTIVE, $response['body']['status']);
- $this->assertArrayHasKey('platforms', $response['body']);
- $this->assertArrayHasKey('webhooks', $response['body']);
- $this->assertArrayHasKey('keys', $response['body']);
/**
* Test for FAILURE - project not found
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects/' . ID::unique(), array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects/' . ID::unique(), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -209,17 +214,17 @@ trait ProjectsBase
$otherTeam = $this->createTeamFixture(array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
- ], $this->getHeaders()), [
+ ], $this->getConsoleHeaders()), [
'teamId' => ID::unique(),
'name' => 'Other Organization',
]);
$this->assertContains($otherTeam['headers']['status-code'], [200]);
$otherTeamId = $otherTeam['body']['$id'] ?? $otherTeam['body']['teamId'];
- $otherProject = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $otherProject = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
- ], array_merge($this->getHeaders(), [
+ ], array_merge($this->getConsoleHeaders(), [
'x-appwrite-organization' => $otherTeamId,
])), [
'projectId' => ID::unique(),
@@ -229,7 +234,7 @@ trait ProjectsBase
$this->assertEquals(201, $otherProject['headers']['status-code']);
$otherProjectId = $otherProject['body']['$id'];
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects/' . $otherProjectId, array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects/' . $otherProjectId, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -245,7 +250,7 @@ trait ProjectsBase
/**
* Test for SUCCESS
*/
- $response = $this->client->call(Client::METHOD_PATCH, '/v1/organization/projects/' . $projectId, array_merge([
+ $response = $this->client->call(Client::METHOD_PATCH, '/organization/projects/' . $projectId, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -259,7 +264,7 @@ trait ProjectsBase
/**
* Test for FAILURE - project not found
*/
- $response = $this->client->call(Client::METHOD_PATCH, '/v1/organization/projects/' . ID::unique(), array_merge([
+ $response = $this->client->call(Client::METHOD_PATCH, '/organization/projects/' . ID::unique(), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -271,7 +276,7 @@ trait ProjectsBase
/**
* Test for FAILURE - empty name
*/
- $response = $this->client->call(Client::METHOD_PATCH, '/v1/organization/projects/' . $projectId, array_merge([
+ $response = $this->client->call(Client::METHOD_PATCH, '/organization/projects/' . $projectId, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -285,7 +290,7 @@ trait ProjectsBase
{
$organization = $this->setupOrganization();
- $project = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $project = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -300,7 +305,7 @@ trait ProjectsBase
/**
* Test for SUCCESS
*/
- $response = $this->client->call(Client::METHOD_DELETE, '/v1/organization/projects/' . $projectId, array_merge([
+ $response = $this->client->call(Client::METHOD_DELETE, '/organization/projects/' . $projectId, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -308,7 +313,7 @@ trait ProjectsBase
$this->assertEquals(204, $response['headers']['status-code']);
// Verify project is actually deleted
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects/' . $projectId, array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects/' . $projectId, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -318,7 +323,7 @@ trait ProjectsBase
/**
* Test for FAILURE - project not found (already deleted)
*/
- $response = $this->client->call(Client::METHOD_DELETE, '/v1/organization/projects/' . $projectId, array_merge([
+ $response = $this->client->call(Client::METHOD_DELETE, '/organization/projects/' . $projectId, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -332,7 +337,7 @@ trait ProjectsBase
$teamId = $organization['teamId'];
// Create a second project in the same organization
- $project2 = $this->client->call(Client::METHOD_POST, '/v1/organization/projects', array_merge([
+ $project2 = $this->client->call(Client::METHOD_POST, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -347,7 +352,7 @@ trait ProjectsBase
/**
* Test for SUCCESS - basic list
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -360,7 +365,7 @@ trait ProjectsBase
/**
* Test search queries
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders(), [
@@ -370,12 +375,12 @@ trait ProjectsBase
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertGreaterThan(0, $response['body']['total']);
$this->assertIsArray($response['body']['projects']);
- $this->assertEquals('Second Organization Project', $response['body']['projects'][0]['name']);
+ $this->assertContains('Second Organization Project', \array_column($response['body']['projects'], 'name'));
/**
* Test pagination with limit
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -390,7 +395,7 @@ trait ProjectsBase
/**
* Test pagination with offset
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -405,7 +410,7 @@ trait ProjectsBase
/**
* Test query by name
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -416,12 +421,12 @@ trait ProjectsBase
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertGreaterThanOrEqual(1, count($response['body']['projects']));
- $this->assertEquals('Second Organization Project', $response['body']['projects'][0]['name']);
+ $this->assertContains('Second Organization Project', \array_column($response['body']['projects'], 'name'));
/**
* Test cursor pagination
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()));
@@ -429,7 +434,7 @@ trait ProjectsBase
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertNotEmpty($response['body']['projects']);
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -444,7 +449,7 @@ trait ProjectsBase
/**
* Test for FAILURE - invalid cursor
*/
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
@@ -461,7 +466,7 @@ trait ProjectsBase
$data = $this->setupOrganizationProject();
$projectId = $data['projectId'];
- $response = $this->client->call(Client::METHOD_GET, '/v1/organization/projects', array_merge([
+ $response = $this->client->call(Client::METHOD_GET, '/organization/projects', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getOrganizationHeaders()), [
diff --git a/tests/e2e/Services/Project/KeysBase.php b/tests/e2e/Services/Project/KeysBase.php
index c56a055b76..da4f629267 100644
--- a/tests/e2e/Services/Project/KeysBase.php
+++ b/tests/e2e/Services/Project/KeysBase.php
@@ -2,1043 +2,82 @@
namespace Tests\E2E\Services\Project;
-use Appwrite\Tests\Async;
use Tests\E2E\Client;
-use Utopia\Database\Document;
use Utopia\Database\Helpers\ID;
-use Utopia\Database\Query;
-use Utopia\Database\Validator\Datetime as DatetimeValidator;
+/**
+ * Smoke coverage for the project-scoped keys endpoints kept for a zero-downtime transition.
+ * Full coverage lives in Tests\E2E\Services\Organization\KeysBase.
+ *
+ * TODO: Remove with /v1/project/keys once the Console, CLI and SDKs use the Organization API.
+ */
trait KeysBase
{
- use Async;
-
- // =========================================================================
- // Create key tests
- // =========================================================================
-
- public function testCreateKey(): void
+ public function testKeysLifecycle(): void
{
- $key = $this->createKey(
- ID::unique(),
- 'My API Key',
- ['users.read', 'users.write'],
- );
+ $projectHeaders = array_merge([
+ 'content-type' => 'application/json',
+ 'x-appwrite-project' => $this->getProject()['$id'],
+ ], $this->getHeaders());
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertNotEmpty($key['body']['$id']);
- $this->assertSame('My API Key', $key['body']['name']);
- $this->assertSame(['users.read', 'users.write'], $key['body']['scopes']);
- $this->assertNotEmpty($key['body']['secret']);
- $this->assertSame('', $key['body']['expire']);
- $this->assertSame('', $key['body']['accessedAt']);
- $this->assertSame([], $key['body']['sdks']);
-
- $dateValidator = new DatetimeValidator();
- $this->assertSame(true, $dateValidator->isValid($key['body']['$createdAt']));
- $this->assertSame(true, $dateValidator->isValid($key['body']['$updatedAt']));
-
- // Verify via GET
- $get = $this->getKey($key['body']['$id']);
- $this->assertSame(200, $get['headers']['status-code']);
- $this->assertSame($key['body']['$id'], $get['body']['$id']);
- $this->assertSame('My API Key', $get['body']['name']);
- $this->assertSame(['users.read', 'users.write'], $get['body']['scopes']);
-
- // Verify via LIST
- $list = $this->listKeys(null, true);
- $this->assertSame(200, $list['headers']['status-code']);
- $this->assertGreaterThanOrEqual(1, $list['body']['total']);
- $this->assertGreaterThanOrEqual(1, \count($list['body']['keys']));
-
- // Cleanup
- $this->deleteKey($key['body']['$id']);
- }
-
- public function testCreateKeyWithExpire(): void
- {
- $expire = '2030-01-01T00:00:00.000+00:00';
-
- $key = $this->createKey(
- ID::unique(),
- 'Expiring Key',
- ['users.read'],
- $expire,
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertSame($expire, $key['body']['expire']);
-
- // Verify via GET
- $get = $this->getKey($key['body']['$id']);
- $this->assertSame(200, $get['headers']['status-code']);
- $this->assertSame($expire, $get['body']['expire']);
-
- // Cleanup
- $this->deleteKey($key['body']['$id']);
- }
-
- public function testCreateKeyWithEmptyScopes(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Empty Scopes Key',
- [],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertSame([], $key['body']['scopes']);
-
- // Cleanup
- $this->deleteKey($key['body']['$id']);
- }
-
- public function testCreateKeyWithNullScopesV22BackwardCompat(): void
- {
- $headers = [
+ // Key creation is denied for key-authorized requests, so always use a console session
+ $consoleHeaders = [
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
- 'x-appwrite-response-format' => '1.9.0',
- // Key creation is denied for key-authorized requests, so always use a console session
'origin' => 'http://localhost',
'cookie' => 'a_session_console=' . $this->getRoot()['session'],
'x-appwrite-mode' => 'admin',
];
- $key = $this->client->call(Client::METHOD_POST, '/project/keys', $headers, [
+ /**
+ * Test for SUCCESS
+ */
+ $key = $this->client->call(Client::METHOD_POST, '/project/keys', $consoleHeaders, [
'keyId' => ID::unique(),
- 'name' => 'V22 Compat Key',
- 'scopes' => null,
- ]);
-
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertSame([], $key['body']['scopes']);
-
- // Cleanup
- $this->deleteKey($key['body']['$id']);
- }
-
- public function testUpdateKeyWithNullScopesV22BackwardCompat(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'V22 Update Compat Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- $headers = [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- 'x-appwrite-response-format' => '1.9.0',
- ];
- $headers = array_merge($headers, $this->getHeaders());
-
- $updated = $this->client->call(Client::METHOD_PUT, '/project/keys/' . $keyId, $headers, [
- 'name' => 'V22 Update Compat Key',
- 'scopes' => null,
- ]);
-
- $this->assertSame(200, $updated['headers']['status-code']);
- $this->assertSame([], $updated['body']['scopes']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testCreateKeyWithoutAuthentication(): void
- {
- $response = $this->createKey(
- ID::unique(),
- 'No Auth Key',
- ['users.read'],
- null,
- false
- );
-
- $this->assertSame(401, $response['headers']['status-code']);
- }
-
- public function testCreateKeyInvalidId(): void
- {
- $key = $this->createKey(
- '!invalid-id!',
- 'Invalid ID Key',
- ['users.read'],
- );
-
- $this->assertSame(400, $key['headers']['status-code']);
- }
-
- public function testCreateKeyMissingName(): void
- {
- $response = $this->createKey(
- ID::unique(),
- null,
- ['users.read'],
- );
-
- $this->assertSame(400, $response['headers']['status-code']);
- }
-
- public function testCreateKeyInvalidScope(): void
- {
- $response = $this->createKey(
- ID::unique(),
- 'Invalid Scope Key',
- ['invalid.scope'],
- );
-
- $this->assertSame(400, $response['headers']['status-code']);
- }
-
- public function testCreateKeyDuplicateId(): void
- {
- $keyId = ID::unique();
-
- $key = $this->createKey(
- $keyId,
- 'Key Dup 1',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
-
- // Attempt to create with same ID
- $duplicate = $this->createKey(
- $keyId,
- 'Key Dup 2',
- ['users.write'],
- );
-
- $this->assertSame(409, $duplicate['headers']['status-code']);
- $this->assertSame('key_already_exists', $duplicate['body']['type']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testCreateKeyCustomId(): void
- {
- $customId = 'my-custom-key-id';
-
- $key = $this->createKey(
- $customId,
- 'Custom ID Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertSame($customId, $key['body']['$id']);
-
- // Verify via GET
- $get = $this->getKey($customId);
- $this->assertSame(200, $get['headers']['status-code']);
- $this->assertSame($customId, $get['body']['$id']);
-
- // Cleanup
- $this->deleteKey($customId);
- }
-
- public function testCreateKeyRequiresSession(): void
- {
- // A request authorized with a standard API key cannot create a key
- $response = $this->client->call(Client::METHOD_POST, '/project/keys', [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- 'x-appwrite-key' => $this->getProject()['apiKey'],
- ], [
- 'keyId' => ID::unique(),
- 'name' => 'Key Made By Key',
+ 'name' => 'Legacy Key',
'scopes' => ['users.read'],
]);
- $this->assertSame(403, $response['headers']['status-code']);
- $this->assertSame('key_creation_denied', $response['body']['type']);
-
- // A request authorized with an ephemeral key cannot create a key either
- $ephemeral = $this->createEphemeralKey(['keys.read', 'keys.write'], 900);
- $this->assertSame(201, $ephemeral['headers']['status-code']);
-
- $response = $this->client->call(Client::METHOD_POST, '/project/keys', [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- 'x-appwrite-key' => $ephemeral['body']['secret'],
- ], [
- 'keyId' => ID::unique(),
- 'name' => 'Key Made By Ephemeral Key',
- 'scopes' => ['users.read'],
- ]);
-
- $this->assertSame(403, $response['headers']['status-code']);
- $this->assertSame('key_creation_denied', $response['body']['type']);
- }
-
- // =========================================================================
- // Create ephemeral key tests
- // =========================================================================
-
- public function testCreateEphemeralKey(): void
- {
- $duration = 900;
-
- $key = $this->createEphemeralKey(
- ['users.read', 'users.write'],
- $duration,
- );
-
$this->assertSame(201, $key['headers']['status-code']);
- $this->assertNotEmpty($key['body']['$id']);
- $this->assertSame('', $key['body']['name']);
- $this->assertSame(['users.read', 'users.write'], $key['body']['scopes']);
$this->assertNotEmpty($key['body']['secret']);
- $this->assertStringStartsWith(API_KEY_EPHEMERAL . '_', $key['body']['secret']);
- $this->assertSame([], $key['body']['sdks']);
- $this->assertSame('', $key['body']['accessedAt']);
-
- $dateValidator = new DatetimeValidator();
- $this->assertSame(true, $dateValidator->isValid($key['body']['$createdAt']));
- $this->assertSame(true, $dateValidator->isValid($key['body']['$updatedAt']));
- $this->assertSame(true, $dateValidator->isValid($key['body']['expire']));
-
- // Verify JWT payload
- $jwt = substr($key['body']['secret'], strlen(API_KEY_EPHEMERAL . '_'));
- $parts = explode('.', $jwt);
- $this->assertCount(3, $parts);
- $payload = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[1])), true);
- $this->assertNotEmpty($payload['projectId']);
- $this->assertSame(['users.read', 'users.write'], $payload['scopes']);
-
- $expireDt = new \DateTime($key['body']['expire']);
- $now = new \DateTime();
- $diff = $expireDt->getTimestamp() - $now->getTimestamp();
- $this->assertGreaterThanOrEqual($duration - 10, $diff);
- $this->assertLessThanOrEqual($duration + 10, $diff);
- }
-
- public function testCreateEphemeralKeyWithDuration(): void
- {
- $duration = 1800;
-
- $key = $this->createEphemeralKey(
- ['databases.read'],
- $duration,
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertSame(['databases.read'], $key['body']['scopes']);
-
- $expireDt = new \DateTime($key['body']['expire']);
- $now = new \DateTime();
- $diff = $expireDt->getTimestamp() - $now->getTimestamp();
- $this->assertGreaterThanOrEqual($duration - 10, $diff);
- $this->assertLessThanOrEqual($duration + 10, $diff);
- }
-
- public function testCreateEphemeralKeyWithEmptyScopes(): void
- {
- $key = $this->createEphemeralKey(
- [],
- 900,
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertSame([], $key['body']['scopes']);
- }
-
- public function testCreateEphemeralKeyWithoutAuthentication(): void
- {
- $response = $this->createEphemeralKey(
- ['users.read'],
- 900,
- false
- );
-
- $this->assertSame(401, $response['headers']['status-code']);
- }
-
- public function testCreateEphemeralKeyMissingDuration(): void
- {
- $response = $this->createEphemeralKey(
- ['users.read'],
- );
-
- $this->assertSame(400, $response['headers']['status-code']);
- }
-
- public function testCreateEphemeralKeyInvalidScope(): void
- {
- $response = $this->createEphemeralKey(
- ['invalid.scope'],
- 900,
- );
-
- $this->assertSame(400, $response['headers']['status-code']);
- }
-
- public function testCreateEphemeralKeyInvalidDuration(): void
- {
- $response = $this->createEphemeralKey(
- ['users.read'],
- 0,
- );
-
- $this->assertSame(400, $response['headers']['status-code']);
-
- $response = $this->createEphemeralKey(
- ['users.read'],
- 3601,
- );
-
- $this->assertSame(400, $response['headers']['status-code']);
- }
-
- // =========================================================================
- // Update key tests
- // =========================================================================
-
- public function testUpdateKey(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Original Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
$keyId = $key['body']['$id'];
- // Update name, scopes, and expire
- $expire = '2031-06-15T12:00:00.000+00:00';
- $updated = $this->updateKey($keyId, 'Updated Key', ['users.write', 'databases.read'], $expire);
-
- $this->assertSame(200, $updated['headers']['status-code']);
- $this->assertSame($keyId, $updated['body']['$id']);
- $this->assertSame('Updated Key', $updated['body']['name']);
- $this->assertSame(['users.write', 'databases.read'], $updated['body']['scopes']);
- $this->assertSame($expire, $updated['body']['expire']);
-
- // Verify update persisted via GET
- $get = $this->getKey($keyId);
- $this->assertSame(200, $get['headers']['status-code']);
- $this->assertSame('Updated Key', $get['body']['name']);
- $this->assertSame(['users.write', 'databases.read'], $get['body']['scopes']);
- $this->assertSame($expire, $get['body']['expire']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testUpdateKeyName(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Name Before',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- $updated = $this->updateKey($keyId, 'Name After', ['users.read']);
-
- $this->assertSame(200, $updated['headers']['status-code']);
- $this->assertSame('Name After', $updated['body']['name']);
- $this->assertSame(['users.read'], $updated['body']['scopes']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testUpdateKeyScopes(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Scopes Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- $updated = $this->updateKey($keyId, 'Scopes Key', ['databases.read', 'databases.write']);
-
- $this->assertSame(200, $updated['headers']['status-code']);
- $this->assertSame(['databases.read', 'databases.write'], $updated['body']['scopes']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testUpdateKeySetExpire(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'No Expire Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $this->assertSame('', $key['body']['expire']);
- $keyId = $key['body']['$id'];
-
- $expire = '2032-12-31T23:59:59.000+00:00';
- $updated = $this->updateKey($keyId, 'No Expire Key', ['users.read'], $expire);
-
- $this->assertSame(200, $updated['headers']['status-code']);
- $this->assertSame($expire, $updated['body']['expire']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testUpdateKeyRemoveExpire(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Expire Key',
- ['users.read'],
- '2030-01-01T00:00:00.000+00:00',
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- // Remove expire by setting to null
- $updated = $this->updateKey($keyId, 'Expire Key', ['users.read'], null);
-
- $this->assertSame(200, $updated['headers']['status-code']);
- $this->assertSame('', $updated['body']['expire']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testUpdateKeyWithoutAuthentication(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Auth Update Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- // Attempt update without authentication
- $response = $this->updateKey($keyId, 'Updated Name', ['users.read'], null, false);
-
- $this->assertSame(401, $response['headers']['status-code']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testUpdateKeyNotFound(): void
- {
- $updated = $this->updateKey('non-existent-id', 'New Name', ['users.read']);
-
- $this->assertSame(404, $updated['headers']['status-code']);
- $this->assertSame('key_not_found', $updated['body']['type']);
- }
-
- public function testUpdateKeyInvalidScope(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Invalid Scope Update',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- $updated = $this->updateKey($keyId, 'Invalid Scope Update', ['invalid.scope']);
-
- $this->assertSame(400, $updated['headers']['status-code']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- // =========================================================================
- // Get key tests
- // =========================================================================
-
- public function testGetKey(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Get Test Key',
- ['users.read', 'databases.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- $get = $this->getKey($keyId);
+ $get = $this->client->call(Client::METHOD_GET, '/project/keys/' . $keyId, $projectHeaders);
$this->assertSame(200, $get['headers']['status-code']);
- $this->assertSame($keyId, $get['body']['$id']);
- $this->assertSame('Get Test Key', $get['body']['name']);
- $this->assertSame(['users.read', 'databases.read'], $get['body']['scopes']);
- $this->assertNotEmpty($get['body']['secret']);
- $this->assertSame('', $get['body']['expire']);
- $this->assertSame('', $get['body']['accessedAt']);
- $this->assertSame([], $get['body']['sdks']);
+ $this->assertSame('Legacy Key', $get['body']['name']);
- $dateValidator = new DatetimeValidator();
- $this->assertSame(true, $dateValidator->isValid($get['body']['$createdAt']));
- $this->assertSame(true, $dateValidator->isValid($get['body']['$updatedAt']));
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testGetKeyNotFound(): void
- {
- $get = $this->getKey('non-existent-id');
-
- $this->assertSame(404, $get['headers']['status-code']);
- $this->assertSame('key_not_found', $get['body']['type']);
- }
-
- public function testGetKeyWithoutAuthentication(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Auth Get Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- // Attempt GET without authentication
- $response = $this->getKey($keyId, false);
-
- $this->assertSame(401, $response['headers']['status-code']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- // =========================================================================
- // List keys tests
- // =========================================================================
-
- public function testListKeys(): void
- {
- // Create multiple keys
- $key1 = $this->createKey(
- ID::unique(),
- 'List Key Alpha',
- ['users.read'],
- );
- $this->assertSame(201, $key1['headers']['status-code']);
-
- $key2 = $this->createKey(
- ID::unique(),
- 'List Key Beta',
- ['databases.read'],
- );
- $this->assertSame(201, $key2['headers']['status-code']);
-
- $key3 = $this->createKey(
- ID::unique(),
- 'List Key Gamma',
- ['users.write'],
- );
- $this->assertSame(201, $key3['headers']['status-code']);
-
- // List all
- $list = $this->listKeys(null, true);
+ $list = $this->client->call(Client::METHOD_GET, '/project/keys', $projectHeaders);
$this->assertSame(200, $list['headers']['status-code']);
- $this->assertGreaterThanOrEqual(3, $list['body']['total']);
- $this->assertGreaterThanOrEqual(3, \count($list['body']['keys']));
- $this->assertIsArray($list['body']['keys']);
+ $this->assertContains($keyId, \array_column($list['body']['keys'], '$id'));
- // Verify structure of returned keys
- foreach ($list['body']['keys'] as $key) {
- $this->assertArrayHasKey('$id', $key);
- $this->assertArrayHasKey('$createdAt', $key);
- $this->assertArrayHasKey('$updatedAt', $key);
- $this->assertArrayHasKey('name', $key);
- $this->assertArrayHasKey('scopes', $key);
- $this->assertArrayHasKey('secret', $key);
- $this->assertArrayHasKey('expire', $key);
- $this->assertArrayHasKey('accessedAt', $key);
- $this->assertArrayHasKey('sdks', $key);
- }
-
- // Cleanup
- $this->deleteKey($key1['body']['$id']);
- $this->deleteKey($key2['body']['$id']);
- $this->deleteKey($key3['body']['$id']);
- }
-
- public function testListKeysWithLimit(): void
- {
- $key1 = $this->createKey(
- ID::unique(),
- 'Limit Key 1',
- ['users.read'],
- );
- $this->assertSame(201, $key1['headers']['status-code']);
-
- $key2 = $this->createKey(
- ID::unique(),
- 'Limit Key 2',
- ['users.write'],
- );
- $this->assertSame(201, $key2['headers']['status-code']);
-
- // List with limit 1
- $list = $this->listKeys([
- Query::limit(1)->toString(),
- ], true);
-
- $this->assertSame(200, $list['headers']['status-code']);
- $this->assertCount(1, $list['body']['keys']);
- $this->assertGreaterThanOrEqual(2, $list['body']['total']);
-
- // Cleanup
- $this->deleteKey($key1['body']['$id']);
- $this->deleteKey($key2['body']['$id']);
- }
-
- public function testListKeysWithoutTotal(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'No Total Key',
- ['users.read'],
- );
- $this->assertSame(201, $key['headers']['status-code']);
-
- // List with total=false
- $list = $this->listKeys(null, false);
-
- $this->assertSame(200, $list['headers']['status-code']);
- $this->assertSame(0, $list['body']['total']);
- $this->assertGreaterThanOrEqual(1, \count($list['body']['keys']));
-
- // Cleanup
- $this->deleteKey($key['body']['$id']);
- }
-
- public function testListKeysCursorPagination(): void
- {
- $key1 = $this->createKey(
- ID::unique(),
- 'Cursor Key 1',
- ['users.read'],
- );
- $this->assertSame(201, $key1['headers']['status-code']);
-
- $key2 = $this->createKey(
- ID::unique(),
- 'Cursor Key 2',
- ['users.write'],
- );
- $this->assertSame(201, $key2['headers']['status-code']);
-
- // Get first page with limit 1
- $page1 = $this->listKeys([
- Query::limit(1)->toString(),
- ], true);
-
- $this->assertSame(200, $page1['headers']['status-code']);
- $this->assertCount(1, $page1['body']['keys']);
- $cursorId = $page1['body']['keys'][0]['$id'];
-
- // Get next page using cursor
- $page2 = $this->listKeys([
- Query::limit(1)->toString(),
- Query::cursorAfter(new Document(['$id' => $cursorId]))->toString(),
- ], true);
-
- $this->assertSame(200, $page2['headers']['status-code']);
- $this->assertCount(1, $page2['body']['keys']);
- $this->assertNotEquals($cursorId, $page2['body']['keys'][0]['$id']);
-
- // Cleanup
- $this->deleteKey($key1['body']['$id']);
- $this->deleteKey($key2['body']['$id']);
- }
-
- public function testListKeysWithoutAuthentication(): void
- {
- $response = $this->listKeys(null, null, false);
-
- $this->assertSame(401, $response['headers']['status-code']);
- }
-
- public function testListKeysInvalidCursor(): void
- {
- $list = $this->listKeys([
- Query::cursorAfter(new Document(['$id' => 'non-existent-id']))->toString(),
- ], true);
-
- $this->assertSame(400, $list['headers']['status-code']);
- }
-
- // =========================================================================
- // Delete key tests
- // =========================================================================
-
- public function testDeleteKey(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Delete Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- // Verify it exists
- $get = $this->getKey($keyId);
- $this->assertSame(200, $get['headers']['status-code']);
-
- // Delete
- $delete = $this->deleteKey($keyId);
- $this->assertSame(204, $delete['headers']['status-code']);
- $this->assertEmpty($delete['body']);
-
- // Verify it no longer exists
- $get = $this->getKey($keyId);
- $this->assertSame(404, $get['headers']['status-code']);
- $this->assertSame('key_not_found', $get['body']['type']);
- }
-
- public function testDeleteKeyNotFound(): void
- {
- $delete = $this->deleteKey('non-existent-id');
-
- $this->assertSame(404, $delete['headers']['status-code']);
- $this->assertSame('key_not_found', $delete['body']['type']);
- }
-
- public function testDeleteKeyWithoutAuthentication(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Delete Auth Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- // Attempt DELETE without authentication
- $response = $this->deleteKey($keyId, false);
-
- $this->assertSame(401, $response['headers']['status-code']);
-
- // Verify it still exists
- $get = $this->getKey($keyId);
- $this->assertSame(200, $get['headers']['status-code']);
-
- // Cleanup
- $this->deleteKey($keyId);
- }
-
- public function testDeleteKeyRemovedFromList(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Delete List Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- // Get list count before delete
- $listBefore = $this->listKeys(null, true);
- $this->assertSame(200, $listBefore['headers']['status-code']);
- $countBefore = $listBefore['body']['total'];
-
- // Delete
- $delete = $this->deleteKey($keyId);
- $this->assertSame(204, $delete['headers']['status-code']);
-
- // Get list count after delete
- $listAfter = $this->listKeys(null, true);
- $this->assertSame(200, $listAfter['headers']['status-code']);
- $this->assertSame($countBefore - 1, $listAfter['body']['total']);
-
- // Verify the deleted key is not in the list
- $ids = \array_column($listAfter['body']['keys'], '$id');
- $this->assertNotContains($keyId, $ids);
- }
-
- public function testDeleteKeyDoubleDelete(): void
- {
- $key = $this->createKey(
- ID::unique(),
- 'Double Delete Key',
- ['users.read'],
- );
-
- $this->assertSame(201, $key['headers']['status-code']);
- $keyId = $key['body']['$id'];
-
- // First delete succeeds
- $delete = $this->deleteKey($keyId);
- $this->assertSame(204, $delete['headers']['status-code']);
-
- // Second delete returns 404
- $delete = $this->deleteKey($keyId);
- $this->assertSame(404, $delete['headers']['status-code']);
- $this->assertSame('key_not_found', $delete['body']['type']);
- }
-
- // =========================================================================
- // Helpers
- // =========================================================================
-
- /**
- * @param array|null $scopes
- */
- protected function createKey(string $keyId, ?string $name, ?array $scopes = null, ?string $expire = null, bool $authenticated = true): mixed
- {
- $params = [
- 'keyId' => $keyId,
- 'scopes' => $scopes,
- ];
-
- if ($name !== null) {
- $params['name'] = $name;
- }
-
- if ($expire !== null) {
- $params['expire'] = $expire;
- }
-
- $headers = [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- ];
-
- if ($authenticated) {
- // Key creation is denied for key-authorized requests, so always use a console session
- $headers = array_merge($headers, [
- 'origin' => 'http://localhost',
- 'cookie' => 'a_session_console=' . $this->getRoot()['session'],
- 'x-appwrite-mode' => 'admin',
- ]);
- }
-
- return $this->client->call(Client::METHOD_POST, '/project/keys', $headers, $params);
- }
-
- /**
- * @param array|null $scopes
- */
- protected function updateKey(string $keyId, ?string $name = null, ?array $scopes = null, ?string $expire = null, bool $authenticated = true): mixed
- {
- $params = [];
-
- if ($name !== null) {
- $params['name'] = $name;
- }
-
- if ($scopes !== null) {
- $params['scopes'] = $scopes;
- }
-
- if ($expire !== null) {
- $params['expire'] = $expire;
- }
-
- $headers = [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- ];
-
- if ($authenticated) {
- $headers = array_merge($headers, $this->getHeaders());
- }
-
- return $this->client->call(Client::METHOD_PUT, '/project/keys/' . $keyId, $headers, $params);
- }
-
- protected function getKey(string $keyId, bool $authenticated = true): mixed
- {
- $headers = [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- ];
-
- if ($authenticated) {
- $headers = array_merge($headers, $this->getHeaders());
- }
-
- return $this->client->call(Client::METHOD_GET, '/project/keys/' . $keyId, $headers);
- }
-
- /**
- * @param array|null $queries
- */
- protected function listKeys(?array $queries, ?bool $total, bool $authenticated = true): mixed
- {
- $headers = [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- ];
-
- if ($authenticated) {
- $headers = array_merge($headers, $this->getHeaders());
- }
-
- return $this->client->call(Client::METHOD_GET, '/project/keys', $headers, [
- 'queries' => $queries,
- 'total' => $total,
+ $updated = $this->client->call(Client::METHOD_PUT, '/project/keys/' . $keyId, $projectHeaders, [
+ 'name' => 'Legacy Key Updated',
+ 'scopes' => ['users.read', 'users.write'],
]);
- }
- protected function deleteKey(string $keyId, bool $authenticated = true): mixed
- {
- $headers = [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- ];
+ $this->assertSame(200, $updated['headers']['status-code']);
+ $this->assertSame(['users.read', 'users.write'], $updated['body']['scopes']);
- if ($authenticated) {
- $headers = array_merge($headers, $this->getHeaders());
- }
+ $ephemeral = $this->client->call(Client::METHOD_POST, '/project/keys/ephemeral', $projectHeaders, [
+ 'scopes' => ['users.read'],
+ 'duration' => 900,
+ ]);
- return $this->client->call(Client::METHOD_DELETE, '/project/keys/' . $keyId, $headers);
- }
+ $this->assertSame(201, $ephemeral['headers']['status-code']);
+ $this->assertStringStartsWith(API_KEY_EPHEMERAL . '_', $ephemeral['body']['secret']);
- /**
- * @param array $scopes
- */
- protected function createEphemeralKey(array $scopes, ?int $duration = null, bool $authenticated = true): mixed
- {
- $params = [
- 'scopes' => $scopes,
- ];
+ $delete = $this->client->call(Client::METHOD_DELETE, '/project/keys/' . $keyId, $projectHeaders);
- if ($duration !== null) {
- $params['duration'] = $duration;
- }
+ $this->assertSame(204, $delete['headers']['status-code']);
- $headers = [
- 'content-type' => 'application/json',
- 'x-appwrite-project' => $this->getProject()['$id'],
- ];
+ /**
+ * Test for FAILURE
+ */
+ $get = $this->client->call(Client::METHOD_GET, '/project/keys/' . $keyId, $projectHeaders);
- if ($authenticated) {
- $headers = array_merge($headers, $this->getHeaders());
- }
-
- return $this->client->call(Client::METHOD_POST, '/project/keys/ephemeral', $headers, $params);
+ $this->assertSame(404, $get['headers']['status-code']);
+ $this->assertSame('key_not_found', $get['body']['type']);
}
}