Skip to content

fix(security): transaction ACL, OTP secret masking, nested relationship permissions - #14045

Merged
abnegate merged 7 commits into
mainfrom
cursor/security-transaction-otp-nested-perms-8991
Oct 1, 2026
Merged

abnegate merged 7 commits into
mainfrom
cursor/security-transaction-otp-nested-perms-8991

Conversation

@abnegate

@abnegate abnegate commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Three security fixes for three Help Scout High reports. There is one commit per report, and each was checked against current main. Review follow-ups are in separate commits on top.

HS 1005147: transaction read ACL bypass

Confirmed on main. TransactionState::getTransactionState() loaded the transactions document under Authorization::skip and only checked status === 'pending'. Every transaction-aware read goes through it: document get, list and count, plus the internal read used by update, delete and upsert. That covers Legacy, TablesDB, DocumentsDB and VectorsDB. So any caller with a leaked transactionId could see another user's staged, uncommitted rows overlaid on the committed data.

Fix: TransactionState now receives the caller (user resource). It loads the transaction under the caller's ACL, unless the caller is an API key or a privileged user. This is the same rule Transactions/Update and Transactions/Operations/Create already use. A foreign transaction now resolves to an empty state: no staged overlay, and the caller only sees committed data their own ACL allows. Because this is the single choke point, every database flavour is covered without changing each read endpoint.

HS 1296591: OTP/token secret returned to sessions.write API keys

Confirmed on main. Response::output() reveals sensitive fields to any isKey() caller. These endpoints all use the sessions.write scope:

  • POST /v1/account/tokens/email
  • POST /v1/account/tokens/magic-url
  • POST /v1/account/tokens/phone

Their SDK auth is admin, session or JWT only; API keys are not listed. Even so, a key holding just sessions.write (the scope the SSR guide recommends) could mint a token for any email or phone and read the secret from the response. That is account takeover without access to the inbox or phone. POST /v1/account/recovery and POST /v1/account/recovery/otp have the same root cause (same scope, same reveal), and a recovery secret is also a takeover. They are included here as part of the same report, not as new scope.

Product intent: server-side minting of user tokens is meant to go through POST /v1/users/:userId/tokens, which requires users.write. SSR login flows never need the token secret back: the user brings the secret from their inbox or phone.

Fix: these five endpoints return an empty secret when the API key lacks users.write. A key with users.write can already mint a token for any user, so it still gets the secret; the existing testCreateMagicUrl expectation is unchanged. Privileged console roles already hold users.write. Event and webhook payloads are unchanged.

HS 1381840: nested relationship child $permissions self-grant (finding 1)

Confirmed on main. Document create, update and upsert check the root $permissions against $authorization->hasRole(). The relationship walkers never look at the $permissions of a nested related document, so a client could create or update a related document granting roles it does not hold (for example team:x or user:other). TablesDB rows inherit these same actions. Transaction staging (POST /v1/databases/transactions/:id/operations, and the TablesDB subclass) did not walk relationships at all, and commit applies the staged data under the caller's ACL.

Fix: a new validateRelatedPermissions() on the shared Databases\Action base. It validates the format, aggregates write into its sub-types, then requires hasRole() for every role the related document does not already have. Leaving out roles it already has means a client can send a fetched relationship back unchanged without a false 401. It is called from:

  • the Create, Update and Upsert relationship walkers (API keys and privileged users are exempt, same as the root check);
  • transaction operation staging, for create, update and upsert. Here the related document is resolved through TransactionState, so a delete staged in an earlier request already counts;
  • transaction commit (Transactions/Update), which is the authoritative check. Just before each staged create, update or upsert is applied, it walks the nested related documents. It compares their permissions against the related document as it exists inside the commit transaction, after earlier operations have been applied. This closes stage-delete-then-recreate within a single request, across requests, and through cascade deletes. The error is rethrown as a database Authorization exception, so withTransaction() rolls back without retrying and the transaction ends failed with a 401.

Bulk paths are already restricted to keys and admins, and reject relationship collections.

Finding 2 (chunked upload takeover) is already fixed on main by #14014 (assertResumeAllowed), so it is not touched here.

Test Plan

