Skip to content

fix(account): use the impersonated user for account reads and block account writes - #13653

Merged
HarshMN2345 merged 14 commits into
mainfrom
fix/impersonation-account-target-user
Sep 24, 2026
Merged

HarshMN2345 merged 14 commits into
mainfrom
fix/impersonation-account-target-user

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Impersonation is a project-user capability: a user flagged impersonator sends x-appwrite-impersonate-user-id alongside their own session, and the reference promises the request then "runs as the target user for API behavior". Only GET and DELETE /v1/account actually do. Everything else in the namespace still reads the impersonator's own user, so /account/prefs, /account/sessions, /account/identities and /account/mfa/factors report the impersonator's data under the target's name.

Verified against a local stack, impersonating target B as impersonator A:

request before
GET /account B
GET /account/prefs A's prefs
GET /account/sessions only A's session
GET /account/mfa/factors A's factors
DELETE /account 204, B is deleted
PATCH /account/name, /account/prefs 401 user_unauthorized
POST /account/targets/push 201, token lands on A
POST /account/jwts 201, A's JWT

Reads use the target. GET /v1/account/sessions, GET /v1/account/sessions/:sessionId, GET /v1/account/prefs, GET /v1/account/identities and GET /v1/account/mfa/factors now inject targetUser, which returns user when nothing is being impersonated, so none of them change outside impersonation.

The request runs on the impersonator's session, so current resolves against none of the target's sessions: GET /v1/account/sessions/:sessionId with current throws USER_SESSION_NOT_FOUND while impersonating, and the sessions list marks none of the target's sessions current. Those two agree — an earlier revision resolved current against 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 GET throw the new user_impersonation_read_only (403). This is not replacing working behaviour: PATCH /account/name and /account/prefs already 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/account used targetUser, so an impersonator permanently deleted the target's account — that is the one this matters most for. POST /account/targets/push did 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, POST and PUT /v1/account/mfa/challenges, and DELETE /v1/account/sessions/:sessionId. The first three go through. The fourth does not, and did not before this change either — it answers 401 user_unauthorized from 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 the mfa group — 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 how GET /v1/account/mfa/recovery-codes stays closed.

Account routes without an SDK Method are 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.read grant is limited to discovery. An impersonator-flagged user is granted users.read in shared/api.php so they can browse the project and pick a target. That same scope is the only gate on GET /v1/users/:userId/mfa/recovery-codes and GET /v1/users/:userId/mfa/challenges/:challengeId; neither handler checks anything further, and neither MFARecoveryCodes nor MFAChallengeSecret marks its field sensitive. 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. The impersonation: deny label 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 to GET /v1/users and GET /v1/users/:userId. A caller who holds users.read through an API key or a team role is unaffected.

request, impersonator's own session, no impersonation header before after
GET /v1/users 200 200
GET /v1/users/:otherId 200 200
GET /v1/users/:otherId/mfa/recovery-codes 200, codes in plaintext 401 general_unauthorized_scope
GET /v1/users/:otherId/sessions 200 401 general_unauthorized_scope

Test Plan

Adds four e2e tests to UsersBase, next to the existing impersonation coverage:

  • testImpersonationReadsTargetAccount — prefs and sessions come from the target, and current 404s.
  • testImpersonationRefusesAccountWrites — PATCH /account/name and /account/prefs are 403 user_impersonation_read_only, while POST /account/jwts still succeeds.
  • testImpersonationRefusesAccountDelete — DELETE /account is 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=testImpersona

Pint, PHPStan (level 4) and the Rector dry-run pass on the touched files.

Related PRs and Issues

  • None.

Checklist

  • Have you read the Contributing Guidelines on issues?
  • Adds the user_impersonation_read_only error; no SDK method metadata changed, so regenerated specs and example docs are not required. The update-user-impersonator reference text changed.

@greptile-apps

greptile-apps Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; the only remaining concern is a non-blocking coverage gap for the explicitly allowed impersonated session-deletion path.

Fix All in Claude CodeFindings

  1. P2 Impersonated logout lacks coverage ▶
Fix with agent prompt
### Issue 1
tests/e2e/Services/Users/UsersBase.php:3172-3175
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.

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!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

This PR makes impersonated account reads consistently use the target user, blocks account mutations during impersonation, and narrows the impersonator’s implicit users.read access to user discovery.

  • Account preferences, sessions, identities, and MFA factors now read from the impersonated target.
  • Account writes are rejected unless explicitly allowed for operations acting on the impersonator’s own session.
  • MFA recovery-code access is explicitly denied during impersonation.
  • The implicit users.read grant is restricted to listing and retrieving user documents.
  • End-to-end coverage verifies target reads, write and deletion refusal, JWT creation, and restricted MFA-secret access.

Reviews (13) · Last reviewed commit: "Merge branch 'main' into fix/impersonati..."

Comment thread app/controllers/api/account.php Resolved
@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/impersonation-account-target-user (after).

Metric Before After Change
🚀 Requests/sec 171.93 172.33 ⚪ +0.2%
⏱️ Latency P50 99.85 ms 99.69 ms ⚪ -0.2%
⏱️ Latency P95 238.5 ms 231.47 ms ⚪ -2.9%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 99.69 231.47 11,172 172.33 -7.03
Account 196.02 381.6 588 9.71 +19.5
TablesDB 96.48 179.26 6,076 97.03 -0.65
Storage 90.41 187.79 2,940 48.26 -9
Functions 148.62 291.5 1,568 26.36 -6.44

Top API waits (after)

API request Max wait (ms)
account.name.update 485.86
functions.variables.create 464.25
account.prefs.update 451.17
tablesdb.rows.increment 427.74
functions.delete 407.04

…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.
@HarshMN2345
HarshMN2345 force-pushed the fix/impersonation-account-target-user branch from 114e8e9 to afaae05 Compare September 14, 2026 08:53

@Hardanish-Singh Hardanish-Singh left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

HarshMN2345 and others added 3 commits September 18, 2026 12:39
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.
Comment thread app/controllers/shared/api.php Resolved
HarshMN2345 and others added 6 commits September 21, 2026 17:46
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.
Comment on lines +3172 to +3175
// 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']);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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!

Fix in Claude Code Fix in Codex

@HarshMN2345
HarshMN2345 merged commit d913004 into main Sep 24, 2026
50 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants