Skip to content

fix: match Mongo document permissions with exact strings - #940

Merged
abnegate merged 1 commit into
mainfrom
fix/mongo-permission-exact-match
Aug 19, 2026
Merged

fix: match Mongo document permissions with exact strings#940
abnegate merged 1 commit into
mainfrom
fix/mongo-permission-exact-match

Conversation

@abnegate

@abnegate abnegate commented Aug 19, 2026

Copy link
Copy Markdown
Member

Problem

With document authorization enabled, the Mongo adapter built a regex from the caller’s role strings and used it as the _permissions $in filter in find(), count(), and sum():

$roles = implode('|', $this->authorization->getRoles());
$filters['_permissions']['$in'] = [new Regex("{$forPermission}\\(\"(?:{$roles})\"\\)", 'i')];

Role identifiers are user-controlled (user:<id>, team:<id>) and Key / UID / Appwrite CustomId all allow ., which is the regex any-char wildcard. The i flag also made matching case-insensitive.

PoC (confirmed):

  • Attacker role user:alice. matches read("user:alice0") and read("user:alice9")
  • Attacker role user:a + 19 dots matches any 20-char owner ID starting with a
  • SQL adapters are not affected (exact IN on the perms table)

Fix

Build $in over exact permission strings (read("<role>")) at all three call-sites. No Regex, no i flag.

Tests

  • Unit: period padding and multi-role output is exact strings
  • E2E: user:alice. cannot list/count/sum foreign docs; user:a+19 dots cannot mass-read; legitimate user:alice0 still works
  • Regression: the new e2e fails on Mongo without this change (alice. leaked alice0 and alice9)

Summary by CodeRabbit

  • Bug Fixes

    • Improved permission matching for MongoDB-backed data.
    • Roles are now matched exactly, including punctuation, capitalization, long names, and special characters.
    • Prevented partial or pattern-like role matches across document retrieval, counting, aggregation, and lookup operations.
  • Tests

    • Added coverage for exact role matching and permission-string generation across supported scenarios.

find/count/sum assembled an unescaped, case-insensitive regex from the
caller's roles. Role IDs may contain `.`, so a custom userId of
`alice.` matched every `read("user:alice?")` document. SQL already uses
an exact IN list; Mongo now does the same.
@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f1f054b4-41d4-4b12-a860-34785144e6a3

📥 Commits

Reviewing files that changed from the base of the PR and between 4f50112 and d46283d.

📒 Files selected for processing (3)
  • src/Database/Adapter/Mongo.php
  • tests/e2e/Adapter/Scopes/PermissionTests.php
  • tests/unit/MongoPermissionStringsTest.php

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

MongoDB permission filters now use exact generated permission strings instead of case-insensitive regular expressions. Unit and end-to-end tests cover role formatting, case sensitivity, punctuation, and query operations.

Changes

Exact permission matching

Layer / File(s) Summary
Generate and apply exact permission filters
src/Database/Adapter/Mongo.php
The adapter generates permission strings for authorized roles. The find, count, and sum filters use exact $in matching.
Validate exact role behavior
tests/unit/MongoPermissionStringsTest.php, tests/e2e/Adapter/Scopes/PermissionTests.php
Tests cover permission-string generation and exact document matching across listing, counting, aggregation, and retrieval.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to d4628

This change makes Mongo document permission matching exact instead of regex-based and adds regression coverage; no actionable merge-blocking risk remains after normal checks and review.

Possibly related PRs

Suggested reviewers: fogelito

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: exact-string matching for Mongo document permissions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/mongo-permission-exact-match

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR replaces MongoDB’s role-derived, case-insensitive permission regexes with exact permission-string filters, preventing regex metacharacters in role identifiers from broadening document access.

  • Adds a shared helper that maps authorization roles to canonical permission strings.
  • Applies exact matching to Mongo find(), count(), and sum().
  • Adds unit and end-to-end coverage for dotted roles, mass-match attempts, multiple roles, case sensitivity, and legitimate access.

Confidence Score: 5/5

The PR appears safe to merge, with the authorization fix consistently applied and no actionable regressions identified.

Exact permission strings match the repository’s canonical persisted encoding, and the changed find, count, and sum paths preserve legitimate role behavior while removing regex-based overmatching.

Important Files Changed

Filename Overview
src/Database/Adapter/Mongo.php Replaces unsafe regex authorization filters with exact canonical permission strings consistently across all three affected Mongo read and aggregation paths.
tests/e2e/Adapter/Scopes/PermissionTests.php Adds end-to-end regression coverage showing dotted attacker roles cannot list, count, sum, or fetch foreign documents while legitimate exact roles still work.
tests/unit/MongoPermissionStringsTest.php Verifies exact helper output for dotted, padded, case-sensitive, multiple, and empty role sets.

Reviews (1): Last reviewed commit: "fix: match Mongo document permissions wi..." | Re-trigger Greptile

@abnegate
abnegate merged commit 1550238 into main Aug 19, 2026
22 checks passed
@abnegate
abnegate deleted the fix/mongo-permission-exact-match branch August 19, 2026 08:44
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.

1 participant