diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..479e130 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,31 @@ +name: Tests + +on: + push: + branches: + - main + pull_request: + +jobs: + tests: + name: Playground against a stub Appwrite + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.5' + extensions: curl, json + tools: composer:v2 + coverage: none + + - name: Install dependencies + run: composer install --no-interaction --no-progress + + - name: Lint + run: find . -path ./vendor -prune -o -name '*.php' -print0 | xargs -0 -n1 php -l + + - name: Run the tests + run: composer test diff --git a/Dockerfile b/Dockerfile index 700aa6d..4b6b96e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,16 +1,22 @@ -FROM composer AS composer +# appwrite/appwrite 32.x needs PHP 8.5, so both stages run on it. The composer +# image is not used as a base for the same reason: it ships its own PHP. +FROM php:8.5-cli-alpine AS vendor + +COPY --from=composer/composer:2-bin /composer /usr/local/bin/composer + +WORKDIR /app COPY composer.json composer.json -COPY composer.lock composer.lock RUN composer install --no-dev --no-interaction --no-progress --no-scripts --optimize-autoloader -FROM php:8.1.11-alpine3.16 +FROM php:8.5-cli-alpine -COPY --from=composer /app/vendor /app/vendor +COPY --from=vendor /app/vendor /app/vendor COPY global.inc.php /app/global.inc.php COPY playground.php /app/playground.php COPY test.txt /app/test.txt +COPY resources /app/resources WORKDIR /app -CMD php playground.php +CMD ["php", "playground.php"] diff --git a/README.md b/README.md index 4bfdaf5..bb017cb 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Appwrite playground is a simple way to explore the Appwrite API & Appwrite PHP S This playground doesn't include any PHP best practices but rather intended to show some of the most simple examples and use cases of using the Appwrite API in your PHP application and server. ## System Requirements -* A system with PHP installed. +* A system with PHP 8.5 or later installed — that is what `appwrite/appwrite` 32.x requires. * You have readily available Appwrite running instance (localhost in most cases). * Create a project in Appwrite instance using console. * Generate a secret key in the Appwrite instance using console. @@ -25,13 +25,48 @@ This playground doesn't include any PHP best practices but rather intended to sh 6. You will see the JSON response in the console. ### API Covered in Playground. -* Create Collection -* List Collection -* Add Document -* List Documents +* Create Table +* List Tables +* Add Row * Upload File +* List Files * Create User -* List User +* List Users +* Mark a user verified +* Confirm an email verification code +* Create, deploy and execute a Function + +Tables, rows and columns are what Appwrite 1.8 renamed collections, documents +and attributes to. The playground uses the `TablesDB` service; the `Databases` +service still answers to the old names but is deprecated. + +### Verifying a user from a server + +Two calls can end up with a verified user, and they are not interchangeable: + +* `markUserVerified()` uses `users->updateEmailVerification()`. It needs + `users.write`, takes no code, and is the right call when the server itself is + the one deciding a user is verified. +* `confirmEmailVerification()` replays the six digit code Appwrite sent the + user. Appwrite counts every attempt against that route — including attempts + made with an API key — at 10 per user per hour, so a server that retries after + a rejected code spends the budget and then gets + `429 general_rate_limit_exceeded` for the rest of the hour, the user's own + correct code included. Treat a rejected code as final and issue a fresh one. + +Set `VERIFICATION_USER_ID` and `VERIFICATION_SECRET` in `global.inc.php` to run +`confirmEmailVerification()`; it is skipped while they are empty. + +### Tests + +`composer test` runs the playground against a stub Appwrite served by PHP's +built-in web server, so it needs no running instance: + +* `tests/smoke.php` — every playground call succeeds and hits the endpoint it + means to. +* `tests/verification.php` — the verification confirmation routes count every + caller, and the playground reports a rate limited confirmation instead of + failing the run. ## Contributing diff --git a/composer.json b/composer.json index 060e8c4..0505c90 100644 --- a/composer.json +++ b/composer.json @@ -23,14 +23,21 @@ } ], "require": { - "php": ">=8.0", + "php": ">=8.5", "ext-curl": "*", - "appwrite/appwrite": "^12.0.0" + "ext-json": "*", + "appwrite/appwrite": "^32.2.0" }, "config": { "optimize-autoloader": true, "preferred-install": "dist" }, + "scripts": { + "test": [ + "@php tests/smoke.php", + "@php tests/verification.php" + ] + }, "support": { "email": "team@appwrite.io", "issues": "https://github.com/appwrite/playground-for-php/issues", diff --git a/global.inc.php b/global.inc.php index ec4a717..8c3cda9 100644 --- a/global.inc.php +++ b/global.inc.php @@ -13,6 +13,18 @@ \define('API_KEY', ''); } +// A user id and the verification code that user received, used by +// `confirmEmailVerification()` in `playground.php`. Both empty skips that call: +// Appwrite counts every attempt against the route — an API key included — at 10 +// per user per hour, so there is nothing to be gained from guessing a code. +if (!\defined('VERIFICATION_USER_ID')) { + \define('VERIFICATION_USER_ID', ''); +} + +if (!\defined('VERIFICATION_SECRET')) { + \define('VERIFICATION_SECRET', ''); +} + // Helper functions /** diff --git a/playground.php b/playground.php index c1e7283..78276a8 100644 --- a/playground.php +++ b/playground.php @@ -1,6 +1,7 @@ setJWT('jwt') // Use this to authenticate with JWT generated from client ->setKey(API_KEY); -$collectionId = ""; $databaseId = ""; +$tableId = ""; $bucketId = ""; +$fileId = ""; +$userId = ""; +$functionId = ""; -$databases = new Databases($client); +$tablesDB = new TablesDB($client); $storage = new Storage($client); $functions = new Functions($client); $users = new Users($client); @@ -34,55 +38,61 @@ * Covered API methods * - createDatabase * - deleteDatabase - * - createCollection - * - deleteCollection - * - listCollection - * - addDoc + * - createTable + * - deleteTable + * - listTables + * - addRow * - uploadFile * - listFiles * - deleteFile * - createUser * - listUser + * - markUserVerified + * - confirmEmailVerification * - getAccount */ /** * Create a new Database. * - * @see https://appwrite.io/docs/server/databases?sdk=php#databasesCreate + * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#create * @throws Exception */ function createDatabase(): array { - global $databases, $databaseId; + global $tablesDB, $databaseId; - $response = $databases->create( + $response = $tablesDB->create( databaseId: ID::unique(), name: "Test Database" ); - $databaseId = $response['$id']; + $databaseId = $response->id; return [ 'call' => 'api.createDatabase', - 'response' => $response, + 'response' => $response->toArray(), ]; } /** -* Create a new Collection. -* -* @see https://appwrite.io/docs/server/databases?sdk=php#databasesCreateCollection -* @throws Exception -*/ -function createCollection(): array + * Create a new Table. + * + * Collections, documents and attributes are the pre-1.8 names for tables, rows + * and columns. The `Databases` service still answers to the old names, but it + * is deprecated — new code should use `TablesDB`. + * + * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#createTable + * @throws Exception + */ +function createTable(): array { - global $databases, $databaseId, $collectionId; + global $tablesDB, $databaseId, $tableId; - $response = $databases->createCollection( + $response = $tablesDB->createTable( databaseId: $databaseId, - collectionId: ID::unique(), - name: 'collection', + tableId: ID::unique(), + name: 'table', permissions: [ Permission::read(Role::any()), Permission::create(Role::users()), @@ -91,18 +101,18 @@ function createCollection(): array ] ); - $collectionId = $response['$id']; + $tableId = $response->id; - $response1 = $databases->createStringAttribute( + $tablesDB->createStringColumn( $databaseId, - $collectionId, + $tableId, key: 'name', size: 255, required: true, ); - $response2 = $databases->createIntegerAttribute( + $tablesDB->createIntegerColumn( $databaseId, - $collectionId, + $tableId, key: 'release_year', required: true, min: 0, @@ -110,46 +120,47 @@ function createCollection(): array ); return [ - 'call' => 'api.createCollection', - 'response' => $response, + 'call' => 'api.createTable', + 'response' => $response->toArray(), ]; } /** - * Get a list of all the user collections. - * On admin mode, this endpoint will return a list of all of the project collections. + * Get a list of all the user tables. + * On admin mode, this endpoint will return a list of all of the project tables. * - * @see https://appwrite.io/docs/server/databases?sdk=php#databasesListCollections + * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#listTables * @return array * @throws Exception */ -function listCollections(): array +function listTables(): array { - global $databases, $databaseId; + global $tablesDB, $databaseId; - $response = $databases->listCollections($databaseId); + $response = $tablesDB->listTables($databaseId); return [ - 'call' => 'api.listCollections', - 'response' => $response, + 'call' => 'api.listTables', + 'response' => $response->toArray(), ]; } /** - * Create a new Document. - * Before using this route, you should create a new collection resource + * Create a new Row. + * Before using this route, you should create a new table resource * - * @see https://appwrite.io/docs/server/databases?sdk=php#databasesCreateDocument + * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#createRow * @return array * @throws Exception */ -function addDoc(): array +function addRow(): array { - global $databases, $databaseId, $collectionId; - $response = $databases->createDocument( + global $tablesDB, $databaseId, $tableId; + + $response = $tablesDB->createRow( $databaseId, - $collectionId, - documentId: ID::unique(), + $tableId, + rowId: ID::unique(), data: [ 'name' => 'Spider Man', 'release_year' => 1920, @@ -162,27 +173,27 @@ function addDoc(): array ); return [ - 'call' => 'api.addDoc', - 'response' => $response, + 'call' => 'api.addRow', + 'response' => $response->toArray(), ]; } /** - * Delete collection - * Delete a collection by it's unique id. + * Delete table + * Delete a table by it's unique id. * - * @see https://appwrite.io/docs/server/databases?sdk=php#databasesDeleteCollection + * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#deleteTable * @return array * @throws Exception */ -function deleteCollection(): array +function deleteTable(): array { - global $databases, $databaseId, $collectionId; + global $tablesDB, $databaseId, $tableId; - $response = $databases->deleteCollection($databaseId, $collectionId); + $response = $tablesDB->deleteTable($databaseId, $tableId); return [ - 'call' => 'api.deleteCollection', + 'call' => 'api.deleteTable', 'response' => $response, ]; } @@ -191,15 +202,15 @@ function deleteCollection(): array * Delete Database * Delete a database by it's unique id. * - * @see https://appwrite.io/docs/server/databases?sdk=php#databasesDelete + * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#delete * @return array * @throws Exception */ function deleteDatabase(): array { - global $databases, $databaseId; + global $tablesDB, $databaseId; - $response = $databases->delete($databaseId); + $response = $tablesDB->delete($databaseId); return [ 'call' => 'api.deleteDatabase', @@ -210,7 +221,7 @@ function deleteDatabase(): array /** * Create a bucket * - * @see https://appwrite.io/docs/server/storage?sdk=php#storageCreateBucket + * @see https://appwrite.io/docs/references/cloud/server-php/storage#createBucket * @return array * @throws Exception */ @@ -230,11 +241,11 @@ function createBucket(): array fileSecurity: true, ); - $bucketId = $response['$id']; + $bucketId = $response->id; return [ 'call' => 'api.createBucket', - 'response' => $response, + 'response' => $response->toArray(), ]; } @@ -243,7 +254,7 @@ function createBucket(): array * The user who creates the file will automatically be assigned to read and write * access unless he has passed custom values for read and write arguments. * - * @see https://appwrite.io/docs/client/storage?sdk=php#storageCreateFile + * @see https://appwrite.io/docs/references/cloud/server-php/storage#createFile * @return array * @throws Exception */ @@ -260,11 +271,11 @@ function createFile(): array ] ); - $fileId = $response['$id']; + $fileId = $response->id; return [ 'call' => 'api.createFile', - 'response' => $response, + 'response' => $response->toArray(), ]; } @@ -273,7 +284,7 @@ function createFile(): array * You can use the query params to filter your results. On admin mode, * this endpoint will return a list of all of the project files. * - * @see https://appwrite.io/docs/client/storage?sdk=php#storageListFiles + * @see https://appwrite.io/docs/references/cloud/server-php/storage#listFiles * @return array * @throws Exception */ @@ -285,7 +296,7 @@ function listFiles(): array return [ 'call' => 'api.listFiles', - 'response' => $response, + 'response' => $response->toArray(), ]; } @@ -293,7 +304,7 @@ function listFiles(): array * Delete a file by its unique ID. * Only users with write permissions have access to delete this resource. * - * @see https://appwrite.io/docs/client/storage?sdk=php#storageDeleteFile + * @see https://appwrite.io/docs/references/cloud/server-php/storage#deleteFile * @return array * @throws Exception */ @@ -313,7 +324,7 @@ function deleteFile(): array * Delete a bucket by its unique ID. * Only users with write permissions have access to delete this resource. * - * @see https://appwrite.io/docs/server/storage?sdk=php#storageDeleteBucket + * @see https://appwrite.io/docs/references/cloud/server-php/storage#deleteBucket * @return array * @throws Exception */ @@ -332,13 +343,13 @@ function deleteBucket(): array /** * Create a new user. * - * @see https://appwrite.io/docs/server/users?sdk=php#usersCreate + * @see https://appwrite.io/docs/references/cloud/server-php/users#create * @return array * @throws Exception */ function createUser(): array { - global $users; + global $users, $userId; $suffix = \time(); @@ -349,16 +360,18 @@ function createUser(): array name: "Example {$suffix}" ); + $userId = $response->id; + return [ 'call' => 'api.createUser', - 'response' => $response, + 'response' => $response->toArray(), ]; } /** * Get a list of all the project users. * - * @see https://appwrite.io/docs/server/users?sdk=php#usersList + * @see https://appwrite.io/docs/references/cloud/server-php/users#list * @throws Exception */ function listUsers(): array @@ -369,14 +382,87 @@ function listUsers(): array return [ 'call' => 'api.listUsers', - 'response' => $response, + 'response' => $response->toArray(), + ]; +} + +/** + * Mark a user's email as verified from the server. + * + * This is the server side way to verify an email: it needs `users.write`, takes + * no code, and is not rate limited per user. Prefer it over replaying a code + * through `confirmEmailVerification()` with an API key. + * + * @see https://appwrite.io/docs/references/cloud/server-php/users#updateEmailVerification + * @throws Exception + */ +function markUserVerified(): array +{ + global $users, $userId; + + $response = $users->updateEmailVerification($userId, true); + + return [ + 'call' => 'api.markUserVerified', + 'response' => $response->toArray(), + ]; +} + +/** + * Confirm the six digit code Appwrite emailed to a user. + * + * The code belongs to the user, so this call needs the `userId` it was issued + * for and the `secret` the user received — set `VERIFICATION_USER_ID` and + * `VERIFICATION_SECRET` in `global.inc.php` to run it. + * + * Appwrite counts every attempt against this route, including attempts made + * with an API key, at 10 per user per hour. One confirmation per code is well + * inside that, but a server that retries after a rejected code will spend the + * budget and then get `429 general_rate_limit_exceeded` for the rest of the + * hour — including for the user's own, correct code. So treat a rejected code + * as final, ask for a fresh one with `createEmailVerificationOTP()`, and use + * `markUserVerified()` when the server itself is the one deciding. + * + * @see https://appwrite.io/docs/references/cloud/server-php/account#updateEmailVerificationOTP + * @throws Exception + */ +function confirmEmailVerification(): array +{ + global $account; + + if (VERIFICATION_USER_ID === '' || VERIFICATION_SECRET === '') { + return [ + 'call' => 'api.confirmEmailVerification', + 'response' => 'Skipped: set VERIFICATION_USER_ID and VERIFICATION_SECRET to run this call.', + ]; + } + + try { + $response = $account->updateEmailVerificationOTP( + userId: VERIFICATION_USER_ID, + secret: VERIFICATION_SECRET + ); + } catch (AppwriteException $e) { + if ($e->getCode() === 429) { + return [ + 'call' => 'api.confirmEmailVerification', + 'response' => 'Rate limited: this user has spent its 10 confirmation attempts for the hour.', + ]; + } + + throw $e; + } + + return [ + 'call' => 'api.confirmEmailVerification', + 'response' => $response->toArray(), ]; } /** * Get an account of authenticated user. Works only with JWT * - * @see https://appwrite.io/docs/server/account?sdk=php#accountGet + * @see https://appwrite.io/docs/references/cloud/server-php/account#get * @throws Exception */ function getAccount(): array @@ -387,14 +473,14 @@ function getAccount(): array return [ 'call' => 'api.getAccount', - 'response' => $response, + 'response' => $response->toArray(), ]; } /** * Create a function * - * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreate + * @see https://appwrite.io/docs/references/cloud/server-php/functions#create * @throws Exception */ function createFunction(): array @@ -408,18 +494,18 @@ functionId: ID::unique(), execute: [Role::any()], ); - $functionId = $response['$id']; + $functionId = $response->id; return [ 'call' => 'api.createFunction', - 'response' => $response, + 'response' => $response->toArray(), ]; } /** * Create a deployment - * - * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreateDeployment + * + * @see https://appwrite.io/docs/references/cloud/server-php/functions#createDeployment * @throws Exception */ function createDeployment(): array @@ -439,14 +525,14 @@ functionId: $functionId, return [ 'call' => 'api.createDeployment', - 'response' => $response, + 'response' => $response->toArray(), ]; } /** * Create sync execution - * - * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreateExecution + * + * @see https://appwrite.io/docs/references/cloud/server-php/functions#createExecution * @throws Exception */ function createSyncExecution(): array @@ -464,14 +550,14 @@ functionId: $functionId, return [ 'call' => 'api.createExecution', - 'response' => $response, + 'response' => $response->toArray(), ]; } /** * Create async execution - * - * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreateExecution + * + * @see https://appwrite.io/docs/references/cloud/server-php/functions#createExecution * @throws Exception */ function createAsyncExecution(): array @@ -490,18 +576,18 @@ functionId: $functionId, // wait for 2 seconds to ensure execution is finished sleep(2); - $asyncResponse = $functions->getExecution($functionId, $response['$id']); + $asyncResponse = $functions->getExecution($functionId, $response->id); return [ 'call' => 'api.createExecution', - 'response' => $asyncResponse, + 'response' => $asyncResponse->toArray(), ]; } /** * List functions * - * @see https://appwrite.io/docs/server/functions?sdk=php#functionsList + * @see https://appwrite.io/docs/references/cloud/server-php/functions#list * @throws Exception */ function listFunctions(): array @@ -512,14 +598,14 @@ function listFunctions(): array return [ 'call' => 'api.listFunctions', - 'response' => $response, + 'response' => $response->toArray(), ]; } /** * Delete a function * - * @see https://appwrite.io/docs/server/functions?sdk=php#functionsDelete + * @see https://appwrite.io/docs/references/cloud/server-php/functions#delete * @throws Exception */ function deleteFunction(): array @@ -541,10 +627,10 @@ function deleteFunction(): array $ret = []; $methods = [ 'createDatabase', - 'createCollection', - 'listCollections', - 'addDoc', - 'deleteCollection', + 'createTable', + 'listTables', + 'addRow', + 'deleteTable', 'deleteDatabase', 'createBucket', 'createFile', @@ -553,6 +639,8 @@ function deleteFunction(): array 'deleteBucket', 'createUser', 'listUsers', + 'markUserVerified', + 'confirmEmailVerification', 'createFunction', 'createDeployment', 'createSyncExecution', diff --git a/tests/assertions.php b/tests/assertions.php new file mode 100644 index 0000000..f587ef3 --- /dev/null +++ b/tests/assertions.php @@ -0,0 +1,96 @@ + $failures */ +$failures = []; + +/** + * Record a failure unless `$ok` holds. + */ +function check(bool $ok, string $what): void +{ + global $failures; + + if (!$ok) { + $failures[] = $what; + } +} + +/** + * Compare two values, reporting what differed. + */ +function checkSame(mixed $expected, mixed $actual, string $what): void +{ + global $failures; + + if ($expected !== $actual) { + $failures[] = $what . "\n expected: " . \json_encode($expected) . "\n actual: " . \json_encode($actual); + } +} + +/** + * Print what failed and exit with a status that says so. + */ +function report(string $name): never +{ + global $failures; + + if ($failures === []) { + echo $name . ": OK\n"; + exit(0); + } + + \fwrite(STDERR, $name . ": " . \count($failures) . " failure(s)\n"); + + foreach ($failures as $failure) { + \fwrite(STDERR, ' - ' . $failure . "\n"); + } + + exit(1); +} + +/** + * Run the whole playground against `$stub` and hand back what it printed. + * + * @param array $env extra environment for the run + */ +function runPlayground(Stub $stub, array $env = []): string +{ + $command = \array_map( + \escapeshellarg(...), + [PHP_BINARY, __DIR__ . '/prelude.php'] + ); + + $environment = ['PLAYGROUND_ENDPOINT' => $stub->endpoint] + $env; + + foreach ($environment as $name => $value) { + \putenv($name . '=' . $value); + } + + $output = \shell_exec(\implode(' ', $command) . ' 2>&1'); + + foreach (\array_keys($environment) as $name) { + \putenv((string) $name); + } + + return \is_string($output) ? $output : ''; +} + +/** + * The `call` values the playground printed, in the order it printed them. + * + * @return list + */ +function playgroundCalls(string $output): array +{ + \preg_match_all('/\[call\] => (\S+)/', $output, $matches); + + return $matches[1]; +} diff --git a/tests/prelude.php b/tests/prelude.php new file mode 100644 index 0000000..b40d8b4 --- /dev/null +++ b/tests/prelude.php @@ -0,0 +1,25 @@ + 'playground-user', + 'PLAYGROUND_VERIFICATION_SECRET' => '123456', + ]); + + $requests = \array_map( + static fn (array $request): array => [$request['method'], $request['path']], + $stub->requests() + ); +} finally { + $stub->stop(); +} + +checkSame($expectedCalls, playgroundCalls($output), 'The playground did not make every call'); +checkSame($expectedRequests, $requests, 'The playground did not hit the expected endpoints'); +check(!\str_contains($output, 'has no route for'), "The playground called a route the stub does not know:\n" . $output); +check( + \str_contains($output, '[response] => Array'), + "The playground printed no hydrated response:\n" . $output +); + +report('smoke'); diff --git a/tests/stub-server.php b/tests/stub-server.php new file mode 100644 index 0000000..fd2023f --- /dev/null +++ b/tests/stub-server.php @@ -0,0 +1,250 @@ + $method, 'path' => $path, 'key' => $hasKey]) . "\n", + FILE_APPEND | LOCK_EX + ); + } +} + +/** + * Answer a request and stop. + * + * @param array|null $payload + */ +function respond(int $status, ?array $payload = null): never +{ + \http_response_code($status); + + if ($payload !== null) { + \header('Content-Type: application/json'); + echo \json_encode($payload); + } + + exit; +} + +/** + * Count one attempt for `$userId` and answer with what is left. + * + * The count is kept per user, the way the server keys the limit on these + * routes, and it advances for every caller — a request carrying an API key + * included. That is the whole point of the fix this stub mirrors: before it, + * a key's attempts were peeked at and never counted, so a key could keep + * guessing a six digit code for free. + */ +function countAttempt(string $userId): int +{ + $state = \getenv('STUB_STATE'); + + if (!\is_string($state) || $state === '') { + return 1; + } + + $handle = \fopen($state, 'c+'); + + if ($handle === false) { + respond(500, ['message' => 'Stub could not open its state', 'type' => 'general_unknown', 'code' => 500]); + } + + \flock($handle, LOCK_EX); + $counts = \json_decode(\stream_get_contents($handle) ?: '{}', true) ?: []; + $spent = ($counts[$userId] ?? 0) + 1; + $counts[$userId] = $spent; + \ftruncate($handle, 0); + \rewind($handle); + \fwrite($handle, (string) \json_encode($counts)); + \fflush($handle); + \flock($handle, LOCK_UN); + \fclose($handle); + + return $spent; +} + +/** + * A verification confirmation route: `PUT /v1/account/verifications/{email,email/otp,phone}`. + * + * @param array $body + */ +function confirmVerification(array $body): never +{ + $userId = (string) ($body['userId'] ?? ''); + $secret = (string) ($body['secret'] ?? ''); + + if ($userId === '' || $secret === '') { + respond(400, [ + 'message' => 'Missing required parameter', + 'type' => 'general_argument_invalid', + 'code' => 400, + ]); + } + + if (countAttempt($userId) > VERIFICATION_LIMIT) { + respond(429, [ + 'message' => 'Too many requests', + 'type' => 'general_rate_limit_exceeded', + 'code' => 429, + ]); + } + + if ($secret !== VERIFICATION_CODE) { + respond(401, [ + 'message' => 'Invalid token passed in the request', + 'type' => 'user_invalid_token', + 'code' => 401, + ]); + } + + respond(200, [ + '$id' => 'playground-token', + '$createdAt' => '2026-01-01T00:00:00.000+00:00', + 'userId' => $userId, + 'secret' => '', + 'expire' => '2026-01-01T01:00:00.000+00:00', + ]); +} + +$user = [ + '$id' => 'playground-user', + 'name' => 'Example', + 'email' => 'example@example.com', + 'prefs' => [], +]; + +$execution = [ + '$id' => 'playground-execution', + 'resourceId' => 'playground-function', + 'trigger' => 'http', + 'status' => 'completed', + 'responseStatusCode' => 200, +]; + +match (true) { + // Readiness probe for `tests/stub.php`, not an Appwrite route. + $path === '/v1/health' => respond(200, ['status' => 'pass']), + + $method === 'POST' && $path === '/v1/tablesdb' => respond(201, [ + '$id' => 'playground-db', + 'name' => 'Test Database', + 'type' => 'tablesdb', + ]), + $method === 'GET' && \preg_match('#^/v1/tablesdb/[^/]+/tables$#', $path) === 1 => respond(200, [ + 'total' => 1, + 'tables' => [['$id' => 'playground-table', 'name' => 'table']], + ]), + $method === 'POST' && \preg_match('#^/v1/tablesdb/[^/]+/tables$#', $path) === 1 => respond(201, [ + '$id' => 'playground-table', + 'name' => 'table', + ]), + $method === 'POST' && \preg_match('#^/v1/tablesdb/[^/]+/tables/[^/]+/columns/[a-z]+$#', $path) === 1 => respond(202, [ + 'key' => 'column', + 'type' => 'string', + 'status' => 'available', + 'required' => true, + ]), + $method === 'POST' && \preg_match('#^/v1/tablesdb/[^/]+/tables/[^/]+/rows$#', $path) === 1 => respond(201, [ + '$id' => 'playground-row', + '$tableId' => 'playground-table', + '$databaseId' => 'playground-db', + 'name' => 'Spider Man', + 'release_year' => 1920, + ]), + $method === 'DELETE' && \preg_match('#^/v1/tablesdb/[^/]+/tables/[^/]+$#', $path) === 1 => respond(204), + $method === 'DELETE' && \preg_match('#^/v1/tablesdb/[^/]+$#', $path) === 1 => respond(204), + + $method === 'POST' && $path === '/v1/storage/buckets' => respond(201, [ + '$id' => 'playground-bucket', + 'name' => 'test bucket', + ]), + $method === 'GET' && \preg_match('#^/v1/storage/buckets/[^/]+/files$#', $path) === 1 => respond(200, [ + 'total' => 1, + 'files' => [['$id' => 'playground-file', 'name' => 'test.txt']], + ]), + $method === 'POST' && \preg_match('#^/v1/storage/buckets/[^/]+/files$#', $path) === 1 => respond(201, [ + '$id' => 'playground-file', + 'bucketId' => 'playground-bucket', + 'name' => 'test.txt', + ]), + $method === 'DELETE' && \preg_match('#^/v1/storage/buckets/[^/]+/files/[^/]+$#', $path) === 1 => respond(204), + $method === 'DELETE' && \preg_match('#^/v1/storage/buckets/[^/]+$#', $path) === 1 => respond(204), + + $method === 'POST' && $path === '/v1/users' => respond(201, $user), + $method === 'GET' && $path === '/v1/users' => respond(200, ['total' => 1, 'users' => [$user]]), + $method === 'PATCH' && \preg_match('#^/v1/users/[^/]+/verification$#', $path) === 1 => respond( + 200, + $user + ['emailVerification' => true] + ), + + $method === 'POST' && $path === '/v1/account/verifications/email' => respond(201, [ + '$id' => 'playground-token', + 'userId' => 'playground-user', + 'secret' => '', + ]), + $method === 'POST' && $path === '/v1/account/verifications/email/otp' => respond(201, [ + '$id' => 'playground-token', + 'userId' => 'playground-user', + 'secret' => '', + ]), + $method === 'PUT' && \in_array($path, [ + '/v1/account/verifications/email', + '/v1/account/verifications/email/otp', + '/v1/account/verifications/phone', + ], true) => confirmVerification($body), + + $method === 'POST' && $path === '/v1/functions' => respond(201, [ + '$id' => 'playground-function', + 'name' => 'Test Function', + 'runtime' => 'php-8.0', + ]), + $method === 'GET' && $path === '/v1/functions' => respond(200, [ + 'total' => 1, + 'functions' => [['$id' => 'playground-function', 'name' => 'Test Function']], + ]), + $method === 'POST' && \preg_match('#^/v1/functions/[^/]+/deployments$#', $path) === 1 => respond(202, [ + '$id' => 'playground-deployment', + 'status' => 'ready', + ]), + $method === 'POST' && \preg_match('#^/v1/functions/[^/]+/executions$#', $path) === 1 => respond(201, $execution), + $method === 'GET' && \preg_match('#^/v1/functions/[^/]+/executions/[^/]+$#', $path) === 1 => respond(200, $execution), + $method === 'DELETE' && \preg_match('#^/v1/functions/[^/]+$#', $path) === 1 => respond(204), + + default => respond(404, [ + 'message' => 'The stub has no route for ' . $method . ' ' . $path, + 'type' => 'general_route_not_found', + 'code' => 404, + ]), +}; diff --git a/tests/stub.php b/tests/stub.php new file mode 100644 index 0000000..a7a7287 --- /dev/null +++ b/tests/stub.php @@ -0,0 +1,113 @@ + ['file', '/dev/null', 'w'], 2 => ['file', '/dev/null', 'w']], + $pipes, + null, + ['STUB_LOG' => $log, 'STUB_STATE' => $state] + \getenv() + ); + + if (!\is_resource($process)) { + throw new RuntimeException('Could not start the stub server'); + } + + $stub = new self('http://127.0.0.1:' . $port . '/v1', $log, $state, $process); + + for ($attempt = 0; $attempt < 100; $attempt++) { + $health = @\file_get_contents($stub->endpoint . '/health'); + + if (\is_string($health) && \str_contains($health, 'pass')) { + return $stub; + } + + \usleep(50_000); + } + + $stub->stop(); + + throw new RuntimeException('The stub server did not come up'); + } + + /** + * Every request the stub has answered so far, in order. + * + * @return list + */ + public function requests(): array + { + $lines = \file($this->log, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; + + return \array_values(\array_filter(\array_map( + static fn (string $line): mixed => \json_decode($line, true), + $lines + ), \is_array(...))); + } + + /** + * Forget the requests logged so far, so one test does not read another's. + */ + public function forgetRequests(): void + { + \file_put_contents($this->log, ''); + } + + public function stop(): void + { + if (\is_resource($this->process)) { + \proc_terminate($this->process); + \proc_close($this->process); + } + + @\unlink($this->log); + @\unlink($this->state); + } + + /** + * A port nothing is listening on, found by letting the OS pick one. + */ + private static function freePort(): int + { + $socket = \stream_socket_server('tcp://127.0.0.1:0', $errno, $error); + + if ($socket === false) { + throw new RuntimeException('Could not find a free port: ' . $error); + } + + $name = (string) \stream_socket_get_name($socket, false); + \fclose($socket); + + return (int) \substr($name, \strrpos($name, ':') + 1); + } +} diff --git a/tests/verification.php b/tests/verification.php new file mode 100644 index 0000000..76b75f0 --- /dev/null +++ b/tests/verification.php @@ -0,0 +1,150 @@ +getCode(); + } +} + +$stub = Stub::start(); + +try { + $client = (new Client()) + ->setEndpoint($stub->endpoint) + ->setProject('playground') + ->setKey('playground-api-key'); + + $account = new Account($client); + $users = new Users($client); + + // A key gets the same budget as anyone else: wrong codes are refused, and + // they are counted, so the attempts run out. + $statuses = []; + + for ($i = 0; $i < LIMIT + 1; $i++) { + $statuses[] = attempt(static fn () => $account->updateEmailVerificationOTP('spender', '000000')); + } + + checkSame( + \array_fill(0, LIMIT, 401), + \array_slice($statuses, 0, LIMIT), + 'Wrong codes should be refused one by one' + ); + checkSame(429, $statuses[LIMIT], 'An API key should run out of attempts like any other caller'); + + // Once the budget is spent it stays spent for the hour — even for the + // user's own, correct code. Retrying a rejected code is what costs the + // integration, which is why the playground does not retry. + checkSame( + 429, + attempt(static fn () => $account->updateEmailVerificationOTP('spender', CODE)), + 'A spent budget should refuse even the correct code' + ); + + // The limit is keyed per user, so one user burning its attempts leaves + // every other user untouched. A server doing the one legitimate + // confirmation per user never notices the limit. + checkSame( + 0, + attempt(static fn () => $account->updateEmailVerificationOTP('fresh-user', CODE)), + 'Another user should still be able to confirm its code' + ); + + $token = $account->updateEmailVerificationOTP('another-user', CODE); + checkSame('another-user', $token->userId, 'A confirmed code should come back as that user\'s token'); + + // All three confirmation routes carry the limit, not just the OTP one. + foreach ([ + 'email' => static fn (string $user) => $account->updateEmailVerification($user, '000000'), + 'email/otp' => static fn (string $user) => $account->updateEmailVerificationOTP($user, '000000'), + 'phone' => static fn (string $user) => $account->updatePhoneVerification($user, '000000'), + ] as $route => $call) { + $user = 'user-for-' . \str_replace('/', '-', $route); + $last = 0; + + for ($i = 0; $i < LIMIT + 1; $i++) { + $last = attempt(static fn () => $call($user)); + } + + checkSame(429, $last, 'Attempts on /account/verifications/' . $route . ' should be counted'); + } + + // Marking a user verified from the server is a different route behind + // `users.write`, and it is not rate limited per user. + $verified = 0; + + for ($i = 0; $i < LIMIT + 1; $i++) { + $verified = attempt(static fn () => $users->updateEmailVerification('spender', true)); + } + + checkSame(0, $verified, 'users->updateEmailVerification() should not share the per-user budget'); + + // Finally, the playground itself: a rate limited confirmation is reported, + // not thrown, so the rest of the run still happens. + $stub->forgetRequests(); + $output = runPlayground($stub, [ + 'PLAYGROUND_VERIFICATION_USER_ID' => 'spender', + 'PLAYGROUND_VERIFICATION_SECRET' => CODE, + ]); + + check( + \str_contains($output, 'Rate limited: this user has spent its 10 confirmation attempts'), + "The playground should report a rate limited confirmation:\n" . $output + ); + check( + \in_array('api.deleteFunction', playgroundCalls($output), true), + "A rate limited confirmation should not stop the run:\n" . $output + ); +} finally { + $stub->stop(); +} + +report('verification');