New e2e tests:

  • HS 1005147: TransactionPermissionsBase::testUserCannotReadAnotherUsersStagedDocuments (Legacy, DocumentsDB and TablesDB client). User 1 stages a create and can read it with their own transactionId. User 2 using the leaked transactionId gets 404 on get, and a list without the staged row.
  • HS 1296591:
    • AccountCustomServerTest::testCreateTokenWithSessionsKey. A key with only sessions.write gets an empty secret from email OTP, magic URL, recovery and recovery OTP, and the email is still delivered. The full test key (with users.write) still gets the secret, and the empty secret cannot be turned into a session.
    • MockPhonesSessionIntegrationTest::testMockPhoneSessionWithSessionsKey. A sessions.write key gets an empty secret from the phone token endpoint, the user still signs in with the mock OTP, and the full key still gets the secret.
  • HS 1381840:
    • DatabasesBase::testCreateRelatedPermissions (Legacy and TablesDB on client, server and console sides). On the client, a nested child with the caller's own roles is accepted, and sending existing child permissions back on update is accepted. A nested child with foreign team or user roles is rejected with 401 on create, update and upsert. Servers and consoles still succeed.
    • TransactionPermissionsBase::testCannotSetUnauthorizedRelatedPermissions: staging a create whose nested child has a foreign role returns 401.
    • TransactionPermissionsBase::testCannotRecreateRelatedWithUnauthorizedPermissions. A child holds a foreign role. A delete staged in an earlier request, followed by a nested recreate carrying that role, returns 401 at staging. A delete and recreate in the same request is staged, then the commit returns 401, the transaction is failed, and the child is unchanged. Recreating it with the user's own role commits.

Run locally against a full docker compose stack, with _APP_DOCUMENTSDB=enabled as in CI:

  • The new tests fail without their fixes (source swapped back, tests kept):
    • A foreign staged read returns 200, expected 404.
    • A sessions.write key gets a non-empty secret, including from the phone endpoint.
    • A nested foreign-role child returns 201, expected 401. This happens on Legacy, on TablesDB, and through transaction staging.
    • Delete then recreate: without the staging change, the cross-request case returns 201. Without the commit check, the same-request commit returns 200 and recreates the child with the foreign role.
  • With the fix, these pass:
    • All transaction suites (ACID, permissions, and client, server and console) for Legacy, DocumentsDB and TablesDB.
    • AccountCustomServerTest, AccountCustomClientTest, AccountConsoleClientTest and MockPhonesSessionIntegrationTest.
    • testCreateRelatedPermissions on Legacy and TablesDB for client, server and console, plus the existing relationship tests on the client side.
  • php -l, Pint (--test), PHPStan (project config) on every changed source file, and the Rector dry-run on the changed tests all pass.

Related PRs and Issues

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? (No API metadata changes.)
Open in Web Open in Cursor 

cursoragent and others added 3 commits October 1, 2026 10:06
TransactionState loaded the transaction under Authorization::skip, so any
caller with a leaked transactionId could read another user's staged rows
through document get/list/count. Load it under the caller's ACL unless the
caller is an API key or privileged user, matching the write paths.

Co-authored-by: Jake Barnby <[email protected]>
…ions.write keys

API keys holding only sessions.write could create email OTP, magic URL,
phone and recovery tokens for any address and read the secret straight
from the response, taking over the account without access to the inbox
or phone. Only reveal the secret to keys that already hold users.write,
which can mint tokens for any user anyway.

Co-authored-by: Jake Barnby <[email protected]>
Document create, update and upsert only checked the root $permissions
against the caller's roles, so a related document written through its
parent could carry roles the caller does not hold. Transaction staging
did not look at nested documents at all. Apply the same role check to
every nested related document, ignoring permissions it already has.

Co-authored-by: Jake Barnby <[email protected]>
@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → cursor/security-transaction-otp-nested-perms-8991 (after).

Metric Before After Change
🚀 Requests/sec 203.08 198.3 ⚪ -2.4%
⏱️ Latency P50 85.56 ms 87.19 ms ⚪ +1.9%
⏱️ Latency P95 201.16 ms 204.89 ms ⚪ +1.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 87.19 204.89 12,483 198.3 +3.73
Account 163.79 328.98 657 11.02 +29.06
TablesDB 84.67 162.02 6,789 110.08 +0.66
Storage 78.81 173.34 3,285 54.94 +4.29
Functions 120.86 246.97 1,752 29.85 +4.84

Top API waits (after)

API request Max wait (ms)
account.name.update 546
functions.variables.update 479.12
tablesdb.rows.create 469.97
tablesdb.rows.increment 407.54
account.prefs.update 403.27

@abnegate
abnegate marked this pull request as ready for review October 1, 2026 11:13
@ghost

