Skip to content

fix: Saving a role clears the entire cache instead of only the cached roles - #10618

Open
AdrianCurtin wants to merge 2 commits into
parse-community:alphafrom
AdrianCurtin:fix_subcache_clear_prefix
Open

AdrianCurtin wants to merge 2 commits into
parse-community:alphafrom
AdrianCurtin:fix_subcache_clear_prefix

Conversation

@AdrianCurtin

@AdrianCurtin AdrianCurtin commented Aug 1, 2026 •

Copy link
Copy Markdown

Pull Request

Issue

Closes #10617.

SubCache#clear() dropped the key prefix that every other method on the class applies, so cacheController.role.clear(), fired on every _Role write, reached the adapter as an unscoped clear. On RedisCacheAdapter that is a raw FLUSHDB, which empties the whole Redis database.

The consequences, in order of how many deployments they touch:

  1. Every _Role write evicts all cached entries for every app on that server, including the <appId>:user:<sessionToken> entries backing session authentication. Apps that create a role per organization, workspace or team at signup destroy their own cache continuously.
  2. Where the cache shares a Redis database with anything else, a job queue, rate limiter state or application data, a single _Role write deletes that data too.
  3. Where an app's CLP permits non-master-key _Role writes, any client can trigger FLUSHDB at will.

Approach

Scoped clearing is added as an optional part of the CacheAdapter contract, so third-party adapters keep working unchanged.

  • CacheAdapter#clear(prefix) documents the new optional parameter. An adapter that ignores it empties the whole cache, which is exactly today's behavior.
  • SubCache#clear() passes its prefix, so role.clear() resolves to <appId>:role.
  • CacheController#clear(prefix) joins the app id, so it resolves to <appId> or <appId>:<prefix>.
  • RedisCacheAdapter#clear(prefix) iterates SCAN with MATCH <prefix>:* and removes matches with UNLINK, glob-escaping the prefix so an app id containing *, ?, [ or ] cannot widen the pattern. It keeps the existing KeyPromiseQueue barrier. Called with no prefix it still issues FLUSHDB.
  • InMemoryCacheAdapter and LRUCache filter their own keys by prefix.

One scope limit worth stating: the in-memory adapter is per-process by construction, so on a multi-node deployment a clear still only evicts the node that handled the write. This PR narrows what a clear destroys, not how far it reaches, and Redis, being shared, is invalidated for the whole cluster.

Worth flagging for review: CacheController#clear() with no arguments now scopes to the app id rather than emptying the adapter outright. Nothing in the codebase relied on the wider behavior, and TestUtils calls cacheAdapter.clear() on the adapter directly, so test teardown still performs a full flush.

SCAN is only reached on role writes and purges, which are rare, and it uses UNLINK so the deletion itself does not block the server.

This continues the direction of #3523, which narrowed the adapter from FLUSHALL to FLUSHDB. Narrowing once more, to the key prefix, drops the remaining assumption that Parse Server exclusively owns the Redis database.

Tests

  • spec/CacheController.spec.js asserts each sub-cache clears under its own <appId>:<prefix> scope, and adds an end-to-end regression test that a _Role save leaves a cached user entry intact. That test fails on alpha with Expected null to equal Object({ objectId: 'someUser' }) and passes here. It runs against the in-memory adapter by default and against Redis under PARSE_SERVER_TEST_CACHE=redis.
  • spec/RedisCacheAdapter.spec.js asserts a scoped clear removes only its own prefix while leaving another app's keys and an unrelated queue:default key in place, that an unscoped clear still empties everything, and that glob characters in a prefix are treated literally.
  • spec/InMemoryCacheAdapter.spec.js covers the same scoping for the default adapter.

Tasks

  • Add tests
  • Add changes to documentation (code comments)

Summary by CodeRabbit

  • New Features

    • Added scoped cache clearing by application and sub-cache prefix.
    • Clearing a sub-cache now preserves unrelated cached data.
    • Cache clearing supports targeted removal or clearing the entire cache.
  • Bug Fixes

    • Improved handling of special characters in Redis cache keys to avoid unintended matches.
    • Prevented unrelated entries from being removed during targeted cache clearing.
  • Tests

    • Added coverage for scoped clearing across in-memory, Redis, and controller-level caches.

Copilot AI review requested due to automatic review settings August 1, 2026 04:59
@parse-github-assistant

Copy link
Copy Markdown

I will reformat the title to use the proper commit message syntax.

