diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..66167cd --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,33 @@ +name: Tests + +on: + pull_request: + push: + branches: + - main + +jobs: + tests: + name: Lint and test + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.5' + extensions: curl, json + coverage: none + + - name: Install dependencies + run: composer install --no-interaction --no-progress --optimize-autoloader + + - name: Lint + run: | + php -l global.inc.php + php -l playground.php + for file in tests/*.php; do php -l "$file"; done + + - name: Test + run: composer test diff --git a/Dockerfile b/Dockerfile index 700aa6d..a23ae3f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,16 +1,16 @@ FROM composer AS composer 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 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..053f6ae 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 newer installed (required by `appwrite/appwrite` 32.x). * 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,59 @@ 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 +* Request Password Recovery +* Log a User In From a Token Secret +* Create Function, Deployment and Executions + +Collections and documents were renamed to tables and rows in Appwrite 1.8. The +playground uses the `TablesDB` service; the older `Databases` service still +exists in the SDK, but every one of its methods is deprecated. + +### Abuse limits + +The account and recovery routes are abuse limited. Reaching a limit answers +`429`, which the SDK raises as an `AppwriteException` whose code is `429` and +whose type is `general_rate_limit_exceeded`. Since +[appwrite/appwrite#15280](https://github.com/appwrite/appwrite/pull/15280) the +count is kept per project: the attempts your project is allowed for a user or an +address are its own, and another project cannot spend them for you. +`createRecovery()` in `playground.php` shows how to handle the refusal. + +An API key used to be waived from those limits. Since +[appwrite/appwrite#15470](https://github.com/appwrite/appwrite/pull/15470) the +routes that confirm a secret — `updateRecovery()`, `updateRecoveryOTP()`, +`createSession()`, `updatePhoneSession()`, `updateMagicURLSession()` and +`updateMFAChallenge()` — count every caller's guesses, a key holder included. A +key is trusted with throughput, not with the inbox or handset the secret was +sent to. + +So a server relaying logins or recoveries for its users has to treat the +confirmation as something it gets a handful of tries at per user: + +* `401` means the secret is wrong or has expired — ask the user for a new one. +* `429` means that user's attempts are spent — wait, do not guess again. + Once a limit is spent the route refuses the correct secret too, so retrying a + mistyped code locks the user out of signing in for the rest of the window. + +`createSessionFromToken()` in `playground.php` shows the shape of that handling. + +## Tests + +`composer test` runs the playground end to end against a stub Appwrite +(`tests/stub-server.php`) served by PHP's built-in web server, checking that +every call succeeded and hit the endpoint it was supposed to +(`tests/smoke.php`), and then drives the abuse-limited confirmation routes with +an API key to check that wrong guesses are counted for it, that the count is per +user, and that the `429` reaches the caller in a shape it can act on +(`tests/code-guesses.php`). No Appwrite instance and no network access are +needed. ## Contributing diff --git a/composer.json b/composer.json index 060e8c4..7d25ac7 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/code-guesses.php" + ] + }, "support": { "email": "team@appwrite.io", "issues": "https://github.com/appwrite/playground-for-php/issues", diff --git a/docker-compose.yml b/docker-compose.yml index 6a82cab..ebcbf5a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,7 @@ -version: '3.9' - services: playground-for-php: build: . volumes: - "./:/app" working_dir: /app - command: "php playground.php" \ No newline at end of file + command: "php playground.php" diff --git a/playground.php b/playground.php index c1e7283..531174f 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 = ""; +$functionId = ""; -$databases = new Databases($client); +$tablesDB = new TablesDB($client); $storage = new Storage($client); $functions = new Functions($client); $users = new Users($client); @@ -34,34 +37,36 @@ * Covered API methods * - createDatabase * - deleteDatabase - * - createCollection - * - deleteCollection - * - listCollection - * - addDoc + * - createTable + * - deleteTable + * - listTables + * - addRow * - uploadFile * - listFiles * - deleteFile * - createUser * - listUser * - getAccount + * - createRecovery + * - createSessionFromToken */ /** * 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', @@ -70,19 +75,19 @@ function createDatabase(): array } /** -* Create a new Collection. -* -* @see https://appwrite.io/docs/server/databases?sdk=php#databasesCreateCollection -* @throws Exception -*/ -function createCollection(): array + * Create a new Table. + * + * @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 +96,18 @@ function createCollection(): array ] ); - $collectionId = $response['$id']; + $tableId = $response->id; - $response1 = $databases->createStringAttribute( + $response1 = $tablesDB->createStringColumn( $databaseId, - $collectionId, + $tableId, key: 'name', size: 255, required: true, ); - $response2 = $databases->createIntegerAttribute( + $response2 = $tablesDB->createIntegerColumn( $databaseId, - $collectionId, + $tableId, key: 'release_year', required: true, min: 0, @@ -110,46 +115,47 @@ function createCollection(): array ); return [ - 'call' => 'api.createCollection', + 'call' => 'api.createTable', 'response' => $response, ]; } /** - * 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', + 'call' => 'api.listTables', 'response' => $response, ]; } /** - * 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 +168,27 @@ function addDoc(): array ); return [ - 'call' => 'api.addDoc', + 'call' => 'api.addRow', 'response' => $response, ]; } /** - * 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 +197,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 +216,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,7 +236,7 @@ function createBucket(): array fileSecurity: true, ); - $bucketId = $response['$id']; + $bucketId = $response->id; return [ 'call' => 'api.createBucket', @@ -243,7 +249,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/client-php/storage#createFile * @return array * @throws Exception */ @@ -260,7 +266,7 @@ function createFile(): array ] ); - $fileId = $response['$id']; + $fileId = $response->id; return [ 'call' => 'api.createFile', @@ -273,7 +279,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/client-php/storage#listFiles * @return array * @throws Exception */ @@ -293,7 +299,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/client-php/storage#deleteFile * @return array * @throws Exception */ @@ -313,7 +319,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,7 +338,7 @@ 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 */ @@ -358,7 +364,7 @@ function createUser(): array /** * 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 @@ -376,7 +382,7 @@ function listUsers(): array /** * 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 @@ -391,10 +397,117 @@ function getAccount(): array ]; } +/** + * Email a password recovery link to an address. + * + * A guest route: it needs the project, and neither an API key nor a session. + * The `X-Appwrite-Project` header the SDK sends for it is what scopes its abuse + * limit — the counter is kept per project and address, so the handful of + * attempts one project is allowed for an address is its own, and another + * project asking to recover the same address still gets its full share. + * + * Two answers are worth handling rather than letting them abort a flow: + * `429` once the project has spent its share for the address (retry later), and + * `404` when no account in the project uses the address. + * + * @see https://appwrite.io/docs/references/cloud/client-php/account#createRecovery + * @throws Exception + */ +function createRecovery(): array +{ + global $account; + + try { + $response = $account->createRecovery( + email: 'recovery@example.com', + url: 'https://example.com/recover' + ); + } catch (AppwriteException $e) { + if ($e->getCode() !== 429 && $e->getCode() !== 404) { + throw $e; + } + + $response = [ + 'recoveryRequested' => false, + 'code' => $e->getCode(), + 'message' => $e->getMessage(), + ]; + } + + return [ + 'call' => 'api.createRecovery', + 'response' => $response, + ]; +} + +/** + * Log a user in from a token secret, the way a server relays a login. + * + * `users->createToken()` mints a short secret for a user with the API key, and + * `account->createSession()` exchanges it for a session. The exchange route is + * where a wrong secret is answered, and since + * [appwrite/appwrite#15470](https://github.com/appwrite/appwrite/pull/15470) a + * wrong guess counts against the per-user abuse limit for *every* caller — an + * API key included. A key is trusted with throughput, not with the inbox or + * handset the secret was sent to, and a six digit code is only 10^6 guesses, so + * the limit is the only thing standing between a key and any account. + * + * What that means for code like this one: handle `401` (wrong or expired + * secret) and `429` (the user's share of attempts is spent) instead of retrying + * the exchange. Retrying a secret the user mistyped now spends the attempts of + * the user it names, so a retry loop locks that user out of signing in. + * + * The same applies to every route that confirms a secret with the caller's + * copy: `updateRecoveryOTP()`, `updatePhoneSession()`, + * `updateMagicURLSession()`, `updateMFAChallenge()` and `updateRecovery()`. + * + * @see https://appwrite.io/docs/references/cloud/server-php/account#createSession + * @throws Exception + */ +function createSessionFromToken(): array +{ + global $users, $account; + + $suffix = \time(); + + $user = $users->create( + userId: ID::unique(), + email: "session{$suffix}@example.com", + password: 'password', + name: "Session {$suffix}" + ); + + $token = $users->createToken(userId: $user->id); + + try { + $response = $account->createSession( + userId: $token->userId, + secret: $token->secret + ); + } catch (AppwriteException $e) { + if ($e->getCode() !== 401 && $e->getCode() !== 429) { + throw $e; + } + + // 401: the secret is wrong or has expired — ask the user for a new one. + // 429: this user's attempts are spent — wait, do not guess again. + $response = [ + 'sessionCreated' => false, + 'code' => $e->getCode(), + 'message' => $e->getMessage(), + ]; + } + + return [ + 'call' => 'api.createSessionFromToken', + 'response' => $response, + ]; +} + /** * 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 @@ -404,11 +517,11 @@ function createFunction(): array $response = $functions->create( functionId: ID::unique(), name: 'Test Function', - runtime: Runtime::PHP80(), + runtime: Runtime::PHP84(), execute: [Role::any()], ); - $functionId = $response['$id']; + $functionId = $response->id; return [ 'call' => 'api.createFunction', @@ -418,8 +531,8 @@ functionId: ID::unique(), /** * 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 @@ -445,8 +558,8 @@ functionId: $functionId, /** * 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 @@ -470,8 +583,8 @@ functionId: $functionId, /** * 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,7 +603,7 @@ 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', @@ -501,7 +614,7 @@ functionId: $functionId, /** * 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 @@ -519,7 +632,7 @@ function listFunctions(): array /** * 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 +654,10 @@ function deleteFunction(): array $ret = []; $methods = [ 'createDatabase', - 'createCollection', - 'listCollections', - 'addDoc', - 'deleteCollection', + 'createTable', + 'listTables', + 'addRow', + 'deleteTable', 'deleteDatabase', 'createBucket', 'createFile', @@ -553,6 +666,8 @@ function deleteFunction(): array 'deleteBucket', 'createUser', 'listUsers', + 'createRecovery', + 'createSessionFromToken', 'createFunction', 'createDeployment', 'createSyncExecution', diff --git a/resources/code.tar.gz b/resources/code.tar.gz index b8d5fb3..beaec3f 100644 Binary files a/resources/code.tar.gz and b/resources/code.tar.gz differ diff --git a/resources/composer.json b/resources/composer.json index d69714a..3c3e74a 100644 --- a/resources/composer.json +++ b/resources/composer.json @@ -2,7 +2,7 @@ "name": "templates/starter", "type": "library", "require": { - "php": ">=8.0.0", - "appwrite/appwrite": "^8.0" + "php": ">=8.2.0", + "appwrite/appwrite": "^28.0" } } \ No newline at end of file diff --git a/tests/code-guesses.php b/tests/code-guesses.php new file mode 100644 index 0000000..40cd981 --- /dev/null +++ b/tests/code-guesses.php @@ -0,0 +1,219 @@ +setEndpoint($stub->endpoint) + ->setProject('playground') + ->setKey('playground-api-key') + ); +} + +/** + * Exchange a secret for a session and report what the caller sees: 201, or the + * code and type of the AppwriteException the SDK raised. + * + * @return array{0: int, 1: string} [code, error type] + */ +function exchangeToken(Account $account, string $userId, string $secret): array +{ + try { + $account->createSession(userId: $userId, secret: $secret); + + return [201, '']; + } catch (AppwriteException $e) { + return [$e->getCode(), $e->getType()]; + } +} + +/** + * Confirm a recovery OTP, reported the same way. + * + * @return array{0: int, 1: string} [code, error type] + */ +function confirmRecoveryOTP(Account $account, string $userId, string $secret): array +{ + try { + $account->updateRecoveryOTP(userId: $userId, secret: $secret, password: 'new-password'); + + return [201, '']; + } catch (AppwriteException $e) { + return [$e->getCode(), $e->getType()]; + } +} + +$stub = Stub::start(); + +try { + $account = keyedAccount($stub); + + echo "A key may still exchange a secret it was given\n"; + + [$code, $type] = exchangeToken($account, 'victim', VALID_SECRET); + check("the correct secret is exchanged for a session (got {$code} {$type})", $code === 201); + + $requests = $stub->requests(); + $last = \end($requests); + check( + 'the exchange went to POST /v1/account/sessions/token', + $last !== false && $last['method'] === 'POST' && $last['path'] === '/v1/account/sessions/token' + ); + check('the exchange carried the API key', ($last['keyed'] ?? false) === true); + check( + "the exchange named the project (got '" . ($last['project'] ?? '') . "')", + ($last['project'] ?? '') === 'playground' + ); + + echo "A wrong secret is refused, and the attempts run out for a key too\n"; + + // The exchange above worked, and the limits on this route count failures + // rather than requests, so all ten of these are still within the share. + + $codes = []; + $types = []; + + for ($attempt = 1; $attempt <= GUESS_LIMIT; $attempt++) { + [$codes[], $types[]] = exchangeToken($account, 'victim', WRONG_SECRET); + } + + check( + 'every attempt within the limit is refused with 401', + $codes === \array_fill(0, GUESS_LIMIT, 401) + ); + check( + 'the refusals are typed user_invalid_token', + $types === \array_fill(0, GUESS_LIMIT, 'user_invalid_token') + ); + + [$code, $type] = exchangeToken($account, 'victim', WRONG_SECRET); + check("the next guess is throttled with 429 (got {$code})", $code === 429); + check("the throttle is typed general_rate_limit_exceeded (got '{$type}')", $type === 'general_rate_limit_exceeded'); + + echo "Spending one user's attempts leaves another user's\n"; + + [$code, $type] = exchangeToken($account, 'bystander', WRONG_SECRET); + check("another user is still answered 401, not 429 (got {$code} {$type})", $code === 401); + + echo "The recovery OTP confirmation counts the same way\n"; + + $codes = []; + + for ($attempt = 1; $attempt <= GUESS_LIMIT; $attempt++) { + [$codes[]] = confirmRecoveryOTP($account, 'victim', WRONG_SECRET); + } + + check( + 'every attempt within the limit is refused with 401', + $codes === \array_fill(0, GUESS_LIMIT, 401) + ); + + [$code, $type] = confirmRecoveryOTP($account, 'victim', WRONG_SECRET); + check("the next guess is throttled with 429 (got {$code})", $code === 429); + check("the throttle is typed general_rate_limit_exceeded (got '{$type}')", $type === 'general_rate_limit_exceeded'); + + [$code, $type] = confirmRecoveryOTP($account, 'victim', VALID_SECRET); + check( + "a spent limit refuses the correct secret too (got {$code} {$type})", + $code === 429 + ); + + if ($failures !== []) { + \fwrite(STDERR, '--- stub server log ---' . "\n" . $stub->errorLog() . "\n"); + } +} finally { + $stub->stop(); +} + +if ($failures !== []) { + \fwrite(STDERR, "FAILED\n"); + + foreach ($failures as $failure) { + \fwrite(STDERR, " - {$failure}\n"); + } + + exit(1); +} + +echo "OK — code guesses are counted for an API key, as appwrite/appwrite#15470 intends\n"; diff --git a/tests/prelude.php b/tests/prelude.php new file mode 100644 index 0000000..fbaf447 --- /dev/null +++ b/tests/prelude.php @@ -0,0 +1,23 @@ +endpoint}\n"; + + $playgroundOutput = \tmpfile(); + $playground = \proc_open( + [PHP_BINARY, $root . '/tests/prelude.php'], + [1 => $playgroundOutput, 2 => $playgroundOutput], + $playgroundPipes, + $root, + ['PLAYGROUND_ENDPOINT' => $stub->endpoint] + \getenv() + ); + + if (!\is_resource($playground)) { + \fwrite(STDERR, "Could not start playground.php\n"); + exit(1); + } + + $status = \proc_close($playground); + \rewind($playgroundOutput); + $output = (string) \stream_get_contents($playgroundOutput); + \fclose($playgroundOutput); + + if ($status !== 0) { + $failures[] = "playground.php exited with status {$status}"; + } + + if (\str_contains($output, 'Stub has no route')) { + $failures[] = 'The playground called a route the stub does not know'; + } + + $remaining = $expectedCalls; + + foreach (\explode("\n", $output) as $line) { + if (!\preg_match('/\[call\] => (\S+)/', $line, $matches)) { + continue; + } + + $found = \array_search($matches[1], $remaining, true); + + if ($found === false) { + $failures[] = "Unexpected call in the result: {$matches[1]}"; + continue; + } + + unset($remaining[$found]); + } + + foreach ($remaining as $missing) { + $failures[] = "Missing from the result (the call threw): {$missing}"; + } + + $requests = \array_map( + static fn (array $request): array => [$request['method'], $request['path']], + $stub->requests() + ); + + if ($requests !== $expectedRequests) { + $failures[] = "Requests did not match.\nexpected:\n" + . \implode("\n", \array_map(static fn (array $r): string => " {$r[0]} {$r[1]}", $expectedRequests)) + . "\nactual:\n" + . \implode("\n", \array_map(static fn (array $r): string => " {$r[0]} {$r[1]}", $requests)); + } + + foreach ($requests as [$method, $path]) { + if (\str_starts_with($path, '/v1/databases')) { + $failures[] = "{$method} {$path} uses the Databases API, deprecated since Appwrite 1.8 in favour of TablesDB"; + } + } + + /** + * Every route the server keys an abuse limit by project needs the project + * to reach it. The SDK sends it per route, so a missing one would be a + * silent cross-project bucket rather than an error. + */ + foreach ($stub->requests() as $request) { + if ($request['project'] !== 'playground') { + $failures[] = "{$request['method']} {$request['path']} did not carry the project"; + } + } + + /** + * The playground is a server: it reaches the session exchange with the API + * key, which is the caller appwrite/appwrite#15470 stopped exempting from + * that route's limits. `tests/code-guesses.php` covers what the limits then + * do; this only pins down that the playground is that kind of caller, so a + * key dropped from the request would not quietly make the test pass. + */ + foreach ($stub->requests() as $request) { + if ($request['path'] === '/v1/account/sessions/token' && $request['keyed'] !== true) { + $failures[] = 'The session exchange did not carry the API key'; + } + } + + if ($failures !== []) { + \fwrite(STDERR, "\n--- playground.php output ---\n{$output}\n"); + \fwrite(STDERR, '--- stub server log ---' . "\n" . $stub->errorLog() . "\n"); + } +} finally { + $stub->stop(); +} + +if ($failures !== []) { + \fwrite(STDERR, "FAILED\n"); + + foreach ($failures as $failure) { + \fwrite(STDERR, " - {$failure}\n"); + } + + exit(1); +} + +echo 'OK — ' . \count($expectedCalls) . ' playground calls over ' + . \count($expectedRequests) . " requests\n"; diff --git a/tests/stub-server.php b/tests/stub-server.php new file mode 100644 index 0000000..308a8f6 --- /dev/null +++ b/tests/stub-server.php @@ -0,0 +1,269 @@ + $method, + 'path' => $path, + 'project' => $project, + // Whether the caller held an API key, which used to exempt it from + // the limits on the routes below. + 'keyed' => ($_SERVER['HTTP_X_APPWRITE_KEY'] ?? '') !== '', + ]) . "\n", + FILE_APPEND | LOCK_EX + ); +} + +/** + * Answer a request and stop. + * + * @param array|null $body + */ +function respond(int $status, ?array $body = null): never +{ + \http_response_code($status); + + if ($body !== null) { + \header('Content-Type: application/json'); + echo \json_encode($body); + } + + exit; +} + +/** + * The request body as an array, or an empty one when there is no JSON body. + * + * @return array + */ +function body(): array +{ + static $body = null; + + if ($body === null) { + $decoded = \json_decode(\file_get_contents('php://input') ?: '[]', true); + $body = \is_array($decoded) ? $decoded : []; + } + + return $body; +} + +/** + * Read the counters, run `$change` over them and write back what it returns. + * + * Nothing here looks at whether the caller holds an API key: the limits on the + * routes that confirm a secret count for every caller. + * + * @param callable(array): array $change + * @return array the counters after the change + */ +function counters(callable $change): array +{ + $state = \getenv('STUB_STATE'); + + if (!\is_string($state) || $state === '') { + return $change([]); + } + + $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 = $change(\json_decode(\stream_get_contents($handle) ?: '{}', true) ?: []); + \ftruncate($handle, 0); + \rewind($handle); + \fwrite($handle, (string) \json_encode($counts)); + \fflush($handle); + \flock($handle, LOCK_UN); + \fclose($handle); + + return $counts; +} + +function spent(string $counter): int +{ + return counters(static fn (array $counts): array => $counts)[$counter] ?? 0; +} + +function spend(string $counter): void +{ + counters(static function (array $counts) use ($counter): array { + $counts[$counter] = ($counts[$counter] ?? 0) + 1; + + return $counts; + }); +} + +/** + * A route that confirms a secret the caller sends for a user it names. + * + * The limit is checked before the secret, the way the server's abuse hook runs + * ahead of the route: once a user's share is spent the route answers `429` even + * to the correct secret. Within the share, the correct secret is answered with + * `$success` and a wrong one with `401`. + * + * `$countEveryAttempt` tells the two kinds of limit apart. `Limit::attempts`, + * which the recovery OTP confirmation carries, counts every request; + * `Limit::failures`, which the session exchanges carry, counts only the ones + * that failed, so a login that worked does not eat into the share. Both count + * for every caller since appwrite/appwrite#15470. + * + * @param array $success + */ +function confirmSecret(string $project, string $path, array $success, bool $countEveryAttempt): never +{ + $body = body(); + $userId = (string) ($body['userId'] ?? ''); + $secret = (string) ($body['secret'] ?? ''); + $counter = $project . "\0" . $path . "\0" . $userId; + + if (spent($counter) >= GUESS_LIMIT) { + respond(429, [ + 'message' => 'Too many requests', + 'type' => 'general_rate_limit_exceeded', + 'code' => 429, + ]); + } + + if ($countEveryAttempt) { + spend($counter); + } + + if ($secret === VALID_SECRET) { + respond(201, $success); + } + + if (!$countEveryAttempt) { + spend($counter); + } + + respond(401, [ + 'message' => 'Invalid token passed in the request.', + 'type' => 'user_invalid_token', + 'code' => 401, + ]); +} + +if ($method === 'POST' && $path === '/v1/account/sessions/token') { + confirmSecret($project, $path, [ + '$id' => 'playground-session', + 'userId' => 'playground-user', + 'secret' => 'playground-session-secret', + ], countEveryAttempt: false); +} + +if ($method === 'PUT' && $path === '/v1/account/recovery/otp') { + confirmSecret($project, $path, [ + '$id' => 'playground-token', + 'userId' => 'playground-user', + ], countEveryAttempt: true); +} + +/** + * @var array|null}> + * [method, path pattern, status, body] — `*` matches one path segment. + */ +$routes = [ + ['POST', '/v1/tablesdb', 201, ['$id' => 'playground-db', 'name' => 'Test Database']], + ['DELETE', '/v1/tablesdb/*', 204, null], + ['GET', '/v1/tablesdb/*/tables', 200, ['total' => 1, 'tables' => [['$id' => 'playground-table', 'name' => 'table']]]], + ['POST', '/v1/tablesdb/*/tables', 201, ['$id' => 'playground-table', 'name' => 'table']], + ['DELETE', '/v1/tablesdb/*/tables/*', 204, null], + ['POST', '/v1/tablesdb/*/tables/*/columns/string', 202, ['key' => 'name', 'type' => 'string', 'size' => 255, 'status' => 'available', 'required' => true]], + ['POST', '/v1/tablesdb/*/tables/*/columns/integer', 202, ['key' => 'release_year', 'type' => 'integer', 'status' => 'available', 'required' => true]], + ['POST', '/v1/tablesdb/*/tables/*/rows', 201, ['$id' => 'playground-row', 'name' => 'Spider Man', 'release_year' => 1920]], + + ['POST', '/v1/storage/buckets', 201, ['$id' => 'playground-bucket', 'name' => 'test bucket']], + ['DELETE', '/v1/storage/buckets/*', 204, null], + ['GET', '/v1/storage/buckets/*/files', 200, ['total' => 1, 'files' => [['$id' => 'playground-file', 'name' => 'test.txt']]]], + ['POST', '/v1/storage/buckets/*/files', 201, ['$id' => 'playground-file', 'name' => 'test.txt']], + ['DELETE', '/v1/storage/buckets/*/files/*', 204, null], + + ['GET', '/v1/users', 200, ['total' => 1, 'users' => [['$id' => 'playground-user', 'prefs' => []]]]], + ['POST', '/v1/users', 201, ['$id' => 'playground-user', 'email' => 'email@example.com', 'prefs' => []]], + ['POST', '/v1/users/*/tokens', 201, ['$id' => 'playground-token', 'userId' => 'playground-user', 'secret' => VALID_SECRET]], + + ['POST', '/v1/account/recovery', 201, ['$id' => 'playground-token', 'userId' => 'playground-user']], + + ['GET', '/v1/functions', 200, ['total' => 1, 'functions' => [['$id' => 'playground-function']]]], + ['POST', '/v1/functions', 201, ['$id' => 'playground-function', 'name' => 'Test Function']], + ['DELETE', '/v1/functions/*', 204, null], + ['POST', '/v1/functions/*/deployments', 202, ['$id' => 'playground-deployment', 'status' => 'ready']], + ['GET', '/v1/functions/*/executions/*', 200, ['$id' => 'playground-execution', 'trigger' => 'http', 'status' => 'completed']], + ['POST', '/v1/functions/*/executions', 201, ['$id' => 'playground-execution', 'trigger' => 'http', 'status' => 'completed']], + + // Reached only once the JWT-only call at the end of the playground's + // `$methods` list is uncommented. + ['GET', '/v1/account', 200, ['$id' => 'playground-user', 'email' => 'email@example.com', 'prefs' => []]], +]; + +/** + * Does a concrete path match a pattern whose `*` segments are wildcards? + */ +function matchesPattern(string $pattern, string $path): bool +{ + $patternSegments = \explode('/', $pattern); + $pathSegments = \explode('/', $path); + + if (\count($patternSegments) !== \count($pathSegments)) { + return false; + } + + foreach ($patternSegments as $i => $segment) { + if ($segment !== '*' && $segment !== $pathSegments[$i]) { + return false; + } + } + + return true; +} + +foreach ($routes as [$routeMethod, $pattern, $status, $body]) { + if ($routeMethod === $method && matchesPattern($pattern, $path)) { + respond($status, $body); + } +} + +respond(404, [ + 'message' => "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..cf20005 --- /dev/null +++ b/tests/stub.php @@ -0,0 +1,136 @@ +process = $process; + $this->errors = $errors; + } + + /** + * Ask the OS for a port nobody is using, then hand it to the stub server. + * There is a gap between closing the probe and the server binding, which is + * why this is a test-only shortcut and not a pattern to copy. + */ + 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 reserve a port: {$error}"); + } + + $name = (string) \stream_socket_get_name($socket, false); + \fclose($socket); + + return (int) \substr($name, \strrpos($name, ':') + 1); + } + + private static function tempFile(string $prefix): string + { + $file = \tempnam(\sys_get_temp_dir(), $prefix); + + if ($file === false) { + throw new RuntimeException("Could not create a temporary file for {$prefix}"); + } + + return $file; + } + + public static function start(): self + { + $root = \dirname(__DIR__); + $port = self::freePort(); + $requestLog = self::tempFile('playground-requests-'); + $stateFile = self::tempFile('playground-stub-state-'); + $errors = \tmpfile(); + + if ($errors === false) { + throw new RuntimeException('Could not create a log for the stub server'); + } + + $process = \proc_open( + [PHP_BINARY, '-S', "127.0.0.1:{$port}", '-t', $root, $root . '/tests/stub-server.php'], + [1 => ['file', '/dev/null', 'w'], 2 => $errors], + $pipes, + $root, + ['STUB_LOG' => $requestLog, 'STUB_STATE' => $stateFile] + \getenv() + ); + + if (!\is_resource($process)) { + throw new RuntimeException('Could not start the stub server'); + } + + for ($attempt = 0; $attempt < 100; $attempt++) { + $probe = @\stream_socket_client("tcp://127.0.0.1:{$port}", $errno, $error, 0.1); + + if ($probe !== false) { + \fclose($probe); + + return new self( + "http://127.0.0.1:{$port}/v1", + $requestLog, + $stateFile, + $process, + $errors + ); + } + + \usleep(50_000); + } + + \proc_terminate($process); + \proc_close($process); + + throw new RuntimeException("Stub server never accepted a connection on port {$port}"); + } + + /** + * The requests the stub has served so far, oldest first. + * + * @return list + */ + public function requests(): array + { + $lines = \file($this->requestLog, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + + return \array_map( + static fn (string $line): array => (array) \json_decode($line, true), + $lines === false ? [] : $lines + ); + } + + public function errorLog(): string + { + \rewind($this->errors); + + return (string) \stream_get_contents($this->errors); + } + + public function stop(): void + { + \proc_terminate($this->process); + \proc_close($this->process); + \fclose($this->errors); + @\unlink($this->requestLog); + @\unlink($this->stateFile); + } +}