Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 185 additions & 17 deletions ProcessMaker/Cache/Settings/SettingCacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ class SettingCacheManager extends CacheManagerBase implements CacheInterface

const DEFAULT_CACHE_PREFIX = 'settings:';

/**
* Envelope marker so cached null is distinguishable from a Laravel cache miss.
*/
private const ENVELOPE_FLAG = '__pm_setting';

protected CacheManager $manager;

protected Repository $cacheManager;
Expand All @@ -28,8 +33,6 @@ public function __construct(CacheManager $cacheManager)
/**
* Determine and set the cache driver to use.
*
* @param CacheManager $cacheManager
*
* @return void
*/
private function setCacheDriver(): void
Expand All @@ -44,14 +47,10 @@ private function setCacheDriver(): void
}

/**
* Create a cache key for a screen
* Create a cache key for a setting.
*
* @param int $processId Process ID
* @param int $processVersionId Process Version ID
* @param string $language Language code
* @param int $screenId Screen ID
* @param int $screenVersionId Screen Version ID
* @return string The generated cache key
* @param array $params
* @return string
*/
public function createKey(array $params): string
{
Expand Down Expand Up @@ -88,7 +87,94 @@ public function __call($method, $arguments): mixed
*/
public function get(string $key, mixed $default = null): mixed
{
return $this->cacheManager->get($key, $default);
SettingMemoryCache::syncEpoch();

$value = $default;

if (!SettingMemoryCache::isEpochUnreliable()) {
if (SettingMemoryCache::exists($key)) {
$value = SettingMemoryCache::get($key);
} else {
$entry = $this->readStoreEntry($key);
if ($entry['hit']) {
SettingMemoryCache::put($key, $entry['value']);
$value = $entry['value'];
}
}
}

return $value;
}

/**
* Resolve a setting from L1, then Redis, then the loader (typically DB).
*
* @param string $key
* @param callable $loader
*
* @return mixed
*/
public function resolve(string $key, callable $loader): mixed
{
SettingMemoryCache::syncEpoch();

// Freshness oracle unavailable: fail closed to DB, do not trust L1/L2.
if (SettingMemoryCache::isEpochUnreliable()) {
return $loader();
}

if (SettingMemoryCache::exists($key)) {
return SettingMemoryCache::get($key);
}

return $this->resolveCacheMiss($key, $loader);
}

/**
* Resolve after an L1 miss: Redis hit, or load + publish with epoch fencing.
*/
private function resolveCacheMiss(string $key, callable $loader): mixed
{
$epochAtStart = SettingMemoryCache::localEpoch();
$entry = $this->readStoreEntry($key);

if ($entry['hit']) {
SettingMemoryCache::put($key, $entry['value']);

return $entry['value'];
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

$value = $this->loadAndPublish($key, $loader, $epochAtStart);
SettingMemoryCache::put($key, $value);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreliable resolve fills worker L1

Medium Severity

When the epoch read after the loader fails, loadAndPublish returns without fencing, but resolveCacheMiss still puts that value into L1. The next request on the same worker keeps that map if the epoch is unchanged, so a stale or pre-commit setting can be served from memory instead of Redis or the database.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0f640d0. Configure here.


return $value;
}

/**
* Load from the callback and write to Redis unless another worker published first.
*/
private function loadAndPublish(string $key, callable $loader, ?int $epochAtStart): mixed
{
$value = $loader();

// If another worker published a committed value while we loaded, do not
// overwrite Redis with a possibly pre-commit row.
SettingMemoryCache::forceResyncEpoch();
if (SettingMemoryCache::isEpochUnreliable()) {
return $value;
}

if (SettingMemoryCache::localEpoch() !== $epochAtStart) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Agentic Security Review

Severity: MEDIUM

Description: SettingObserver::saved() drops the Redis settings key and publishEpoch() inside an open outer transaction. The observer does not use afterCommit, so Eloquent saved runs when the model is written, before DB::transaction commits. A concurrent worker that then resolves that key sees the new epoch, misses Redis, and loadAndPublish() stores loader()'s SELECT. On the default MySQL InnoDB connection that SELECT cannot see the writer's uncommitted row, so writeStoreEntry() persists the previous row with no TTL under the new epoch. DevLinkInstall keeps the transaction open across Bundle::installSettingsPayloads(), which updateOrCreate()s Log-In & Auth settings and never calls SettingCacheManager::set() after the outer commit. RefreshArtisanCaches::handle() is empty, so the terminating refresh does not remove the refilled key. Later Setting::byKey and SettingsConfigRepository reads keep serving the previous password-policy, 2FA, SSO, and session-control values. SettingController::update() does call set() with the refreshed model after save(), so that direct API write publishes the committed row.

Impact: A committed bundle install can leave 2FA, password policy, SSO/login, and session IP/device restrictions at the previous value for every worker until some later epoch bump. Login and session middleware keep enforcing that stale policy. The refill is any overlapping settings read during the install transaction; the poisoned Redis entry then applies to unauthenticated login traffic. This needs an in-flight privileged install, so it is not a scriptable unauthenticated attack on its own, and it does not grant full control of the app.

Remediation: Run epoch publish and the Redis write from DB::afterCommit (observer $afterCommit / ShouldHandleEventsAfterCommit, or an explicit afterCommit callback), and only after the committed value is stored. In loadAndPublish(), when the epoch moved or the key is missing after a bump, do not writeStoreEntry() the loader result; return it for this call and leave Redis empty so a pre-commit snapshot cannot become the authoritative entry. Bundle and DevLink setting writes should set() the committed model in that after-commit hook.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Agentic Security Review

Severity: MEDIUM

Description: loadAndPublish() can publish a pre-update Setting row to Redis after the shared epoch has already moved, so other workers treat the old password-policy, 2FA, session-control, or default-SSO value as current.

Impact: Login and session requests call Setting::byKey/config() with no credentials (login throttling, 2FA, sso.default.login, session-control.ip_restriction/device_restriction). A fill that lands after saved()/set() stamps the previous row at the new epoch. The next worker syncs to that epoch, hits Redis, and enforces the old policy with no DB read until some later epoch bump. The saving worker still keeps the new value in its own L1 after set(), so the admin node looks updated while the others do not. The wide window is an outer transaction: SettingObserver::saved() forgets the key and bumps the epoch before commit and is not afterCommit, and DevLink install of Log-In & Auth settings never calls set() after commit, so any overlapping byKey writes the snapshot that other connections cannot see yet. The narrow window is set() itself: the epoch GET and the later SET are separate Redis commands, so a resolver that still observed the old epoch can overwrite the committed payload after bumpEpoch().

Remediation: Write a fill only with a Redis compare-and-set on the epoch observed before loader() (Lua or WATCH/MULTI). If the epoch changed, do not writeStoreEntry(); return a store hit when one exists, otherwise return loader() to this caller only. Bump and publish only a value read after the commit that produced the bump. Set SettingObserver::$afterCommit = true (or publish the epoch from DB::afterCommit) so saved() does not invalidate inside an open transaction.

$entry = $this->readStoreEntry($key);
$value = $entry['hit'] ? $entry['value'] : $loader();
if (!$entry['hit']) {
$this->writeStoreEntry($key, $value);
}
} else {
$this->writeStoreEntry($key, $value);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale resolve can overwrite Redis

High Severity

resolve() re-checks the epoch before writing Redis, but the write itself is not guarded. A concurrent saved()/set() can bump the epoch and publish a committed value in the gap between forceResyncEpoch() and writeStoreEntry(), so a loader that still holds a pre-commit row overwrites L2 under the new epoch. Later workers then hit that stale envelope and never go back to the database until the setting is saved again.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 13d40b1. Configure here.


return $value;
}

/**
Expand Down Expand Up @@ -125,7 +211,7 @@ public function getOrCache(string $key, callable $callback): mixed
}

/**
* Store a value in the settings cache.
* Store a committed setting value, then publish a new epoch so other workers refresh L1.
*
* @param string $key
* @param mixed $value
Expand All @@ -135,7 +221,14 @@ public function getOrCache(string $key, callable $callback): mixed
*/
public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
{
return $this->cacheManager->put($key, $value, $ttl);
$result = $this->writeStoreEntry($key, $value, $ttl);

if ($result) {
SettingMemoryCache::bumpEpoch();
SettingMemoryCache::put($key, $value);
}

return $result;
}

/**
Expand All @@ -147,7 +240,11 @@ public function set(string $key, mixed $value, null|int|\DateInterval $ttl = nul
*/
public function delete(string $key): bool
{
return $this->cacheManager->forget($key);
$result = $this->cacheManager->forget($key);
SettingMemoryCache::forget($key);
SettingMemoryCache::bumpEpoch();

return $result;
}

/**
Expand All @@ -157,7 +254,10 @@ public function delete(string $key): bool
*/
public function clear(): bool
{
return $this->cacheManager->clear();
$result = $this->cacheManager->clear();
SettingMemoryCache::bumpEpochAfterStoreCleared();

return $result;
}

/**
Expand All @@ -181,6 +281,8 @@ public function clearBy(string $pattern): void
if (!empty($matchedKeys)) {
Redis::connection($defaultDriver)->del($matchedKeys);
}

SettingMemoryCache::bumpEpoch();
} catch (\Exception $e) {
Log::error('SettingCacheException' . $e->getMessage());

Expand All @@ -197,6 +299,16 @@ public function clearBy(string $pattern): void
*/
public function has(string $key): bool
{
SettingMemoryCache::syncEpoch();

if (SettingMemoryCache::isEpochUnreliable()) {
return false;
}

if (SettingMemoryCache::exists($key)) {
return true;
}

return $this->keyExists($key);
}

Expand All @@ -213,22 +325,78 @@ public function missing(string $key): bool
}

/**
* Invalidate a value in the settings cache.
* Drop a settings cache key from Redis/L1.
*
* @param string $key
* By default does NOT bump the shared epoch — that must happen after the
* committed value is published via set()/saved()/delete. Pass
* bump_epoch=true for hard invalidations (e.g. deleted settings).
*
* @param array $params
*
* @return void
*/
public function invalidate($params): void
{
try {
//extract the params from the array
$key = $params['key'];
$bumpEpoch = (bool) ($params['bump_epoch'] ?? false);

$this->cacheManager->forget($key);
SettingMemoryCache::forget($key);

if ($bumpEpoch) {
SettingMemoryCache::bumpEpoch();
}
} catch (\Exception $e) {
Log::error($e->getMessage());

throw new SettingCacheException('Failed to invalidate cache KEY:' . $key);
}
}

/**
* Publish a new shared epoch without changing Redis setting payloads.
*/
public function publishEpoch(): void
{
SettingMemoryCache::bumpEpoch();
}

/**
* Expose the underlying cache store (used for tests).
*/
public function store(): Repository
{
return $this->cacheManager;
}

/**
* @return array{hit: bool, value: mixed}
*/
private function readStoreEntry(string $key): array
{
$sentinel = SettingMemoryCache::sentinel();
$stored = $this->cacheManager->get($key, $sentinel);

if ($stored === $sentinel) {
return ['hit' => false, 'value' => null];
}

if (is_array($stored) && ($stored[self::ENVELOPE_FLAG] ?? false) === true) {
return ['hit' => true, 'value' => $stored['v']];
}

// Legacy unwrapped values written before envelopes.
return ['hit' => true, 'value' => $stored];
}

private function writeStoreEntry(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool
{
$envelope = [
self::ENVELOPE_FLAG => true,
'v' => $value,
];

return $this->cacheManager->put($key, $envelope, $ttl);
}
}
76 changes: 76 additions & 0 deletions ProcessMaker/Cache/Settings/SettingEpochRedis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);