@parse-github-assistant parse-github-assistant Bot changed the title fix: saving a role clears the entire cache instead of only the cached roles fix: Saving a role clears the entire cache instead of only the cached roles Aug 1, 2026
@parse-github-assistant

Copy link
Copy Markdown

🚀 Thanks for opening this pull request! We appreciate your effort in improving the project. Please let us know once your pull request is ready for review.

Tip

  • Keep pull requests small. Large PRs will be rejected. Break complex features into smaller, incremental PRs.
  • Use Test Driven Development. Write failing tests before implementing functionality. Ensure tests pass.
  • Group code into logical blocks. Add a short comment before each block to explain its purpose.
  • We offer conceptual guidance. Coding is up to you. PRs must be merge-ready for human review.
  • Our review focuses on concept, not quality. PRs with code issues will be rejected. Use an AI agent.
  • Human review time is precious. Avoid review ping-pong. Inspect and test your AI-generated code.

Note

Please respond to review comments from AI agents just like you would to comments from a human reviewer. Let the reviewer resolve their own comments, unless they have reviewed and accepted your commit, or agreed with your explanation for why the feedback was incorrect.

Caution

Pull requests must be written using an AI agent with human supervision. Pull requests written entirely by a human will likely be rejected, because of lower code quality, higher review effort and the higher risk of introducing bugs. Please note that AI review comments on this pull request alone do not satisfy this requirement. Our CI and AI review are safeguards, not development tools. If many issues are flagged, rethink your development approach. Invest more effort in planning and design rather than using review cycles to fix low-quality code.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 14ae47a7-43f8-42a4-9be6-8cc30be0fc0d
📥 Commits

Reviewing files that changed from the base of the PR and between 607bb56 and 4ed9f09.

📒 Files selected for processing (2)
  • spec/InMemoryCacheAdapter.spec.js
  • src/Adapters/Cache/LRUCache.js

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

Cache clearing now accepts application and subcache prefixes. Cache adapters remove matching keys when given a prefix, while unscoped clearing retains full-cache behavior. Tests cover prefix isolation and role-cache invalidation without removing cached users.

Changes

Scoped cache clearing

Layer / File(s) Summary
Controller scope propagation
src/Controllers/CacheController.js, src/Adapters/Cache/CacheAdapter.js
SubCache.clear() and CacheController.clear(prefix) pass application and subcache prefixes to the adapter. The adapter contract documents optional scoped clearing.
Adapter-scoped deletion
src/Adapters/Cache/InMemoryCacheAdapter.js, src/Adapters/Cache/LRUCache.js, src/Adapters/Cache/RedisCacheAdapter.js
In-memory and LRU caches remove keys that match a prefix. Redis scans for matching keys using an escaped pattern, then removes them with UNLINK. Without a prefix, Redis retains its FLUSHDB behavior.
Scoped clearing validation
spec/CacheController.spec.js, spec/InMemoryCacheAdapter.spec.js, spec/RedisCacheAdapter.spec.js
Tests verify prefix isolation, literal wildcard handling, unscoped clearing, and role-cache invalidation without removing cached users.

Priority: ⬆️ High

Estimated code review effort: 3 (Moderate) | ~20 minutes

Severity of issue fixed: High

Suggested reviewers: mtrezza

Merge Risk: ⚪ Minimal · up to 4ed9f

Scoped cache clearing preserves unrelated entries in the supplied coverage, and no merge-blocking issue remains.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 4ed9f

Scoped clearing substantially reduces accidental deletion across applications and unrelated Redis data. However, Redis clearing becomes a multi-step operation that role writes do not wait for, potentially extending the period in which revoked roles remain usable. The practical exposure depends on cache size, concurrency, expiration settings, and Redis failures.

Retained concerns

  • Medium · security · inferred: Redis role invalidation now requires multiple asynchronous scan and deletion commands, while role persistence proceeds without awaiting completion. Cached role memberships can therefore remain available after a successful role update until their batch is deleted or they expire; an interrupted clear can leave only part of the namespace invalidated. This adds scan-duration exposure and partial-completion states to the pre-existing unawaited invalidation race.
Security review details

Security Blast Radius

  • inferred — For non-overlapping application namespaces using the built-in adapters, role-write eviction narrows from the entire backend to that application's role keys. The authorization concern affects users relying on cached roles in the application whose role state changes; Redis scan work still traverses the selected database. Actual shared-database and multi-server deployment exposure is unknown.

