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

fix: Saving a role clears the entire cache instead of only the cached roles#10618
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.

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 both targeted removal and full-cache clearing.
  • Bug Fixes

    • Improved handling of special characters in Redis cache keys.
    • Prevented unrelated entries from being removed during targeted cache operations.
  • 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 Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9dd7ee29-7ac7-470e-9146-34f218615b29

📥 Commits

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

📒 Files selected for processing (1)
  • src/Controllers/CacheController.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Controllers/CacheController.js

📝 Walkthrough

Walkthrough

Scoped cache clearing now accepts application and subcache prefixes. Cache adapters delete only matching keys when a prefix is provided. Unscoped clearing retains full-cache behavior. Tests cover prefix isolation and role-cache invalidation.

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) now 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
Adapters now remove keys matching a prefix. Redis uses escaped SCAN patterns and UNLINK. Unscoped clearing retains full-cache behavior.
Scoped clearing validation
spec/CacheController.spec.js, spec/InMemoryCacheAdapter.spec.js, spec/RedisCacheAdapter.spec.js
Tests verify prefix isolation, literal wildcard handling, full clearing, and role-cache invalidation without removing cached users.

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

Sequence Diagram(s)

sequenceDiagram
  participant SubCache
  participant CacheController
  participant RedisCacheAdapter
  participant Redis
  SubCache->>CacheController: clear(appId:subcachePrefix)
  CacheController->>RedisCacheAdapter: clear(prefix)
  RedisCacheAdapter->>Redis: SCAN matching escaped prefix
  RedisCacheAdapter->>Redis: UNLINK matching keys
Loading

Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Security Check ❓ Inconclusive Evidence gathering is still in progress. Inspect Redis matching and authorization cache behavior before deciding.
Engage In Review Feedback ❓ Inconclusive The repository shows an implementation commit and a follow-up “Adjust comments per copilot” commit, but no review threads or discussion records; GitHub metadata returned 403. Provide the PR review comments and author responses, including evidence that each comment was implemented or retracted after discussion.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title uses the required fix: prefix, starts with a capitalized word, and accurately describes the cache-clearing bug fix.
Description check ✅ Passed The description includes the required sections, explains the issue and approach, and documents completed tests and code comments.
Linked Issues check ✅ Passed The implementation addresses issue [#10617] by scoping cache clears, preserving compatibility, protecting Redis keys, and adding regression tests.
Out of Scope Changes check ✅ Passed All production and test changes directly support the scoped cache-clearing fix described in issue [#10617].
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

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 on lines +37 to 41
/**
* Empty this sub-cache, leaving keys owned by other sub-caches, other Parse
* apps, and other consumers of the same cache backend untouched.
*/
clear() {

@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

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