Skip to content

MOD-15105 make one generic getUser function - #1981

Merged
TalBarYakar merged 7 commits into
masterfrom
tal.ba/feat/refactor_get_user
May 19, 2026
Merged

TalBarYakar merged 7 commits into
masterfrom
tal.ba/feat/refactor_get_user

Conversation

@TalBarYakar

@TalBarYakar TalBarYakar commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

Medium Risk
Touches ACL enforcement paths for multi-key reads and libmr context-user handling; mistakes could cause incorrect permission allow/deny behavior or user lifetime issues.

Overview
Centralizes Redis ACL user resolution into a new GetUserFromContext()/User_Ctx_t API and updates key-permission helpers to accept a RedisModuleUser* instead of repeatedly resolving/freeing users.

Multi-key scans (QueryIndex, CheckDictSeriesPermissions, and GetSeries ACL checks) now hoist user lookup once per operation and reuse it across per-key ACL checks, reducing alloc/free churn and explicitly freeing username strings to avoid lingering auto-memory on long-lived contexts.

libmr_integration.c updates context-user apply/release logic to reuse the centralized user lookup and avoid redundant context user swaps; ACL-related test commentary is adjusted to reflect the new per-key checking approach.

Reviewed by Cursor Bugbot for commit d15953f. Bugbot is set up for automated code reviews on this repo. Configure here.

Comment thread src/module.h Resolved
Comment thread src/module.c Resolved
Comment thread src/module.c Resolved
Comment thread src/libmr_integration.c Resolved
Comment thread src/libmr_integration.c Resolved
@TalBarYakar
TalBarYakar removed the request for review from galcohen-redislabs May 3, 2026 07:18
Comment thread src/module.h
if (ctx != NULL) {
RedisModuleUser *user = GetCurrentUser(ctx);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If no one is using GetCurrentUser() anymore then just nuke it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done , removed!!

Comment thread src/module.h
* set. */
#define API_USER_CONTEXT_SUPPORTED \
(RedisModule_SetContextUser && RedisModule_GetContextUser && \
RedisModule_GetModuleUserFromUserName && RedisModule_GetUserUsername)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Too many confusing function names (above and below).
Maybe here is a good place to explain the dual-user mechanism inside ctx and briefly describe what each of those ^^ four functions do.
And then explain what the GetUserFromContext() (below) does (i.e., in light of the dual-user logic).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

Comment thread src/module.h Outdated
}

const int allowed = RedisModule_ACLCheckKeyPermissions(user, keyName, permissionFlags);
if ((user = GetUserFromContext(ctx)) != NULL) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Sonar is right. Avoid the extra tabulation by simply &&-ing the two conditions, or simply return true immediately if no context (and same if user is null after the GetUserFromContext())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

Comment thread src/module.h Outdated