Security Findings and Attack Paths

  • inferred — A user with a valid session and previously cached role membership could continue requesting role-protected reads or writes after membership is revoked while the Redis clear has not reached that key, or if clearing fails before deleting it. Auth accepts the cached list without rechecking membership. The PR extends invalidation into multiple commands; the underlying unawaited, pre-persistence race predates it. This is a conditional architecture concern, not a demonstrated exploit.

Trust Boundaries and Controls

  • observed — Application identity comes from server configuration and is passed directly into CacheController. Redis escapes glob metacharacters, and LRU matching is literal. The inspected application-ID character check warns rather than rejects colon-containing IDs.
  • inferred — Delimiter-based namespaces can overlap when application IDs contain colons, so scoped clearing is not an unconditional isolation guarantee for arbitrary configured IDs. This is residual exposure rather than a PR-introduced deletion vulnerability: the base cleared the entire backend, and the key delimiter itself is unchanged.

Resilience and Maintainability Implications

  • observed — The Redis queue does not encompass the SCAN/UNLINK operation or coordinate it with role-key writes. Clear has no local retry or compensation path for partial progress, and the role-write caller does not observe its completion. Redis entries normally expire using the adapter TTL, which defaults to 30 seconds; explicit Infinity values are stored without expiration.

Hardening Proposals

  • proposed — Consider generation-based role-cache invalidation tied to successful role updates, so old authorization data becomes unusable independently of physical key deletion. Validate the intended revocation point under concurrent cache population, repeated clears, and interrupted Redis operations.
🚥 Pre-merge checks | ✅ 6 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (6 passed)
Check name Status Explanation
Title check ✅ Passed The title begins with the required fix: prefix, capitalizes the first word after the prefix, and clearly describes the cache-clearing fix.
Description check ✅ Passed The description includes the required sections, identifies the linked issue, explains the approach, and describes tests. It also marks the applicable test and documentation tasks complete.
Linked Issues check ✅ Passed Issue #10617 requires role-subcache clears to preserve other subcaches, apps, and unrelated Redis keys. SubCache.clear() and CacheController.clear() pass app and subcache scopes to the adapter. Th…
Out of Scope Changes check ✅ Passed The changes are limited to cache-clear scoping, adapter implementations, related documentation, and regression tests. Each change supports issue #10617; no unrelated changes are present in the reviewe…
Security Check ✅ Passed The changes do not introduce an evident security vulnerability. RedisCacheAdapter.clear(prefix) escapes Redis glob metacharacters before using SCAN MATCH, then removes only matching keys with `UNL…
Engage In Review Feedback ✅ Passed No review feedback requires engagement. The supplied current review produced zero actionable findings, and no posted CodeRabbit review threads were returned.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

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

Copilot AI 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.

Pull request overview

This PR fixes a cache-clearing security/availability issue where saving a _Role could clear the entire cache backend (including unrelated keys), by introducing scoped cache clearing via optional key-prefix support across the cache controller and adapters.

Changes:

  • Extend the cache adapter contract so clear(prefix) can optionally clear only keys under <prefix>:*, while preserving legacy “clear everything” behavior when called without a prefix.
  • Fix SubCache#clear() / CacheController#clear() to pass the appropriate scope (<appId>:<subcache>), preventing role saves from flushing unrelated caches.
  • Implement scoped clearing for Redis (SCAN + UNLINK) and in-memory caches, and add regression/unit tests for scoped behavior.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/Controllers/CacheController.js Passes sub-cache/app scopes into clear(prefix) to avoid unscoped adapter clears.
src/Adapters/Cache/RedisCacheAdapter.js Adds scoped Redis clearing using SCAN + UNLINK, retaining FLUSHDB for unscoped clears.
src/Adapters/Cache/LRUCache.js Adds prefix-scoped key removal for the in-memory LRU store.
src/Adapters/Cache/InMemoryCacheAdapter.js Threads clear(prefix) through to the underlying in-memory cache implementation.
src/Adapters/Cache/CacheAdapter.js Documents and exposes optional clear(prefix) parameter in the adapter contract.
spec/RedisCacheAdapter.spec.js Adds tests ensuring scoped clear only removes matching prefixes and treats glob chars literally.
spec/InMemoryCacheAdapter.spec.js Adds tests ensuring scoped clear only removes matching prefixes for in-memory adapter.
spec/CacheController.spec.js Adds tests verifying controller/sub-cache scoping and regression test for _Role save not evicting cached users.
Suppressed comments (1)

src/Controllers/CacheController.js:74

  • The JSDoc for CacheController#clear() says other Parse apps' keys are left untouched, but that depends on the adapter honoring the optional prefix parameter. For adapters that ignore the parameter, this may still clear the whole cache backend.
  /**
   * Empty this app's cache. Keys belonging to other Parse apps sharing the
   * same cache backend are left untouched.
   *
   * @param {String} prefix Optional sub-cache prefix to narrow the scope

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/Controllers/CacheController.js

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

🧹 Nitpick comments (2)
src/Adapters/Cache/RedisCacheAdapter.js (1)

92-113: 🩺 Stability & Availability | 🔵 Trivial

Scoped clear implementation is correct.

The SCAN cursor handling, glob escaping, and colon-boundary scoping are correct and match documented node-redis v5 behavior. One point worth noting for future maintainers: SCAN provides only an eventually-consistent view of the keyspace. A key written to the target scope after its hash slot is already scanned can survive this clear. This is an accepted trade-off of SCAN+UNLINK over blocking KEYS+DEL, not a defect, but it means a _Role save that races with a fresh cache write to the same role key has a narrow window where the stale entry is not removed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Adapters/Cache/RedisCacheAdapter.js` around lines 92 - 113, No code
change is required; retain the current scoped clear implementation in clear,
including SCAN cursor handling, glob escaping, colon-boundary matching, and
UNLINK behavior, while accepting the documented race window for keys written
during the scan.
spec/CacheController.spec.js (1)