ghost commented Oct 1, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Adds caller-aware ACL checks for transaction overlays, masks account token and recovery secrets for API keys without users.write, and validates nested relationship permission grants. Transaction validation now considers staged child state and rechecks permissions during commit after preceding operations have applied. E2E coverage includes transaction isolation, unauthorized nested grants and rollback, and restricted-key email and phone token flows.

Latest changes: The newest commits validate nested permissions against staged state and again during commit, add delete/recreate rollback coverage, and test phone secret masking with a sessions.write-only key.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 13
File Change
app/controllers/api/account.php Masks secrets on five token and recovery responses for keys lacking users.write.
app/init/resources/request.php Passes the caller into the transaction-state resource.
src/Appwrite/Databases/TransactionState.php Enforces transaction read ACLs for non-key, non-privileged callers.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php Adds shared nested-permission validation with an existing-permissions exemption.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php Validates nested related-document grants during creation.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php Validates nested related-document grants during updates.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php Validates nested related-document grants during upserts.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Operations/Create.php Recursively validates staged nested grants against transaction-aware child state.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php Revalidates nested grants during commit and rolls back unauthorized writes.
tests/e2e/Services/Account/AccountCustomServerTest.php Tests restricted-key secret masking on email token and recovery routes.
tests/e2e/Services/Databases/DatabasesBase.php Tests nested permission acceptance and rejection across document writes.
tests/e2e/Services/Databases/Transactions/TransactionPermissionsBase.php Tests transaction isolation, nested grants, and delete/recreate rejection with rollback.
tests/e2e/Services/Project/MockPhonesSessionIntegrationTest.php Tests restricted-key phone secret masking, mock OTP login, and users.write secret visibility.

Reviewed the commits since bf11232 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost 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.

🔴 Tier D · 1 blocking finding to address. Summary

Comment thread app/controllers/api/account.php Resolved
abnegate and others added 4 commits October 2, 2026 00:16
…ansaction state

Staging compared nested related-document permissions against the committed
document, so a related document deleted earlier in the transaction could be
recreated on commit with permissions the user does not hold. Staging now reads
the related document through the transaction state, and commit re-checks the
nested permissions against the document as it exists inside the commit
transaction, after earlier operations (including same-batch and cascade
deletes) have been applied.

Co-authored-by: Jake Barnby <[email protected]>
…nested-perms-8991' into cursor/security-transaction-otp-nested-perms-8991

Co-authored-by: Jake Barnby <[email protected]>

@ghost ghost 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.

🟢 Tier S · Looks good to merge. Summary

@cursor

cursor Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Both review findings are addressed. Details are in the inline replies.

  • Transaction stage-delete-then-recreate (critical): valid, fixed in b00cb01.
    • Commit (Transactions/Update) now re-checks nested related $permissions against the related document as it exists inside the commit transaction. That covers deletes staged in the same request, in earlier requests, and cascade deletes.
    • Staging now resolves the related document through TransactionState, so a delete staged in an earlier request is rejected early.
    • New test: testCannotRecreateRelatedWithUnauthorizedPermissions. It fails without either half of the fix.
  • Phone token masking coverage (medium): valid, test added in ff567d7.
    • testMockPhoneSessionWithSessionsKey: a sessions.write key gets an empty secret, the mock OTP login succeeds, and a users.write key still gets the secret.
    • It fails when the phone masking block is removed.

All transaction suites pass for Legacy, DocumentsDB and TablesDB, as do MockPhonesSessionIntegrationTest, Pint, PHPStan and Rector. The PR description is updated to match.

@abnegate
abnegate merged commit 514e2ac into main Oct 1, 2026
58 checks passed
@abnegate
abnegate deleted the cursor/security-transaction-otp-nested-perms-8991 branch October 1, 2026 11:51
Thegreatsura pushed a commit to Thegreatsura/appwrite that referenced this pull request Oct 15, 2026
Main moved 16 pull requests ahead (2aa55a4) and the PR could not merge.

Conflicts keep both sides. Realtime's permission rebuild stays in
Realtime::rebuildConnection, which now keeps every key the connection
handler records (session, impersonator, expiry, JWT expiry, presences)
instead of only authorization, and the session expiry is re-read after it,
as main does. The realtime user factory main split from the store keeps
the uncached, authorization-skipping user load.

Main's nested related-permission check (appwrite#14045) is ported onto
RelationshipValues: for users and guests every nested document's
$permissions are checked against the stored related document at any depth,
through a RelatedPermissions rule that Action::validateRelatedPermissions
shares with the transaction staging and commit checks. Its
Database::VAR_RELATIONSHIP uses become ColumnType::Relationship, which
database 8 replaced it with.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

2 participants