Skip to content

fix(auth,databases): restrict account keys to console; gate increment/decrement; fix upsert perms; drop guest embeddings - #14755

Merged
ArnabChatterjee20k merged 3 commits into
mainfrom
security/db-document-authz
Oct 22, 2026
Merged

ArnabChatterjee20k merged 3 commits into
mainfrom
security/db-document-authz

Conversation

@ArnabChatterjee20k

Copy link
Copy Markdown
Member

What

Authorization and isolation fixes on the Databases document surface and the shared auth gate, each with a regression that fails before the change and passes after.

Account API keys restricted to the console project (Critical)

An account API key has an empty projectId, so the project-binding check was skipped and the API_KEY_ACCOUNT branch injected the console user's roles — user:{id}, users, team:{orgId} for each confirmed org membership — into any target project's authorization. Console user and organization IDs are caller-chosen, so they can be made to collide with a target project's own user/team IDs. Fix: reject account keys on any project other than console, in both the HTTP auth gate and the realtime connection resource. Also tightens the project-scoped admin role match to require an exact project-{projectId}- delimiter (a prefix like project-app2-owner previously matched project app); this one is defense-in-depth — the admin-mode project-read gate already blocks cross-project data access.

Increment/decrement honor the enabled flag

These two actions skipped the enabled gate that every other document action applies, so a client with update permission kept mutating numeric attributes in a disabled database/collection. Now 404 for non-privileged callers, like the sibling actions. Inherited by the DocumentsDB and TablesDB subclasses.

Upsert no longer re-validates inherited permissions

When no permissions were supplied, upsert inherited the existing document's permissions and then ran the grant role-check over them, wrongly refusing a user who could update a shared document whose stored permissions named another role. Now only caller-supplied permissions are checked (parity with update).

Guests lose embeddings.write

Embedding generation is backed compute with no per-resource gate; an unauthenticated caller who knew a public project ID could drive the backend. Removed from the guests role.

Tests

  • AccountKeyCrossProjectTest (added in the Cloud repo, where account-key creation lives): console key works, customer-project use refused — covers the fix here.
  • DatabasesBase::testDisabledCollectionBlocksIncrement (Legacy + DocumentsDB): increment on a disabled collection 200 → 404.
  • DatabasesBase::testUpsertDoesNotRevalidateInheritedPermissions (Legacy + DocumentsDB): legitimate upsert of a shared document 401 → 200.
  • Embeddings/GuestEmbeddingsTest: guest POST /v1/embeddings/text is 401.

🤖 Generated with Claude Code

…/decrement, fix upsert perms, drop guest embeddings

- Account API keys are refused on any project other than console, in the HTTP auth
  gate and the realtime connection resource. Previously an account key (empty
  projectId) injected the console user's roles into any target project, where
  caller-chosen console user/org IDs can collide with a project's user/team IDs.
  Also tightens the project-scoped admin role match to require an exact
  'project-{projectId}-' delimiter (defense-in-depth).
- Increment/decrement now honor the database and collection enabled flag for
  non-privileged callers, like every other document action.
- Upsert role-checks only caller-supplied permissions, not permissions inherited
  from the existing document (parity with update).
- Remove embeddings.write from the guests role; embedding generation is backed
  compute with no per-resource gate.

Refs appwrite-labs/cloud#6747, appwrite-labs/cloud#6749, appwrite-labs/cloud#6752, appwrite-labs/cloud#6753, appwrite-labs/cloud#6754

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Realtime silently downgrades account keys instead of rejecting — connection.php:289
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Account key state mutates before non-console guard rejects (api.php:255) — For an account key used against a non-console project, the new rejection at app/controllers/shared/api.php:260 runs only after the key-lookup block has already updated accessedAt, appended the caller's x-sdk-name to the key's sdks, persisted the key document on the platform DB, and purged the owner's platform cache (app/controllers/shared/api.php:175-233).