namespace ProcessMaker\Cache\Settings;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Throwable;

/**
* Raw Redis I/O for the shared settings epoch key (integer, not PHP-serialized).
*/
class SettingEpochRedis
{
/**
* @return array{unreliable: bool, epoch: int}
*/
public static function get(): array
{
try {
$value = self::connection()->get(self::key());

return [
'unreliable' => false,
'epoch' => $value === null || $value === false ? 0 : (int) $value,
];
} catch (Throwable $e) {
Log::info('SettingMemoryCache: failed to read epoch: ' . $e->getMessage());

return [
'unreliable' => true,
'epoch' => 0,
];
}
}

/**
* Atomically increment the shared epoch; on failure, seed with $fallback.
*/
public static function incrementOrFallback(int $fallback): int

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Agentic Security Review

Severity: MEDIUM

Description: SettingEpochRedis::incrementOrFallback() treats a failed epoch INCR as a successful publish: it logs, may SET the caller's localEpoch+1 over the shared key, and always returns that fallback. SettingMemoryCache::bumpEpoch() then clears only the publishing worker's L1 and records epochUnreliable=false and syncedThisRequest=true. Peer workers invalidate solely by observing a higher Redis epoch, so an unchanged or rewound epoch leaves their existing L1 entries in place. resolve() then returns those entries and does not hit Redis or the database.

Impact: The shared epoch is the only cross-worker freshness gate for process-local settings L1. After a committed setting save, a publisher-side INCR failure (timeout, connection reset, OOM, or READONLY on the epoch write) while peer GETs still succeed leaves other Octane or queue workers enforcing the previous value. Session IP and device restrictions are read through Setting::configByKey on each login check, and SSO default login is read through Setting::byKey, so those workers can keep allowing sessions the new policy was meant to block. A fallback SET can also move the shared counter backward when the publisher's localEpoch is behind, so workers already sitting on that lower value never invalidate. A total epoch GET failure still fail-closes the worker that sees it; this gap is the swallowed write path, and it is not attacker-scriptable.

Remediation: Do not return or SET a locally computed epoch when INCR fails. Leave the publisher epochUnreliable so its own later reads skip L1, and do not mark syncedThisRequest. Only advance the shared counter with INCR (or a compare-and-set that refuses a lower value). Peers should drop L1 unless a successful GET shows an epoch greater than the one they cached with the entry.

{
try {
return (int) self::connection()->incr(self::key());
} catch (Throwable $e) {
Log::info('SettingMemoryCache: failed to increment epoch: ' . $e->getMessage());

try {
self::set($fallback);
} catch (Throwable $inner) {
Log::info('SettingMemoryCache: failed to write epoch: ' . $inner->getMessage());
}

return $fallback;
}
}

public static function set(int $epoch): void
{
self::connection()->set(self::key(), (string) $epoch);
}

public static function key(): string
{
$prefix = config('cache.stores.cache_settings.prefix', 'settings:');

return $prefix . SettingMemoryCache::EPOCH_KEY;
}

private static function connection()
{
$connection = config('cache.stores.cache_settings.connection', 'cache_settings');

return Redis::connection($connection);
}
}
Loading
Loading