codeant-ai-for-open-source[bot] commented on code in PR #33924:
URL: https://github.com/apache/superset/pull/33924#discussion_r3599752244
##########
superset/jinja_context.py:
##########
@@ -305,6 +311,57 @@ def url_param(
self.cache_key_wrapper(result)
return result
+ def get_guest_user_attribute(
+ self,
+ attribute_name: str,
+ default: JsonValue = None,
+ add_to_cache_keys: bool = True,
+ ) -> JsonValue:
+ """
+ Get a specific user attribute from guest user.
+
+ This function retrieves attributes from the guest user token and
supports
+ all JSON-native types (string, number, boolean, array, object, null).
+
+ Args:
+ attribute_name: Name of the attribute to retrieve
+ default: Default value if attribute not found (can be any
JSON-native type)
+ add_to_cache_keys: Whether the value should be included in the
cache key
+
+ Returns:
+ The attribute value from the guest user token, or the default
value.
+ Can be any JSON-native type: string, number, boolean, array,
object, or
+ null.
+
+ Examples:
+ {{ get_guest_user_attribute('department') }} # Returns:
"Engineering"
+ {{ get_guest_user_attribute('is_admin') }} # Returns: True
+ {{ get_guest_user_attribute('permissions') }} # Returns: ["read",
"write"]
+ {{ get_guest_user_attribute('config') }} # Returns: {"theme":
"dark"}
+ {{ get_guest_user_attribute('missing', 'default') }} # Returns:
"default"
+ """
+
+ # The macro only applies to guest users (embedded). is_guest_user()
+ # handles the feature-flag and request-context checks internally.
+ if not security_manager.is_guest_user():
+ return default
+
+ token = g.user.guest_token
+ user_attributes = token.get("user", {}).get("attributes") or {}
+
+ # Only add to the cache key if the attribute exists in the guest token
+ if attribute_name not in user_attributes:
+ return default
+
+ result = user_attributes[attribute_name]
+ if add_to_cache_keys and result is not None:
Review Comment:
**Suggestion:** Cache key handling skips both missing attributes and
attributes explicitly set to `null`, even though those cases can render
different SQL when a non-null default is provided. This can cause cache
collisions and stale cross-user results (for example, one user with `null` and
another without the attribute but with a default fallback). Include a
deterministic cache marker for all code paths, including missing and `None`
values. [cache]
<details>
<summary><b>Severity Level:</b> Critical ๐จ</summary>
```mdx
- โ Guest users may see cached results for other tenants.
- โ Attribute-driven filters can return stale cross-user data.
- โ ๏ธ Cache keys ignore missing/null guest attribute distinctions.
```
</details>
<details>
<summary><b>Steps of Reproduction โ
</b></summary>
```mdx
1. Create a dashboard or dataset query that uses `{{
get_guest_user_attribute("tenant",
"fallback") }}` in a WHERE clause so that the attribute value affects the
rendered SQL;
this macro is exposed through the Jinja context in `set_context` at
`superset/jinja_context.py:995-1009`, bound to
`ExtraCache.get_guest_user_attribute`.
2. Execute the query for guest user A whose
`guest_token["user"]["attributes"]` does not
contain `"tenant"`; inside `ExtraCache.get_guest_user_attribute` at
`superset/jinja_context.py:349-355`, the code hits `if attribute_name not in
user_attributes: return default`, returning `"fallback"` without calling
`cache_key_wrapper`, so no cache marker is added.
3. Execute the same query for guest user B whose
`guest_token["user"]["attributes"]["tenant"]` is explicitly `None`; the code
at
`superset/jinja_context.py:356-357` sets `result =
user_attributes[attribute_name]` and
skips `cache_key_wrapper` because `result is not None` is false, again
leaving extra cache
keys identical to user A.
4. Because both executions share the same extra cache key state despite
potentially
rendering different SQL or representing distinct logical tenants, the query
cache can
serve results computed under one user's attribute context to another user,
causing
cross-user cache collisions and stale or incorrect data.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=a8bbb5cd24944811afba1b2b2e8128db&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=a8bbb5cd24944811afba1b2b2e8128db&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent ๐ค </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/jinja_context.py
**Line:** 352:357
**Comment:**
*Cache: Cache key handling skips both missing attributes and attributes
explicitly set to `null`, even though those cases can render different SQL when
a non-null default is provided. This can cause cache collisions and stale
cross-user results (for example, one user with `null` and another without the
attribute but with a default fallback). Include a deterministic cache marker
for all code paths, including missing and `None` values.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F33924&comment_hash=622aa1e85365e41292ebf0f0f7775285df55e85c02da424df4922ed391dd7428&reaction=like'>๐</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F33924&comment_hash=622aa1e85365e41292ebf0f0f7775285df55e85c02da424df4922ed391dd7428&reaction=dislike'>๐</a>
##########
tests/unit_tests/jinja_context_test.py:
##########
@@ -1974,10 +1975,944 @@ def
test_undefined_template_variable_not_function(mocker: MockerFixture) -> None
("SELECT {{ current_user_email() }}", True),
("SELECT {{ current_user_roles() }}", True),
("SELECT {{ current_user_rls_rules() }}", True),
+ ("SELECT {{ get_guest_user_attribute('department') }}", True),
("SELECT 'cache_key_wrapper(abc)' AS false_positive", False),
("SELECT 1", False),
("SELECT '{{ 1 + 1 }}'", False),
],
)
def test_extra_cache_regex(sql: str, expected: bool) -> None:
assert bool(ExtraCache.regex.search(sql)) is expected
+
+
+def test_get_guest_user_attribute_no_request_context(mocker: MockerFixture) ->
None:
+ """
+ Test that get_guest_user_attribute returns default when there is no guest
user
+ (e.g. outside of a request context).
+ """
+ mocker.patch("superset.security_manager.is_guest_user", return_value=False)
+
+ cache = ExtraCache()
+ result = cache.get_guest_user_attribute("department", "default_dept")
+ assert result == "default_dept"
Review Comment:
**Suggestion:** This test never exercises the โno request contextโ path
because `is_guest_user` is hardcoded to `False`, which makes
`get_guest_user_attribute` return early before any request-context behavior is
touched. As written, the test is tautological and can pass even if
request-context handling regresses; set up a true no-request-context scenario
without forcing the early return. [incorrect condition logic]
<details>
<summary><b>Severity Level:</b> Major โ ๏ธ</summary>
```mdx
- โ ๏ธ No-request-context behavior for macro remains untested here.
- โ ๏ธ Regressions in is_guest_user outside context may go unnoticed.
```
</details>
<details>
<summary><b>Steps of Reproduction โ
</b></summary>
```mdx
1. Open `superset/jinja_context.py` and inspect
`ExtraCache.get_guest_user_attribute` at
lines 315-64: it immediately returns `default` when
`security_manager.is_guest_user()` is
`False`, without touching Flask request context or `g.user`.
2. Open `tests/unit_tests/jinja_context_test.py` and inspect
`test_get_guest_user_attribute_no_request_context` at lines 1988-1998: the
test patches
`superset.security_manager.is_guest_user` to always return `False` (line
1993), then calls
`cache.get_guest_user_attribute("department", "default_dept")` and asserts
that the
default is returned (lines 1995-1997).
3. Run `pytest
tests/unit_tests/jinja_context_test.py::test_get_guest_user_attribute_no_request_context`;
observe that the test passes solely because the patched `is_guest_user`
forces the
early-return branch in `get_guest_user_attribute`, without exercising any
real
no-request-context behavior in `security_manager.is_guest_user` or `g`.
4. Consider a regression in `security_manager.is_guest_user` at
`superset/security/manager.py:4614-19` (e.g., mishandling lack of request
context); since
this test fully mocks `is_guest_user`, such a regression would not be
covered here,
meaning the test does not truly validate the "no request context" path it
claims to cover.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e4549dad74194cf4bb962abf02bd7d77&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e4549dad74194cf4bb962abf02bd7d77&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent ๐ค </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/jinja_context_test.py
**Line:** 1993:1997
**Comment:**
*Incorrect Condition Logic: This test never exercises the โno request
contextโ path because `is_guest_user` is hardcoded to `False`, which makes
`get_guest_user_attribute` return early before any request-context behavior is
touched. As written, the test is tautological and can pass even if
request-context handling regresses; set up a true no-request-context scenario
without forcing the early return.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F33924&comment_hash=f537b33bc1f278523961366020900fc479d32b223ad9a9f55bc5a8e91d06a09b&reaction=like'>๐</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F33924&comment_hash=f537b33bc1f278523961366020900fc479d32b223ad9a9f55bc5a8e91d06a09b&reaction=dislike'>๐</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]