The change tightens auth boundaries and fixes two permission-model defects. Account API keys are now rejected on non-console projects in the REST auth path, with a matching (but looser) guard in realtime, and the project- role prefix computation is fixed. The guests role loses embeddings.write, and the guest embeddings e2e test is updated to expect rejection. On the Databases surface, increment/decrement now honor the collection enabled flag with 404 responses matching sibling endpoints, and upsert only role-checks caller-supplied permissions rather than inherited ones. Regression tests cover all three behavior changes.

Files Change
app/controllers/shared/api.php, app/init/realtime/connection.php Reject account API keys outside the console project; fix project- role prefix parsing.
app/config/roles.php, tests/e2e/Services/Databases/Embeddings/GuestEmbeddingsTest.php Remove embeddings.write from the guests role; update the guest embeddings test to expect 401.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php, .../Decrement.php Enforce the collection enabled gate (404) before mutating documents.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php Run the permission grant role-check only on caller-supplied permissions.
tests/e2e/Services/Databases/DatabasesBase.php Add regression tests for the enabled gate and upsert permission behavior.

Reviewed commit: 70ebe83

@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The authorization and database behavior changes are covered by focused regressions, and I found no remaining correctness issues.

The change confines account API key authentication to the console in HTTP and realtime, tightens project-specific admin role matching, and removes embedding generation from guest scopes. It also applies enabled checks to document increment/decrement and avoids rechecking inherited upsert permissions, with regression coverage for these behaviors.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 9
File Change
app/config/roles.php Removes the embedding-write scope from the guest role.
app/controllers/shared/api.php Restricts account keys to the console project and requires exact project-specific admin role matching.
app/init/realtime/connection.php Rejects account-key realtime connections outside the console project.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Decrement.php Applies database and collection enabled checks to decrement.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php Applies database and collection enabled checks to increment.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php Role-checks only permissions supplied by the caller, not inherited permissions.
tests/e2e/Services/Databases/DatabasesBase.php Adds regressions for disabled collection increments/decrements and upserting documents with inherited permissions.
tests/e2e/Services/Databases/Embeddings/GuestEmbeddingsTest.php Adds a guest access regression test for text embeddings.
tests/e2e/Services/Projects/ProjectsConsoleClientTest.php Adds a regression test for project-specific role prefix collisions.

Reviewed 4006c5e · 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 A · See the inline comments. Summary

Comment thread app/init/realtime/connection.php Resolved
Comment thread app/controllers/shared/api.php Resolved
@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot 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.

This PR restricts account API keys to the console project, removes embeddings.write from the guests role, enforces the collection enabled gate on increment/decrement, and stops upsert from re-validating inherited permissions.

Key findings

  • 🟡 Realtime silently downgrades account keys instead of rejecting — connection.php:289

