Repository navigation
fix(account): use the impersonated user for account reads and block account writes - #13653
Conversation
|
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
…ccount writes While impersonating, most account endpoints still read the operator's session user, so the console showed (and let operators edit) their own identities, sessions, prefs and MFA factors under the target's name. - Account reads (sessions list/get, prefs, identities, MFA factors) now inject targetUser. - Non-GET account routes are refused with user_impersonation_read_only while impersonating. MFA-group routes stay open (the operator's own session) and an `impersonation` route label can override: 'allow' for JWT creation, 'deny' for credentials. - MFA recovery codes (account and users routes) and users MFA challenge secrets are labelled 'deny'. The implicit users.read grant for impersonators skips 'deny' routes, so operators can't read another user's recovery codes or challenge secrets.
114e8e9 to
afaae05
Compare
Skipping the implicit users.read grant on routes labelled `impersonation: deny` closed a separate hole: an operator holding the impersonator flag could read another console user's MFA recovery codes and challenge secrets through the Users API without impersonating anyone. That is its own bug, in a different namespace, with its own urgency - it does not belong in a change about which user the account endpoints read. Reverts the grant condition in shared/api.php and the labels on Users/MFA/RecoveryCodes/Get and Users/MFA/Challenges/Get, leaving this PR to the account namespace only. The label still refuses GET /v1/account/mfa/recovery-codes while impersonating. That path runs off the throw in shared/api.php, not the scope grant, so it is unaffected by this revert.
The guard exempted every route in the `mfa` group. That group means "reachable before MFA is satisfied", not "acts on the impersonator's own session", so it happened to cover the right three routes by coincidence and would have opened any future mfa-group write to an impersonator. Label those three instead: deleting the current session, and creating or confirming an MFA challenge. `GET /v1/account/sessions/:sessionId` looked `current` up on the impersonator while the sessions list reported the target, so the session it returned was absent from the list. Read the target for every id, which makes `current` throw USER_SESSION_NOT_FOUND while impersonating, matching the list marking none of the target's sessions current.
…ating The reference promised the request runs as the target user for API behavior, which no longer holds for anything that would change that account.
…used delete Nothing exercised the account surface under impersonation, so the reads reporting the impersonator and DELETE /v1/account removing the target both passed CI.
A user flagged `impersonator` is granted `users.read` so they can browse the project and pick a target. That scope also gates `GET /v1/users/:userId/mfa/recovery-codes` and `GET /v1/users/:userId/mfa/challenges/:challengeId`, whose handlers check nothing further and whose models do not mark the secrets sensitive, so the flag alone read any other user's recovery codes in plaintext -- enough to pass that user's second factor -- with no impersonation header in the request. Grant the scope only on `GET /v1/users` and `GET /v1/users/:userId`, which is what discovery needs. Holding the flag is a property of the impersonator's own account rather than a role on the project, so it should not carry a read of anyone else's credentials. The `impersonation: deny` label refuses the account-namespace route that returns the target's recovery codes, but it never covered the users-namespace one, which needs no impersonation to reach.
`DELETE /v1/account/sessions/current` returns 401 `user_unauthorized` while impersonating, on main as well: the session document belongs to the impersonator while the request carries the target's roles, so the delete is refused in the database layer. The `impersonation: allow` label still belongs on the route -- without it the answer becomes a 403 that blames impersonation for a failure that predates it -- but the route cannot stand as proof that allowed writes go through. `POST /v1/account/jwts` covers that branch.
| // Labelled `impersonation: allow` -- it mints a token for the impersonator's own | ||
| // session rather than touching the target's account. | ||
| $jwt = $this->client->call(Client::METHOD_POST, '/account/jwts', $accountHeaders); | ||
| $this->assertEquals(201, $jwt['headers']['status-code']); |
There was a problem hiding this comment.
Impersonated logout lacks coverage
Removing the impersonated DELETE /account/sessions/current request leaves the new impersonation: allow exception for session deletion completely untested. The remaining JWT assertion exercises a different handler, so it cannot detect whether logout is rejected or deletes the wrong session. Please retain an observable API assertion that logout succeeds and that the impersonator's session—not a target session—is deleted.
Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/e2e/Services/Users/UsersBase.php
Line: 3172-3175
Comment:
**Impersonated logout lacks coverage**
Removing the impersonated `DELETE /account/sessions/current` request leaves the new `impersonation: allow` exception for session deletion completely untested. The remaining JWT assertion exercises a different handler, so it cannot detect whether logout is rejected or deletes the wrong session. Please retain an observable API assertion that logout succeeds and that the impersonator's session—not a target session—is deleted.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
What does this PR do?
Impersonation is a project-user capability: a user flagged
impersonatorsendsx-appwrite-impersonate-user-idalongside their own session, and the reference promises the request then "runs as the target user for API behavior". OnlyGETandDELETE /v1/accountactually do. Everything else in the namespace still reads the impersonator's own user, so/account/prefs,/account/sessions,/account/identitiesand/account/mfa/factorsreport the impersonator's data under the target's name.Verified against a local stack, impersonating target B as impersonator A:
GET /accountGET /account/prefsGET /account/sessionsGET /account/mfa/factorsDELETE /accountPATCH /account/name,/account/prefsuser_unauthorizedPOST /account/targets/pushPOST /account/jwtsReads use the target.
GET /v1/account/sessions,GET /v1/account/sessions/:sessionId,GET /v1/account/prefs,GET /v1/account/identitiesandGET /v1/account/mfa/factorsnow injecttargetUser, which returnsuserwhen nothing is being impersonated, so none of them change outside impersonation.The request runs on the impersonator's session, so
currentresolves against none of the target's sessions:GET /v1/account/sessions/:sessionIdwithcurrentthrowsUSER_SESSION_NOT_FOUNDwhile impersonating, and the sessions list marks none of the target's sessions current. Those two agree — an earlier revision resolvedcurrentagainst the impersonator and returned a session that was absent from the list.Writes are refused while impersonating. Account-namespace routes that carry SDK metadata and are not
GETthrow the newuser_impersonation_read_only(403). This is not replacing working behaviour:PATCH /account/nameand/account/prefsalready fail today with a bare 401 out of the database layer, because the write targets the impersonator's document while authorization roles come from the target.DELETE /v1/accountusedtargetUser, so an impersonator permanently deleted the target's account — that is the one this matters most for.POST /account/targets/pushdid succeed, registering the push token against the impersonator rather than the target, and is now refused too.Four routes are marked
->label('impersonation', 'allow')because they aim at the impersonator's own session rather than the target's account:POST /v1/account/jwts,POSTandPUT /v1/account/mfa/challenges, andDELETE /v1/account/sessions/:sessionId. The first three go through. The fourth does not, and did not before this change either — it answers 401user_unauthorizedfrom the database layer, because the session document belongs to the impersonator while the request carries the target's roles. The label keeps that pre-existing failure as it is instead of turning it into a 403 that blames impersonation, and the route works again if that authorization gap is closed. An impersonator can still log out by dropping the impersonation header. The label is explicit rather than derived from themfagroup — that group means "reachable before MFA is satisfied" and covered the right routes only by coincidence, so any future mfa-group write would have silently opened.->label('impersonation', 'deny')refuses a route on any method, which is howGET /v1/account/mfa/recovery-codesstays closed.Account routes without an SDK
Methodare not covered, because the check sits inside the existing! empty($method)branch. In practice that is the three OAuth2 callback and redirect routes, which are driven by the provider rather than by a caller's request.The implicit
users.readgrant is limited to discovery. An impersonator-flagged user is grantedusers.readinshared/api.phpso they can browse the project and pick a target. That same scope is the only gate onGET /v1/users/:userId/mfa/recovery-codesandGET /v1/users/:userId/mfa/challenges/:challengeId; neither handler checks anything further, and neitherMFARecoveryCodesnorMFAChallengeSecretmarks its fieldsensitive. Holding the flag was therefore enough to read any other user's MFA recovery codes in plaintext, with no impersonation header in the request at all — those codes pass that user's second factor. Theimpersonation: denylabel above closes the account-namespace route that returns them; it never covered the users-namespace one, which needs no impersonation to reach. The grant now applies only toGET /v1/usersandGET /v1/users/:userId. A caller who holdsusers.readthrough an API key or a team role is unaffected.GET /v1/usersGET /v1/users/:otherIdGET /v1/users/:otherId/mfa/recovery-codesgeneral_unauthorized_scopeGET /v1/users/:otherId/sessionsgeneral_unauthorized_scopeTest Plan
Adds four e2e tests to
UsersBase, next to the existing impersonation coverage:testImpersonationReadsTargetAccount— prefs and sessions come from the target, andcurrent404s.testImpersonationRefusesAccountWrites—PATCH /account/nameand/account/prefsare 403user_impersonation_read_only, whilePOST /account/jwtsstill succeeds.testImpersonationRefusesAccountDelete—DELETE /accountis 403 and the target still exists.testImpersonatorUsersReadCoversDiscoveryOnly— another user's recovery codes are 401, and reading a user document still works.Run:
docker compose exec appwrite test tests/e2e/Services/Users --filter=testImpersonaPint, PHPStan (level 4) and the Rector dry-run pass on the touched files.
Related PRs and Issues
Checklist
user_impersonation_read_onlyerror; no SDK method metadata changed, so regenerated specs and example docs are not required. Theupdate-user-impersonatorreference text changed.