if (allowed != REDISMODULE_OK) {
return false;
RedisModule_FreeModuleUser(user);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The alloc and free of user bothers me. We probably do it per key and always with the same user. There could be tons of keys, so better refactor it such that you get the user once and pass it to the CheckIfAllowed functions and free it when done with all keys.

@TalBarYakar TalBarYakar May 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

With the new logic and the struct I added, we no longer allocate and free the user when it’s unnecessary , although I change the code as asked

@TalBarYakar
TalBarYakar force-pushed the tal.ba/feat/refactor_get_user branch from 9653c11 to 32ff582 Compare May 14, 2026 08:01
@TalBarYakar
TalBarYakar force-pushed the tal.ba/feat/refactor_get_user branch from 32ff582 to 2715b7c Compare May 14, 2026 08:16

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 2715b7c. Configure here.

Comment thread src/libmr_integration.c Resolved
Comment thread src/module.c
const User_Ctx_t empty = { .user = NULL, .is_owned = false };

if (!API_USER_CONTEXT_SUPPORTED)
return empty;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ACL checks silently bypassed on older Redis versions

Medium Severity

GetUserFromContext gates all user resolution behind API_USER_CONTEXT_SUPPORTED, which requires all four functions including RedisModule_SetContextUser and RedisModule_GetUserUsername. The old GetCurrentUser only needed RedisModule_GetCurrentUserName and RedisModule_GetModuleUserFromUserName — it had no dependency on the context-user APIs. On Redis versions where SetContextUser or GetUserUsername are unavailable (e.g., 7.0.x), GetUserFromContext now returns a NULL user, causing CheckKeyIsAllowedByAcls to skip the ACL check entirely and return true. The old code would still have resolved the user and enforced permissions.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2715b7c. Configure here.

Comment thread src/module.h Outdated
/* A RedisModuleCtx carries the connection's authenticated "client user" plus an
* optional "attached user" set by the module: SetContextUser attaches one,
* GetContextUser reads it back (borrowed), GetModuleUserFromUserName allocates
* one by name (owned), GetUserUsername returns a user's name. GetUserFromContext()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

C, being a low-level language, does not have "borrowed" and "owned" concepts. I'm guessing that by "borrowed" you mean that that the function returns an internal pointer (i.e., which should not be freed and it will not outlive ctx) and by "owned" you mean that the caller is now responsible (and therefore should free it eventually).
If this is the case then explain it explicitly in the comment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

Comment thread src/module.h Outdated
* optional "attached user" set by the module: SetContextUser attaches one,
* GetContextUser reads it back (borrowed), GetModuleUserFromUserName allocates
* one by name (owned), GetUserUsername returns a user's name. GetUserFromContext()
* below picks the attached user if present, else allocates the client user. */

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Wait, what? The return value of GetUserFromContext() could either be borrowed or owned, depending on whether a context user was attached or not??

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, this is intentional. The whole point of returning a tagged wrapper (User_Ctx_t with is_owned) instead of a raw RedisModuleUser* is to expose this dual ownership model to the caller without forcing them to reason about the implementation details.

When a user is already attached to the context, we receive a const pointer directly, without cloning it. In contrast, when the user is attached through ctx->client, redis clone the user object, which means the caller owns it and must free it afterward.

Comment thread src/module.h Outdated
#include "fast_double_parser_c/fast_double_parser_c.h"

/* A RedisModuleCtx carries the connection's authenticated "client user" plus an
* optional "attached user" set by the module: SetContextUser attaches one,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This optional "attached user" shades over the the connection's original (client) user. It should be mentioned here, otherwise it is not clear why two users in the same context.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

Comment thread src/module.h
typedef struct
{
RedisModuleUser *user;
bool is_owned;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is this wrapping really necessary? In C this is a weird abstraction because the "ownership" better be explicit and known to the caller (such abstractions have the risk of hiding weird bugs).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, it's intentional. The wrapper is meant as an abstraction layer: the caller calls GetUserFromContext, gets back a User_Ctx_t, uses it, then calls FreeUser on it. The caller doesn't need to know which user was returned (client vs attached) or how it was obtained (allocated clone vs internal pointer) — that bookkeeping stays in one place instead of being replicated at every call site.

Comment thread src/module.h Outdated
@@ -160,15 +178,15 @@ static inline bool IsUserAllowedToReadAllTheKeys(struct RedisModuleCtx *ctx,
}

static inline bool IsCurrentUserAllowedToReadAllTheKeys(struct RedisModuleCtx *ctx) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This function is not used anywhere.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

removed

Comment thread src/module.h
if (userCtx->user != NULL && userCtx->is_owned) {
RedisModule_FreeModuleUser(userCtx->user);
}
userCtx->user = NULL;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I see FreeUser() is being called from all sorts of functions. Are you 100% sure it is always called by the same thread?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

There's no shared User_Ctx_t between threads — every call site declares its own on the stack.

Comment thread src/module.h
if (user == NULL) {
return true;
}
RedisModuleString *key = RedisModule_CreateString(ctx, keyName, keyNameLength);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Same issue here: redundant (and slow) multiple allocs (CreateString) and frees (FreeString). Should be refactored as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ACLCheckKeyPermissions only takes a RedisModuleString *, and there's no API to mutate one in place — only Create/AppendBuffer/Free. So we can't reuse the same string across keys. Real fix is asking core to add a ACLCheckKeyPermissionsC that takes raw bytes; I can open that. For now this Create/Free is the floor.

Comment thread src/libmr_integration.c
static void ReleaseCtxUser(RedisModuleCtx *ctx) {
if (!API_USER_CONTEXT_SUPPORTED)
return;
RedisModuleUser *user = (RedisModuleUser *)RedisModule_GetContextUser(ctx);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

You mentioned that callers of GetConextUser borrow the user (and indeed the minimal C protection of using a const pointer is used for the return value) so you should not cast the const away because you basically violate the contract.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The cast is technically a contract violation, however , In the previous PR we actually went back and forth on this — the alternative was to return the allocated user from ApplyCtxUser and have every caller hold onto it until release time, passing it back to ReleaseCtxUser explicitly.
We chose this cast-and-fetch approach instead because it keeps the call sites symmetric and clean — callers just do ApplyCtxUser(ctx, ...) / ReleaseCtxUser(ctx) without threading an extra pointer through every function. The cast is ugly but localized to one spot, and since we're the only ones attaching users to that ctx we know it's safe in practice. Happy to switch to the explicit-pointer version if you'd rather lean on the contract — just felt the readability win was worth the small smell here.

@sonarqubecloud

Copy link
Copy Markdown

@gabsow gabsow changed the title make one generic getUser function MOD-15105 make one generic getUser function May 19, 2026
@gabsow

gabsow commented May 19, 2026

Copy link
Copy Markdown
Collaborator

Correctness findings

1. Dangling pointer in ApplyCtxUser (src/libmr_integration.c:470) — recommend fixing

After ReleaseCtxUser(ctx) frees the attached user, currentUserCtx.user still holds that freed pointer. FreeUser doesn't free it (is_owned == false), so there's no double-free today, but the structure invites a future use-after-free if anyone adds code between ReleaseCtxUser and _cleanup that dereferences currentUserCtx.user.

Suggested fix — null the wrapper immediately after release so the dangling ref can't leak past this point:

if (currentName && RedisModule_StringCompare(currentName, userName) == 0) {
    goto _cleanup;
}
ReleaseCtxUser(ctx);
currentUserCtx.user = NULL;   // ctx no longer holds it; drop our borrowed ref

2. Silent default-allow when user resolution fails (src/module.h, CheckKeyIsAllowedByAcls)

if (user == NULL) {
    return true;
}

Previously, the ACL helper logged a warning when it couldn't run (when ctx was NULL). Now, if GetUserFromContext returns an empty User_Ctx_t for any reason (e.g., GetModuleUserFromUserName returns NULL because the user was deleted mid-request, or an API path that isn't API_USER_CONTEXT_SUPPORTED), we silently allow access on the ACL enforcement path.

Suggest adding a RedisModule_Log(..., "warning", ...) inside GetUserFromContext when it returns empty, so operators can diagnose if a request unexpectedly bypasses ACL because user resolution failed.

@gabsow
gabsow self-requested a review May 19, 2026 08:24
@TalBarYakar

Copy link
Copy Markdown
Contributor Author

@gabsow can't reply to your comment :
Not a bug — the borrowed currentUserCtx.user is only ever observed before ReleaseCtxUser(ctx), and the code between that call and _cleanup (GetModuleUserFromUserName + SetContextUser) never touches it. FreeUser(&currentUserCtx) at _cleanup skips the free because is_owned=false (no double-free) and unconditionally NULLs the wrapper, so the dangling pointer cannot escape the function. The suggestion is purely defensive against hypothetical future edits, which the reviewer themselves acknowledged ("no double-free today").

@gabsow

gabsow commented May 19, 2026

Copy link
Copy Markdown
Collaborator

i think you can merge , looks like all comments was solved

@TalBarYakar
TalBarYakar merged commit d3642aa into master May 19, 2026
95 of 105 checks passed
@TalBarYakar
TalBarYakar deleted the tal.ba/feat/refactor_get_user branch May 19, 2026 12:36
YaacovHazan pushed a commit to redis/redis that referenced this pull request Jun 14, 2026
## Summary

Bumps the pinned `MODULE_VERSION` for **RedisTimeSeries** from `v8.8.0`
to `v8.9.80`. RedisBloom and RedisJSON are unchanged.

| Module          | From    | To       |
|-----------------|---------|----------|
| RedisTimeSeries | v8.8.0  | v8.9.80  |

> **Note:** `v8.9.80` is the **8.10 LTS branch cut** (targets Redis
8.10) and has diverged from `v8.8.0`. The `v8.8.0...v8.9.80` ancestry
diff contains 37 commits, but **7 are backports already shipped in
`v8.8.0`** (verified with `git cherry`, see below); the **30 genuinely
new** changes are listed here.

## Module changes ([v8.8.0 →
v8.9.80](RedisTimeSeries/RedisTimeSeries@v8.8.0...v8.9.80))

- MOD-14124 — m commands acl
([#1913](RedisTimeSeries/RedisTimeSeries#1913))
- MOD-14250 — missing artifacts logs fix
([#1932](RedisTimeSeries/RedisTimeSeries#1932))
- MOD-14289 — Increase LibMR execution timeout for Valgrind builds
([#1933](RedisTimeSeries/RedisTimeSeries#1933))
- MOD-12726 — unique snapshot name + new output params for nighly event
([#1937](RedisTimeSeries/RedisTimeSeries#1937))
- MOD-14674 — oss refresh list
([#1935](RedisTimeSeries/RedisTimeSeries#1935))
- nightly build, upload snapshot artifact
([#1954](RedisTimeSeries/RedisTimeSeries#1954))
- MOD-14902 — existence check to prevent Timeseries crash when Redis is
not aligned with new redis-core changes
([#1940](RedisTimeSeries/RedisTimeSeries#1940))
- MOD-14850 — Bump libmr
([#1962](RedisTimeSeries/RedisTimeSeries#1962))
- MOD-14715 — add apt retries/timeouts to Debian/Ubuntu Dockerfiles
([#1965](RedisTimeSeries/RedisTimeSeries#1965))
- MOD-15262 — Align TimeSeries with the RedisModule_GetUserUserName API
changes
([#1975](RedisTimeSeries/RedisTimeSeries#1975))
- RED-180951 RED-180027 — fixing bugs and improving the code
([#2004](RedisTimeSeries/RedisTimeSeries#2004))
- MOD-14239 — Ignore known init-rdbchannel migration timeout under
sanitizer
([#1979](RedisTimeSeries/RedisTimeSeries#1979))
- MOD-15105 — make one generic getUser function
([#1981](RedisTimeSeries/RedisTimeSeries#1981))
- MOD-15741 MOD-14091 — add dont-cache command tip to non-cacheable read
commands
([#2031](RedisTimeSeries/RedisTimeSeries#2031))
- MOD-15731 — modules modernization alignment
([#2027](RedisTimeSeries/RedisTimeSeries#2027))
- MOD-15728 — Tal.ba/feat/blocking get
([#2028](RedisTimeSeries/RedisTimeSeries#2028))
- MOD-8187 — fix the aggregation bugs (fix reverse iterator)
([#2036](RedisTimeSeries/RedisTimeSeries#2036))
- MOD-15749 — Link to new version of LibMR with short-form CLUSTERSET
and add tests
([#2034](RedisTimeSeries/RedisTimeSeries#2034))
- Fix REDISMODULE_MAIN typo + drop common.h forward-decl workarounds
([#2044](RedisTimeSeries/RedisTimeSeries#2044))
- CI: switch flow-linux arm64 runner to standard ubuntu-24.04-arm
([#2048](RedisTimeSeries/RedisTimeSeries#2048))
- MOD-15999 — Centralize Redis ref into a single source-of-truth file
for CI
([#2045](RedisTimeSeries/RedisTimeSeries#2045))
- CI: trigger OSS cluster (multi-shard) benchmarks on demand
([#2050](RedisTimeSeries/RedisTimeSeries#2050))
- MOD-15899 — oom try calloc
([#2051](RedisTimeSeries/RedisTimeSeries#2051))
- MOD-8187 — fix non twa aggregation
([#2053](RedisTimeSeries/RedisTimeSeries#2053))
- MOD-16224 — Fix filter-blind neighbor lookups in EMPTY aggregation
([#2056](RedisTimeSeries/RedisTimeSeries#2056))
- MOD-15893 — Nrange new command
([#2052](RedisTimeSeries/RedisTimeSeries#2052))
- MOD-16160 — update blocking get syntax
([#2054](RedisTimeSeries/RedisTimeSeries#2054))
- MOD-16160 — Fix client-side cache tips for TS.BGET and
TS.NRANGE/TS.NREVRANGE
([#2057](RedisTimeSeries/RedisTimeSeries#2057))
- Cut 8.10 LTS branch: bump version to 8.9.80, target Redis 8.10
([27484f7](RedisTimeSeries/RedisTimeSeries@27484f7))
- Fix event-nightly CI on 8.10: read Redis ref from dedicated redis_ref
field
([#2058](RedisTimeSeries/RedisTimeSeries#2058))

<details>
<summary>7 commits excluded — already shipped in v8.8.0 as
backports</summary>

These show up in the `v8.8.0...v8.9.80` ancestry diff with different
SHAs, but `git cherry` confirms their patch content is already in
`v8.8.0`: they were backported to the 8.8 release branch (the "in 8.8
via" PR below), so they are **not** new in this bump.

- MOD-9320 — Multiple aggregators single command
([#1916](RedisTimeSeries/RedisTimeSeries#1916))
→ in 8.8 via
[#1921](RedisTimeSeries/RedisTimeSeries#1921)
- MOD-9320 — rename AGGREGATION token in m commands
([#1926](RedisTimeSeries/RedisTimeSeries#1926))
→ in 8.8 via
[#1927](RedisTimeSeries/RedisTimeSeries#1927)
- MOD-13142 — Allow changing number of threads while pool hasn't started
([#1928](RedisTimeSeries/RedisTimeSeries#1928))
→ in 8.8 via
[#1934](RedisTimeSeries/RedisTimeSeries#1934)
- MOD-14439 — Detect cluster topology changes during a multi-shard
command
([#1930](RedisTimeSeries/RedisTimeSeries#1930))
→ in 8.8 under the same PR
- ci: skip Event CI when PR only changes src/version.h
([#1984](RedisTimeSeries/RedisTimeSeries#1984))
→ in 8.8 via
[#1986](RedisTimeSeries/RedisTimeSeries#1986)
- MOD-15020 — remove bionic os support
([#1983](RedisTimeSeries/RedisTimeSeries#1983))
→ in 8.8 via
[#1996](RedisTimeSeries/RedisTimeSeries#1996)
- MOD-14420 — fix count reducers return wrong NaN
([#2013](RedisTimeSeries/RedisTimeSeries#2013))
→ in 8.8 via
[#2016](RedisTimeSeries/RedisTimeSeries#2016)

</details>

## Test plan
- [ ] CI passes for RedisTimeSeries at the new pinned version
- [ ] `make all` builds RedisTimeSeries cleanly against `unstable`
- [ ] Module tests run under `make test`

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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.

3 participants