Comment thread app/init/realtime/connection.php Outdated
Comment on lines 289 to 291
if (!empty($accountKeyUserId) && !empty($accountKey) && $project->getId() === 'console') {
if (!$user->isEmpty()) {
throw new Exception(Exception::USER_API_KEY_AND_SESSION_SET);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Realtime silently downgrades account keys instead of rejecting

The PR rejects account API keys on non-console projects in app/controllers/shared/api.php:260 by throwing USER_UNAUTHORIZED, but the parallel realtime guard wraps the whole account-key block in a $project->getId() === 'console' condition, so on any other project the block is skipped rather than rejected (app/init/realtime/connection.php:289). A realtime connection presenting an account key therefore proceeds as a guest (or with an unrelated session) with no error, and the USER_API_KEY_AND_SESSION_SET conflict check is also skipped, so a session+key combination is accepted there but rejected on every REST route. Realtime clients get silently unauthenticated subscriptions instead of the 401 the REST surface returns for the same credentials.

📋 Prompt for AI Agents

In app/init/realtime/connection.php around lines 284-307, restructure the account-key block so that when both x-appwrite-user and x-appwrite-key headers are non-empty and the project is not 'console', the code throws new Exception(Exception::USER_UNAUTHORIZED, 'Account API keys can only be used with the console project.') — matching the guard added in app/controllers/shared/api.php around line 260. Keep the existing console-project branch (the USER_API_KEY_AND_SESSION_SET conflict check, key lookup, and expiry check) unchanged for the console project.

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → security/db-document-authz (after).

Metric Before After Change
🚀 Requests/sec 199.81 210.42 🟢 +5.3%
⏱️ Latency P50 85.86 ms 80.37 ms 🟢 -6.4%
⏱️ Latency P95 206.87 ms 195.69 ms 🟢 -5.4%
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 80.37 195.69 13,509 210.42 -11.18
Account 159.24 314.54 711 11.78 +12.5
TablesDB 77.14 147.9 7,347 117.87 -18.88
Storage 75.42 175.96 3,555 58.23 -13.61
Functions 119.47 239.08 1,896 31.65 +5.46

Top API waits (after)

API request Max wait (ms)
account.name.update 613.48
functions.variables.create 446.34
functions.create 419.17
account.prefs.update 418.62
storage.buckets.create 357.49

… ignoring them

The realtime guard wrapped the whole account-key block in a console-project
condition, so on any other project the credentials were silently skipped: a
key-only client fell through to a guest connection and a key+session request
avoided the mutual-authentication error. Reject them with USER_UNAUTHORIZED,
matching the HTTP auth gate.

Addresses review on #14755.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Addressed the two findings:

  1. Realtime account keys (connection.php:289) — fixed in b1957e1. Non-console projects now throw USER_UNAUTHORIZED for account-key headers instead of silently skipping the block, matching the HTTP gate (no guest fall-through, no skipped key+session conflict check).

  2. Project-role prefix collision test (api.php:321) — the delimiter fix is kept as defense-in-depth, but I could not add a meaningful cross-project data-access regression, and here's why: admin-mode requests on a non-console project are independently gated, in the same init hook, by the project-read check against $project->getPermissionsByType(Read), whose permissions are team:{teamId}/project-{projectId}-{role} — bound to the exact project ID. A member holding only project-{B}-owner hitting sibling project A gets 404 both before and after this change (verified live), because the leaked bare owner role never satisfies project A's read permission. So the prefix bug grants no observable cross-project access, and a data-access e2e would pass identically with or without the fix. If you'd prefer, I can add a unit-level assertion on the role-derivation instead — happy to, just flagging that the e2e angle can't distinguish it.

@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 A · Looks good to merge. Summary

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@hansi-codes review

All prior findings are resolved. What would it take for this PR to reach Tier S rather than Tier A?

@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 A · Looks good to merge. Summary

Adds testProjectSpecificPermissionsPrefixCollision: two projects whose IDs are
prefix siblings (A is a prefix of B), a member granted project-{B}-owner, asserting
they see and can read B only, never A. Locks in the cross-project authorization
boundary the exact 'project-{projectId}-' delimiter match protects.

Addresses review on #14755.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Added testProjectSpecificPermissionsPrefixCollision (Projects console suite): two prefix-sibling projects (A is a prefix of B), a member granted project-{B}-owner, asserting they see/read B only, never A.

One honest caveat on this boundary: the project list/read filter matches the member's team role (team:{T}/project-{B}-owner), which never matches project A's read permission, so this boundary holds independently of the admin-role prefix match. The delimiter fix is therefore defense-in-depth, and this test documents/guards the boundary rather than isolating the prefix logic alone. Happy to also add a focused unit test if you'd like the prefix parse covered in isolation.

@hansi-codes review

@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

@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

@ArnabChatterjee20k
ArnabChatterjee20k merged commit bb790c1 into main Oct 22, 2026
68 checks passed
ChiragAgg5k pushed a commit that referenced this pull request Oct 24, 2026
…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)
ChiragAgg5k pushed a commit that referenced this pull request Oct 24, 2026
…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)
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
…authz

fix(auth,databases): restrict account keys to console; gate increment/decrement; fix upsert perms; drop guest embeddings

(cherry picked from commit bb790c1)
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