79-92: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace the fixed 200ms sleep with a poll-based wait.

The test waits a fixed 200ms for RestWrite's un-awaited role-cache clear to complete. A fixed sleep is a known source of CI flakiness: too short under load and the assertion fails spuriously, too long and the test wastes time. Poll cacheController.role.get('someUser') in a short loop until it resolves to null or a bounded timeout elapses, instead of a single fixed delay.

♻️ Proposed polling-based wait
-    await new Parse.Role('Admin', new Parse.ACL()).save(null, { useMasterKey: true });
-    // The role cache is cleared without being awaited by RestWrite.
-    await new Promise(resolve => setTimeout(resolve, 200));
-
-    expect(await cacheController.role.get('someUser')).toEqual(null);
+    await new Parse.Role('Admin', new Parse.ACL()).save(null, { useMasterKey: true });
+    // The role cache is cleared without being awaited by RestWrite; poll instead of a fixed sleep.
+    const deadline = Date.now() + 2000;
+    let roleCacheEntry;
+    do {
+      roleCacheEntry = await cacheController.role.get('someUser');
+    } while (roleCacheEntry !== null && Date.now() < deadline);
+
+    expect(roleCacheEntry).toEqual(null);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@spec/CacheController.spec.js` around lines 79 - 92, Replace the fixed 200ms
timeout in the “should not evict cached users when a _Role is saved” test with
bounded polling of cacheController.role.get('someUser'). Repeatedly check at a
short interval until the value is null, while enforcing a maximum timeout so the
test cannot wait indefinitely, then retain the existing role and user cache
assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@spec/CacheController.spec.js`:
- Around line 79-92: Replace the fixed 200ms timeout in the “should not evict
cached users when a _Role is saved” test with bounded polling of
cacheController.role.get('someUser'). Repeatedly check at a short interval until
the value is null, while enforcing a maximum timeout so the test cannot wait
indefinitely, then retain the existing role and user cache assertions.

In `@src/Adapters/Cache/RedisCacheAdapter.js`:
- Around line 92-113: No code change is required; retain the current scoped
clear implementation in clear, including SCAN cursor handling, glob escaping,
colon-boundary matching, and UNLINK behavior, while accepting the documented
race window for keys written during the scan.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 89cbb037-46b2-47e0-b4ab-f1a90dfef304

📥 Commits

Reviewing files that changed from the base of the PR and between 315e157 and d4e08df.

📒 Files selected for processing (8)
  • spec/CacheController.spec.js
  • spec/InMemoryCacheAdapter.spec.js
  • spec/RedisCacheAdapter.spec.js
  • src/Adapters/Cache/CacheAdapter.js
  • src/Adapters/Cache/InMemoryCacheAdapter.js
  • src/Adapters/Cache/LRUCache.js
  • src/Adapters/Cache/RedisCacheAdapter.js
  • src/Controllers/CacheController.js

@AdrianCurtin
AdrianCurtin force-pushed the fix_subcache_clear_prefix branch from 607bb56 to 4ed9f09 Compare October 6, 2026 12:08

This branch has not been deployed

No deployments
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.

Saving a _Role clears the entire cache, issuing FLUSHDB on the Redis cache adapter

2 participants