Repository navigation
fix: backport database, realtime and storage security fixes to 1.9.x - #14913
Conversation
|
Review complete. 🟡 4 medium 💬 Inline comments (4)
The change spans account/token endpoint refactors (removing injected
Reviewed commit: 0d8d4dd |
🟢 Tier S · Ready to mergeThis backport adds authentication and authorization hardening across account, organization, project, database, realtime, and storage flows. It also adds request limits, upload and response validation, cache invalidation, and regression coverage for the backported behavior. 18 of 72 changed files were too large to include in full.
Note Part of the diff was too large to review, so Hansi did not approve. 📂 Walkthrough · 13
🔇 Filtered out · 1Findings Hansi considered but did not post.
Reviewed |
0d8d4dd to
170c571
Compare
✨ Benchmark resultsComparing 1.9.x (before) to fix/1.9.x-security-data (after). Before
After
Delta
Top API waits
|
There was a problem hiding this comment.
This PR hardens realtime/transaction auth paths, refactors account token flows, and adds transaction e2e permission tests, but a new e2e test calls a nonexistent helper and a few auth gates have subtle divergences.
Key findings
- 🟡 Undefined
createTeamFixturebreaks new transfer test — ProjectsConsoleClientTest.php:353 - 🟡 Realtime impersonation gate diverges from HTTP path — connection.php:350
- 🟡 Staged creates drop the default self-grant permissions — Create.php:299
- 🟡 Stale
$sessionIdshadows$jwtSessionIdin impersonation gate — connection.php:352
| $foreignTeam = $this->createTeamFixture(array_merge([ | ||
| 'content-type' => 'application/json', | ||
| 'x-appwrite-project' => $this->getProject()['$id'], | ||
| ], $this->getHeaders()), [ | ||
| 'teamId' => Id::unique(), | ||
| 'name' => 'Foreign Team', | ||
| ]); | ||
| $this->assertSame(200, $foreignTeam['headers']['status-code']); | ||
| $foreignTeamId = $foreignTeam['body']['$id']; | ||
|
|
||
| $email = 'transfer-' . Id::unique() . '@localhost.test'; | ||
| ['membershipId' => $membershipId] = $this->setupUserMembership([ | ||
| 'teamId' => $sourceTeamId, | ||
| 'email' => $email, | ||
| 'name' => 'Transfer User', | ||
| 'roles' => ['owner'], | ||
| ]); | ||
|
|
||
| $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [ | ||
| 'origin' => 'http://localhost', | ||
| 'content-type' => 'application/json', | ||
| 'x-appwrite-project' => $this->getProject()['$id'], | ||
| ], [ | ||
| 'email' => $email, | ||
| 'password' => 'password', | ||
| ]); | ||
| $this->assertSame(201, $session['headers']['status-code']); | ||
|
|
||
| $headers = [ | ||
| 'origin' => 'http://localhost', | ||
| 'content-type' => 'application/json', | ||
| 'x-appwrite-project' => $this->getProject()['$id'], | ||
| 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session['cookies']['a_session_' . $this->getProject()['$id']], | ||
| ]; | ||
|
|
||
| $ownTeam = $this->createTeamFixture($headers, [ |
There was a problem hiding this comment.
🟡 bug · medium
Undefined createTeamFixture breaks new transfer test
The new test testTransferProjectTeamRequiresOwnership calls $this->createTeamFixture(...) twice (tests/e2e/Services/Projects/ProjectsConsoleClientTest.php:353 and :388), but no such method exists anywhere in the codebase. The test fatals with "Call to undefined method" as soon as it runs, breaking the projectsCRUD CI group.
📋 Prompt for AI Agents
In tests/e2e/Services/Projects/ProjectsConsoleClientTest.php around lines 353-388, the new test testTransferProjectTeamRequiresOwnership calls $this->createTeamFixture(...), a method that does not exist anywhere in the codebase. Add a private helper createTeamFixture(array $headers, array $params): array that POSTs to /teams with the given headers and params and returns the response array (asserting a 200/201 status code), or replace both calls with inline $this->client->call(Client::METHOD_POST, '/teams', $headers, $params) calls plus status assertions.
| if (!$user->isEmpty() && $user->getAttribute('impersonator', false)) { | ||
| // As over HTTP: impersonating needs a session to count factors on. | ||
| $impersonatorSessionId = $sessionId ?: $jwtSessionId; | ||
| $impersonating = !empty($impersonateUserId) || !empty($impersonateEmail) || !empty($impersonatePhone); | ||
| if ($impersonating && (empty($impersonatorSessionId) || !$user->sessionFactorsMet($impersonatorSessionId))) { | ||
| throw new Exception(Exception::USER_MORE_FACTORS_REQUIRED); | ||
| } |
There was a problem hiding this comment.
🟡 bug · medium
Realtime impersonation gate diverges from HTTP path
The new realtime gate rejects impersonation unless the impersonator holds a fully-factored session, justified by the comment "As over HTTP" — but the HTTP impersonation path (app/init/resources/request.php:494-519) performs no session or factors check whatsoever. An impersonator authenticated only with an account key (no session) can impersonate over HTTP, while the identical connection over realtime now throws USER_MORE_FACTORS_REQUIRED, breaking key-only Console realtime impersonation that worked before this PR.
📋 Prompt for AI Agents
Align impersonation authorization across surfaces: in app/init/resources/request.php around lines 494-519, before cloning the target user in the impersonation block, add the equivalent of the realtime gate in app/init/realtime/connection.php lines 350-356 — require an impersonator session id and $user->sessionFactorsMet($sessionId), throwing USER_MORE_FACTORS_REQUIRED otherwise (or deliberately relax the realtime gate for key-authenticated impersonators if key-only impersonation over HTTP is the intended policy).
| private function normalizePermissions(mixed $permissions): array | ||
| { | ||
| if (!\is_array($permissions)) { | ||
| throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Permissions must be an array of permission strings.'); | ||
| } | ||
|
|
||
| $validator = new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE, [ | ||
| Database::PERMISSION_READ, | ||
| Database::PERMISSION_UPDATE, | ||
| Database::PERMISSION_DELETE, | ||
| Database::PERMISSION_WRITE, | ||
| ]); | ||
| if (!$validator->isValid($permissions)) { | ||
| throw new Exception(Exception::GENERAL_BAD_REQUEST, $validator->getDescription()); | ||
| } | ||
|
|
||
| return Permission::aggregate($permissions, [ | ||
| Database::PERMISSION_READ, | ||
| Database::PERMISSION_UPDATE, | ||
| Database::PERMISSION_DELETE, | ||
| ]) ?? []; |
There was a problem hiding this comment.
🟡 bug · medium
Staged creates drop the default self-grant permissions
The direct document create endpoint grants the current user read/update/delete when no permissions are supplied (src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php:250-258), but the transaction staging path never applies that default: normalizePermissions normalizes only an explicitly present $permissions key and falls back to [] (src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Operations/Create.php:299-319). A session user who stages a create operation with '$permissions' => [] — or omits the key, in which case staged data is committed verbatim — commits a document with zero document-level permissions, while the identical direct call persists a full self-grant. The creator can end up with a document they cannot read or update.
📋 Prompt for AI Agents
In src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Operations/Create.php, make staged create operations match src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php:250-258: when $operation['data']['$permissions'] is absent or normalizes to an empty array and the caller is a non-privileged user with a non-empty id (see the $isAPIKey/$isPrivilegedUser/$user values at lines 87-88), set the staged permissions to read/update/delete grants on user:{callerId} before staging, so the commit handler's verbatim write persists the same default the direct endpoint does.
| $impersonatorSessionId = $sessionId ?: $jwtSessionId; | ||
| $impersonating = !empty($impersonateUserId) || !empty($impersonateEmail) || !empty($impersonatePhone); | ||
| if ($impersonating && (empty($impersonatorSessionId) || !$user->sessionFactorsMet($impersonatorSessionId))) { | ||
| throw new Exception(Exception::USER_MORE_FACTORS_REQUIRED); | ||
| } |
There was a problem hiding this comment.
🟡 bug · medium
Stale $sessionId shadows $jwtSessionId in impersonation gate
When a cookie session verifies but fails the sessionFactorsMet check, $user is reset to a guest while $sessionId keeps the old session id (app/init/realtime/connection.php:266-275). A subsequent x-appwrite-jwt header then loads a different user, and the impersonation gate resolves $impersonatorSessionId = $sessionId ?: $jwtSessionId, so the stale cookie session id wins over the JWT-bound session. sessionFactorsMet($sessionId) searches the JWT user's sessions for a foreign session id, returns false, and denies impersonation even though the JWT session satisfies the factor requirement.
📋 Prompt for AI Agents
In app/init/realtime/connection.php around lines 268-275, when the sessionFactorsMet check fails and $user is reset to new User([]), also set $sessionId = false so the stale cookie session id cannot leak into the impersonation gate at lines 350-356, where $impersonatorSessionId = $sessionId ?: $jwtSessionId must resolve to the session of the user that was actually authenticated.
f2c6f7e to
cddd248
Compare
cddd248 to
83455c2
Compare
Transaction operation create and file update are reachable by guests and had no abuse labels, so the shared api hook applied no limit to them. They now carry the document create and file write limits. The membership status part of the original commit is left to the teams backport. (cherry picked from commit 5a22fc3)
) Staging role-checked the raw permissions before aggregating, so write("<role not held>") was staged and committed unvalidated. Permissions are now validated, aggregated, role-checked and staged in canonical form. Legacy transaction Get and List also accept documents.read. (cherry picked from commit d2d54bf)
…ement, fix upsert perms (backport #14755) - Account API keys are refused on any project other than console, over HTTP and realtime, and project-scoped admin roles match an exact project-{id}- boundary. - Increment and decrement honor the database and collection enabled flags. - Upsert role-checks only caller-supplied permissions, not inherited ones. - Guests cannot generate embeddings. 1.9 has no embeddings.write scope (the route uses documents.write, which guests hold), so the text embeddings action refuses callers with neither a user nor a key. (cherry picked from commit bb790c1)
… (backport #14787) Organization project routes now grant project-specific roles only for the project named in the path, and organization-level routes grant only team-wide roles. Organization project reads keep database authorization on. 1.9 has no projectIdFromPath resource, so the path project is read from the URI inline; the organization key routes do not exist on 1.9 and their test calls are dropped. (cherry picked from commit 3f79291)
…ect (backport #14780) Any member of the source team could move a project into another team. Transfer now requires a confirmed owner membership on both the current and destination organization. 1.9 has no targetUser resource, so the effective user resource is used. (cherry picked from commit b7f9c9c)
The magic URL, email and phone token endpoints and the recovery endpoint copied the recipient into the shared user resource and added its role to the shared authorization, so later fields in the same GraphQL operation ran as the recipient. They now use a local recipient and create tokens under authorization skip. Each resolver restores the roles it started with, and the resolver lock is a per-request resource. 1.9 has no recovery OTP endpoint and no Authorization::withRoles, so roles are saved and restored around the field. (cherry picked from commit f3e4c08)
The console default bucket granted create, read, update and delete to any. It now only lets users create files, and file security governs the rest. Existing installs get the permissions corrected on start. (cherry picked from commit 2c5a569)
…port #14803) A session or session-bound JWT that still owes an MFA factor, and a blocked user, no longer authenticate a realtime connection, and in-band authentication refuses them. A blocked user cannot impersonate either. The per-connection message limiter is keyed by project, container and connection. 1.9 has no realtime permission revalidation, so the update.mfa revalidation trigger is not ported, and HTTP impersonation on 1.9 does not require a session, so the onOpen impersonation session check is not ported. Adds User::getMinimumFactors() and User::sessionFactorsMet(). (cherry picked from commit 3f829a1)
…nline encryption (backport #14791) The list cache key ignored collection permissions and documentSecurity, so a permission change kept serving cached lists until the TTL ran out. Inline encrypted attributes on create collection/table skipped the plan gate and minimum size the dedicated string endpoints apply. (cherry picked from commit db6ea18)
72c5aa8 to
0234ebe
Compare
0234ebe to
29c3249
Compare
The findings that requested changes are resolved. See the summary comment for what is still open.
…ckport #14788) The image and favicon avatars read a remote body of any size into memory. They now fetch through a cURL adapter that aborts the transfer once the body passes APP_STORAGE_READ_BUFFER (CURLOPT_MAXFILESIZE_LARGE plus a write callback that stops on the cap), failing with avatar_remote_url_failed, and both routes are limited to 60 requests per minute per IP. 1.9 fetches through utopia-php/fetch, whose cURL adapter takes no raw options, hence the small Appwrite\Utopia\Fetch\Adapter\Curl. The remote-file-too-large E2E test is not ported: it relies on the internal address allowlist 1.9 does not have. (cherry picked from commit d2c83c3)
…port #14816) Content-Range bounds at or past PHP_INT_MAX made the chunk arithmetic divide by zero, and the abuse hook swallowed the error and skipped the limit. Such ranges are now rejected, the chunk index is start divided by the upload chunk size, and the hook fails open only when the limiter itself fails. (cherry picked from commit f83fd3a)
…14785) The {url} abuse-key component included the request hostname, so a client could reset any limit by changing the Host or X-Forwarded-Host header. It is now the matched route path, and the realtime connection limit keys on /v1/realtime instead of the raw URI. The forwarded host and port trust changes live in packages/http, which 1.9 does not have, and are not ported. (cherry picked from commit 5cb4be8)
…ion routes (backport #14779) On a non-console project, a project session whose project team shared the organization ID counted as organization membership. Outside the console, organization routes now accept only API keys and console sessions in admin mode. The organization key routes do not exist on 1.9, so their test calls are dropped. (cherry picked from commit bf06dcb)
…kport #14790) A realtime connection opened in admin mode against a project only needed a console session. It now needs a confirmed membership in the project organization and read access to the project, and must come from a console origin. Authorized connections subscribe with the organization admin roles instead of the console user identity roles, and carry no user ID in the project. (cherry picked from commit 7090683)
…e names (backport #14789) Download and push concatenated the raw stored file name into Content-Disposition, so a name with quotes, semicolons or line breaks could rewrite the header. View, download and push now share Response::setContentDisposition(), which sends a printable ASCII fallback plus an RFC 5987 UTF-8 name. Download also sends nosniff and a sandbox CSP, push forces attachment for SVG, accepts only inline or attachment and quotes its CSP keyword, and file names with control characters are refused on create and update. The S3 gateway does not exist on 1.9; view keeps its 1.9 inline disposition and CSP. The tests use logo.png because the HTML and SVG fixtures are not on 1.9. (cherry picked from commit abc6b6f)
View, download, preview and push served a file before its final chunk was joined and scanned. They now answer file not found until every chunk is uploaded. (cherry picked from commit 73b71a6)
29c3249 to
662dac0
Compare
|
@hansi-codes review |
|
@hansi-codes review |
# Conflicts: # app/controllers/api/account.php # src/Appwrite/Utopia/Database/Documents/User.php # src/Appwrite/Utopia/Response.php
|
@hansi-codes review |
Backports security fixes from
mainto1.9.x. One commit per PR. No schema changes, migrations or new env vars.embeddings.writescope (route usesdocuments.write), so the embeddings action refuses guests directlyOrganizationis not in the 1.9 E2E matrixuser(notargetUserresource on 1.9)projectIdFromPathon 1.9)update.mfatrigger); impersonation session check skipped since 1.9 HTTP doesn't require oneJSONvalidatorwithRoles)packages/httpforwarded-host trust not on 1.9