You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "aminghadersohi (via GitHub)" <gi...@apache.org> on 2026/07/22 03:49:20 UTC
[PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
aminghadersohi opened a new pull request, #42297:
URL: https://github.com/apache/superset/pull/42297
## Summary
- Route onboarding and User Settings credential saves through one canonical `agentic_tools[tool][field]` patch helper.
- Teach `check-auth` that Claude `setup-token` values are `CLAUDE_CODE_OAUTH_TOKEN` OAuth credentials, not Anthropic Console API keys.
- Validate credentials stored in User Settings β Env Vars by reusing the same user/tool env resolver used for executor session environments.
- Validate Claude subscription tokens through the Claude SDK with an explicit per-probe env, avoiding daemon-global `process.env` mutation.
- Include `CLAUDE_CODE_OAUTH_TOKEN` env-var setups in onboarding/banner key detection.
- Clarify the short `claude setup-token` instructions with terminal/Claude Code install context and a Claude Code install-docs link.
- Add regression tests for shared storage shape, Claude subscription-token auth checks, user env-var auth checks, and banner detection.
## Root cause
The onboarding wizard already saved Claude subscription tokens to the same canonical per-user storage path as User Settings: `agentic_tools['claude-code'].CLAUDE_CODE_OAUTH_TOKEN`. The broken part was auth verification: `check-auth` only resolved/validated `ANTHROPIC_API_KEY` for Claude Code, so a `claude setup-token` value could be tested as the wrong credential type or ignored when stored.
There was also a gap for non-recommended-but-working setups where users put `ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN` in User Settings β Env Vars. Executors can receive those env vars, but auth verification and banners were not fully aligned with that effective runtime env.
## Canonical path after this change
Onboarding and User Settings now save Claude subscription tokens through the same helper and storage shape: `agentic_tools['claude-code'].CLAUDE_CODE_OAUTH_TOKEN`. `check-auth` resolves credentials in the same order sessions effectively use them: canonical per-tool credentials first, then user env vars for the tool, then native Claude auth fallback.
## Verification
- `pnpm i`
- `pnpm --filter @agor/daemon test -- src/services/check-auth.test.ts`
- `pnpm --filter agor-ui test -- src/components/OnboardingBanners/OnboardingBanners.test.tsx src/utils/agenticToolCredentials.test.ts src/components/OnboardingWizard/OnboardingWizard.test.tsx src/components/SettingsModal/UserSettingsModal.test.tsx`
- `pnpm --filter agor-ui typecheck`
- `pnpm check` β typecheck/lint/shortid phases passed; stopped at existing `check:multitenancy-boundaries` baseline violations unrelated to this PR.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5300030379
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi merged PR #42297:
URL: https://github.com/apache/superset/pull/42297
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5186221691
### <span aria-hidden="true">β
</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">π¨</span> Latest commit | 9ea986e3517afba3445466d5197ecf8acac4df1e |
|<span aria-hidden="true">π</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a7286f762acff00080facb7 |
|<span aria-hidden="true">π</span> Deploy Preview | [https://deploy-preview-42297--superset-docs-preview.netlify.app](https://deploy-preview-42297--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">π±</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
|<span aria-hidden="true">π€</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#q1YqKMrPLShRslJS0lFKKkrMS84AsouTdRNLSzJ0i5PzC1KLdTNzC3KA0impBTn5lZ4pQAVmieZGFmZp5mZGiclpaQYGBhYGaYnJSeZKtQA) |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-42297--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on code in PR #42297:
URL: https://github.com/apache/superset/pull/42297#discussion_r3785630668
##########
superset/mcp_service/auth.py:
##########
@@ -400,7 +435,9 @@ def check_tool_permission( # noqa: C901
# advertises scopes. Tokens/deployments that don't use scopes (API keys,
# scope-less JWTs, dev-mode) fall through to RBAC-only behavior β see
# ``_token_scope_allows``.
- if has_permission and not _token_scope_allows(method_permission_name):
+ if has_permission and not _token_scope_allows(
Review Comment:
This block worries me a bit, though I don't think it's a regression you introduced. `check_tool_permission` returns True for tools with no `class_permission_name` (line 408) before `_token_scope_allows` is ever consulted, so scoped tokens are not constrained at all on those tools. I verified it on this branch against a live MCP service: an API key scoped only to `superset:dashboard:read` can call `find_users` and get back user ids, usernames and names, and can call `get_instance_info`, both directly and through the `call_tool` proxy. The same held for flat scopes before this PR, but per-resource keys are what make "this key can only touch dashboards" a promise users will rely on, and the PR description's "denies chart tools and all write tools" doesn't cover this surface.
Was leaving permission-less tools outside scope enforcement intentional? If not, calling `_token_scope_allows(method_permission_name)` in the permission-less branch would require at least the flat `superset:read` for these tools when a token advertises scopes, while keeping unscoped tokens on today's behavior. A test in `test_auth_rbac.py` with a class-permission-less tool and a token scoped `["superset:dashboard:read"]` would lock it in; the existing scope tests all use tools that declare a class permission, which is why this path went untested. Not a blocker either way, but worth deciding explicitly.
##########
superset/security/manager.py:
##########
@@ -4926,6 +4927,116 @@ def parse_jwt_guest_token(self, raw_token: str) -> dict[str, Any]:
raw_token, secret, algorithms=[algo], audience=audience
)
+ def get_api_key_scopes(self, api_key_string: str) -> Optional[str]:
+ """Return the ``scopes`` value for a validated API key.
+
+ FAB's ``validate_api_key`` resolves the matching ``ApiKey`` row
+ internally (by lookup hash) but only returns the associated
+ ``User`` β the row's ``scopes`` column is otherwise unreachable by
+ callers. This repeats the same cheap, indexed lookup so MCP's
+ ``CompositeTokenVerifier`` can propagate per-key scopes instead of
+ silently falling back to verifier-global scopes. Call only after
+ ``validate_api_key`` has already succeeded for this token β this
+ method does not itself verify the key hash or active status.
+ """
+ lookup = self._compute_lookup_hash(api_key_string) # type: ignore[attr-defined]
+ api_key = (
+ self.session.query(self.api_key_model) # type: ignore[attr-defined]
+ .filter(self.api_key_model.lookup_hash == lookup)
+ .one_or_none()
+ )
+ return api_key.scopes if api_key else None
+
+ def _validate_requested_api_key_scopes(
+ self, user: Any, scopes: Optional[str]
+ ) -> None:
+ """Raise if ``scopes`` would grant a user more than their own RBAC.
+
+ Enforces the "intersection, never broader" rule confirmed for this
+ feature: a user must never be able to mint a token scoped beyond
+ what their own role already permits, even if they hand-author the
+ scopes string themselves at issuance time.
+
+ Per-resource scopes (``superset:<resource>:<action>``) are checked
+ against the user's actual ``can_<method>`` RBAC grant for that
+ resource. Flat scopes (``superset:read``/``superset:write``, the
+ pre-per-resource form) can only be self-issued by Admins β a flat
+ scope grants a method across every resource, and there's no single
+ RBAC check that soundly proves a non-Admin has that for "every
+ resource," so it's rejected for anyone else rather than guessed at.
+ Unrecognized scope strings are rejected outright (fail closed).
+
+ NOTE: this only prevents the request from being honored; it does
+ not (yet) produce a clean 400 response, since FAB's ``ApiKeyApi``
+ has no validation hook this can plug into without replacing the API
+ registration entirely. Raising here surfaces as a 500 via FAB's
+ ``@safe`` decorator until that's addressed β tracked as a known
+ follow-up, not silently accepted.
+ """
+ if not scopes:
+ return
+ # pylint: disable-next=import-outside-toplevel
+ from superset.security.api_key_scopes import (
+ RESOURCE_SCOPE_ACTIONS,
+ RESOURCE_SCOPE_CLASS,
+ )
+
+ is_admin = any(role.name == "Admin" for role in getattr(user, "roles", []))
+ for raw_scope in scopes.split(","):
+ scope = raw_scope.strip()
+ if not scope:
+ continue
+ parts = scope.split(":")
+ if len(parts) == 3 and parts[0] == "superset":
+ _, resource_slug, action = parts
+ class_permission_name = RESOURCE_SCOPE_CLASS.get(resource_slug)
+ if class_permission_name is None:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"resource '{resource_slug}'"
+ )
+ if action not in RESOURCE_SCOPE_ACTIONS:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"action '{action}'"
+ )
+ if self._has_view_access(user, f"can_{action}", class_permission_name):
Review Comment:
Not a blocker, everything here fails closed, but three of the sixteen advertised resource scopes can never be minted by anyone, Admin included. I verified it live on this branch: `create_api_key` for Admin with `superset:user:read`, `superset:role:read` or `superset:sqllab:write` is rejected with "exceeds the issuing user's own permissions", because the permission-views `can_read` on User/Role and `can_write` on SQLLab don't exist in an initialized instance (those views register `can_get` and `can_execute_sql_query` instead, which is exactly why the MCP tools declare `method_permission_name="get"` for User/Role). Meanwhile the runtime side happily grants those scopes when presented on a JWT, since `get` and `execute_sql_query` map to `read`/`write` in `METHOD_PERMISSION_SCOPE_ACTION`.
One way to line the two sides up: accept a requested scope when the user holds any method permission that maps to that action for the resource (invert `METHOD_PERMISSION_SCOPE_ACTION`, so `read` checks `can_read` or `can_get`, and `write` also checks `can_execute_sql_query`), which mirrors what the scope actually grants at runtime. Also, the "exceeds the issuing user's own permissions" message is misleading for this case since no user can hold a permission that doesn't exist. If you'd rather keep it strict, a docstring note on which scopes are effectively JWT-only would do.
##########
superset/security/manager.py:
##########
@@ -4926,6 +4927,116 @@ def parse_jwt_guest_token(self, raw_token: str) -> dict[str, Any]:
raw_token, secret, algorithms=[algo], audience=audience
)
+ def get_api_key_scopes(self, api_key_string: str) -> Optional[str]:
+ """Return the ``scopes`` value for a validated API key.
+
+ FAB's ``validate_api_key`` resolves the matching ``ApiKey`` row
+ internally (by lookup hash) but only returns the associated
+ ``User`` β the row's ``scopes`` column is otherwise unreachable by
+ callers. This repeats the same cheap, indexed lookup so MCP's
+ ``CompositeTokenVerifier`` can propagate per-key scopes instead of
+ silently falling back to verifier-global scopes. Call only after
+ ``validate_api_key`` has already succeeded for this token β this
+ method does not itself verify the key hash or active status.
+ """
+ lookup = self._compute_lookup_hash(api_key_string) # type: ignore[attr-defined]
+ api_key = (
+ self.session.query(self.api_key_model) # type: ignore[attr-defined]
+ .filter(self.api_key_model.lookup_hash == lookup)
+ .one_or_none()
+ )
+ return api_key.scopes if api_key else None
+
+ def _validate_requested_api_key_scopes(
+ self, user: Any, scopes: Optional[str]
+ ) -> None:
+ """Raise if ``scopes`` would grant a user more than their own RBAC.
+
+ Enforces the "intersection, never broader" rule confirmed for this
+ feature: a user must never be able to mint a token scoped beyond
+ what their own role already permits, even if they hand-author the
+ scopes string themselves at issuance time.
+
+ Per-resource scopes (``superset:<resource>:<action>``) are checked
+ against the user's actual ``can_<method>`` RBAC grant for that
+ resource. Flat scopes (``superset:read``/``superset:write``, the
+ pre-per-resource form) can only be self-issued by Admins β a flat
+ scope grants a method across every resource, and there's no single
+ RBAC check that soundly proves a non-Admin has that for "every
+ resource," so it's rejected for anyone else rather than guessed at.
+ Unrecognized scope strings are rejected outright (fail closed).
+
+ NOTE: this only prevents the request from being honored; it does
+ not (yet) produce a clean 400 response, since FAB's ``ApiKeyApi``
+ has no validation hook this can plug into without replacing the API
+ registration entirely. Raising here surfaces as a 500 via FAB's
+ ``@safe`` decorator until that's addressed β tracked as a known
+ follow-up, not silently accepted.
+ """
+ if not scopes:
+ return
+ # pylint: disable-next=import-outside-toplevel
+ from superset.security.api_key_scopes import (
+ RESOURCE_SCOPE_ACTIONS,
+ RESOURCE_SCOPE_CLASS,
+ )
+
+ is_admin = any(role.name == "Admin" for role in getattr(user, "roles", []))
Review Comment:
Just a small NIT: this hardcodes the "Admin" role name, while `is_admin()` further down this file resolves it from `conf["AUTH_ROLE_ADMIN"]`. On a deployment with a renamed admin role, real admins can't self-issue flat scopes (fail closed, so no security concern, and runtime RBAC still bounds any key regardless), but it's a one-line fix to read the config value and stay consistent with the rest of the security manager.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42297:
URL: https://github.com/apache/superset/pull/42297#discussion_r3717165856
##########
superset/mcp_service/auth.py:
##########
@@ -398,7 +467,9 @@ def check_tool_permission( # noqa: C901
# advertises scopes. Tokens/deployments that don't use scopes (API keys,
# scope-less JWTs, dev-mode) fall through to RBAC-only behavior β see
# ``_token_scope_allows``.
- if has_permission and not _token_scope_allows(method_permission_name):
+ if has_permission and not _token_scope_allows(
+ method_permission_name, class_permission_name
+ ):
_log_scope_denial(
Review Comment:
**Suggestion:** The new scope check is only applied through `check_tool_permission`, but `get_schema` performs its own dynamic RBAC check and does not call `_token_scope_allows`. Consequently, a scoped token carrying an unrelated resource scope can still retrieve schema metadata for any resource for which its user has RBAC access, bypassing the intended per-resource token/RBAC intersection. Apply the same scope check to dynamic permission paths such as `get_schema` before allowing the operation. [incomplete implementation]
<details>
<summary><b>Severity Level:</b> Major β οΈ</summary>
```mdx
- β Scoped tokens can bypass intended schema scope restrictions.
- β οΈ `get_schema` exposes chart, dataset, dashboard, database, or report metadata.
- β οΈ Token/RBAC intersection is inconsistent across MCP tools.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=12428ba0c2d4497f8990e1ed21d55459&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=12428ba0c2d4497f8990e1ed21d55459&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/mcp_service/auth.py
**Line:** 470:473
**Comment:**
*Incomplete Implementation: The new scope check is only applied through `check_tool_permission`, but `get_schema` performs its own dynamic RBAC check and does not call `_token_scope_allows`. Consequently, a scoped token carrying an unrelated resource scope can still retrieve schema metadata for any resource for which its user has RBAC access, bypassing the intended per-resource token/RBAC intersection. Apply the same scope check to dynamic permission paths such as `get_schema` before allowing the operation.
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%2F42297&comment_hash=86b952a954782b6e07599c92dea0cc784c41a73d2c9c950daceff34cdb373426&reaction=like'>π</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42297&comment_hash=86b952a954782b6e07599c92dea0cc784c41a73d2c9c950daceff34cdb373426&reaction=dislike'>π</a>
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -168,32 +181,38 @@ async def verify_token(self, token: str) -> AccessToken | None:
if any(token.startswith(prefix) for prefix in self._api_key_prefixes):
if self._app is not None:
loop = asyncio.get_running_loop()
- username = await loop.run_in_executor(
+ result = await loop.run_in_executor(
None, self._validate_api_key_sync, token
)
- if username is None:
+ if result is None:
logger.debug(
"API key rejected at transport layer (invalid or expired)"
)
return None
+ username, key_scopes = result
logger.debug(
"API key validated at transport layer for user=%s", username
)
return AccessToken(
token=token,
client_id="api_key",
- scopes=list(self.required_scopes or []),
+ # Prefer the key's own scopes over verifier-global
+ # required_scopes. Empty list = no scopes set = "no scopes
+ # advertised" back-compat per auth.py's
+ # _get_token_scopes()/_token_scope_allows().
+ scopes=key_scopes or list(self.required_scopes or []),
Review Comment:
**Suggestion:** The empty-key-scope fallback re-advertises `self.required_scopes`, so a key with no `ApiKey.scopes` is treated as a scoped token whenever global required scopes are configured. That contradicts the documented no-scopes behavior in `auth.py`, where an empty scope set means RBAC-only authorization, and can unexpectedly deny otherwise RBAC-authorized API-key requests. Preserve the empty scope list for unscoped keys rather than converting it into global JWT scopes. [logic error]
<details>
<summary><b>Severity Level:</b> Major β οΈ</summary>
```mdx
- β Unscoped API keys can lose RBAC-authorized MCP operations.
- β οΈ Behavior changes when `MCP_REQUIRED_SCOPES` is configured.
- β οΈ API-key scope semantics contradict documented back-compat behavior.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d85215dfa34b4bd5beaca7972359a18c&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=d85215dfa34b4bd5beaca7972359a18c&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/mcp_service/composite_token_verifier.py
**Line:** 203:203
**Comment:**
*Logic Error: The empty-key-scope fallback re-advertises `self.required_scopes`, so a key with no `ApiKey.scopes` is treated as a scoped token whenever global required scopes are configured. That contradicts the documented no-scopes behavior in `auth.py`, where an empty scope set means RBAC-only authorization, and can unexpectedly deny otherwise RBAC-authorized API-key requests. Preserve the empty scope list for unscoped keys rather than converting it into global JWT scopes.
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%2F42297&comment_hash=875c033e7cbc198e7006cb4daf6f1e071cde7298825798a25f85394fff0ebae6&reaction=like'>π</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42297&comment_hash=875c033e7cbc198e7006cb4daf6f1e071cde7298825798a25f85394fff0ebae6&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #42297:
URL: https://github.com/apache/superset/pull/42297#discussion_r3785666572
##########
superset/mcp_service/auth.py:
##########
@@ -400,7 +435,9 @@ def check_tool_permission( # noqa: C901
# advertises scopes. Tokens/deployments that don't use scopes (API keys,
# scope-less JWTs, dev-mode) fall through to RBAC-only behavior β see
# ``_token_scope_allows``.
- if has_permission and not _token_scope_allows(method_permission_name):
+ if has_permission and not _token_scope_allows(
Review Comment:
Addressed in f9f1aba40. Permission-less tools now still enforce the token method scope: unscoped tokens retain the existing behavior, a flat `superset:read` token can call a read-class permission-less tool, and a resource-only token such as `superset:dashboard:read` cannot. Added the suggested regression coverage.
##########
superset/security/manager.py:
##########
@@ -4926,6 +4927,116 @@ def parse_jwt_guest_token(self, raw_token: str) -> dict[str, Any]:
raw_token, secret, algorithms=[algo], audience=audience
)
+ def get_api_key_scopes(self, api_key_string: str) -> Optional[str]:
+ """Return the ``scopes`` value for a validated API key.
+
+ FAB's ``validate_api_key`` resolves the matching ``ApiKey`` row
+ internally (by lookup hash) but only returns the associated
+ ``User`` β the row's ``scopes`` column is otherwise unreachable by
+ callers. This repeats the same cheap, indexed lookup so MCP's
+ ``CompositeTokenVerifier`` can propagate per-key scopes instead of
+ silently falling back to verifier-global scopes. Call only after
+ ``validate_api_key`` has already succeeded for this token β this
+ method does not itself verify the key hash or active status.
+ """
+ lookup = self._compute_lookup_hash(api_key_string) # type: ignore[attr-defined]
+ api_key = (
+ self.session.query(self.api_key_model) # type: ignore[attr-defined]
+ .filter(self.api_key_model.lookup_hash == lookup)
+ .one_or_none()
+ )
+ return api_key.scopes if api_key else None
+
+ def _validate_requested_api_key_scopes(
+ self, user: Any, scopes: Optional[str]
+ ) -> None:
+ """Raise if ``scopes`` would grant a user more than their own RBAC.
+
+ Enforces the "intersection, never broader" rule confirmed for this
+ feature: a user must never be able to mint a token scoped beyond
+ what their own role already permits, even if they hand-author the
+ scopes string themselves at issuance time.
+
+ Per-resource scopes (``superset:<resource>:<action>``) are checked
+ against the user's actual ``can_<method>`` RBAC grant for that
+ resource. Flat scopes (``superset:read``/``superset:write``, the
+ pre-per-resource form) can only be self-issued by Admins β a flat
+ scope grants a method across every resource, and there's no single
+ RBAC check that soundly proves a non-Admin has that for "every
+ resource," so it's rejected for anyone else rather than guessed at.
+ Unrecognized scope strings are rejected outright (fail closed).
+
+ NOTE: this only prevents the request from being honored; it does
+ not (yet) produce a clean 400 response, since FAB's ``ApiKeyApi``
+ has no validation hook this can plug into without replacing the API
+ registration entirely. Raising here surfaces as a 500 via FAB's
+ ``@safe`` decorator until that's addressed β tracked as a known
+ follow-up, not silently accepted.
+ """
+ if not scopes:
+ return
+ # pylint: disable-next=import-outside-toplevel
+ from superset.security.api_key_scopes import (
+ RESOURCE_SCOPE_ACTIONS,
+ RESOURCE_SCOPE_CLASS,
+ )
+
+ is_admin = any(role.name == "Admin" for role in getattr(user, "roles", []))
+ for raw_scope in scopes.split(","):
+ scope = raw_scope.strip()
+ if not scope:
+ continue
+ parts = scope.split(":")
+ if len(parts) == 3 and parts[0] == "superset":
+ _, resource_slug, action = parts
+ class_permission_name = RESOURCE_SCOPE_CLASS.get(resource_slug)
+ if class_permission_name is None:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"resource '{resource_slug}'"
+ )
+ if action not in RESOURCE_SCOPE_ACTIONS:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"action '{action}'"
+ )
+ if self._has_view_access(user, f"can_{action}", class_permission_name):
Review Comment:
Addressed in f9f1aba40. Issuance now uses the inverse of the canonical runtime method-to-action mapping, so `user:read`/`role:read` accept `can_get` and `sqllab:write` accepts `can_execute_sql_query` while remaining bounded by the issuing userβs actual permission. Added parameterized regression coverage for all three cases.
##########
superset/security/manager.py:
##########
@@ -4926,6 +4927,116 @@ def parse_jwt_guest_token(self, raw_token: str) -> dict[str, Any]:
raw_token, secret, algorithms=[algo], audience=audience
)
+ def get_api_key_scopes(self, api_key_string: str) -> Optional[str]:
+ """Return the ``scopes`` value for a validated API key.
+
+ FAB's ``validate_api_key`` resolves the matching ``ApiKey`` row
+ internally (by lookup hash) but only returns the associated
+ ``User`` β the row's ``scopes`` column is otherwise unreachable by
+ callers. This repeats the same cheap, indexed lookup so MCP's
+ ``CompositeTokenVerifier`` can propagate per-key scopes instead of
+ silently falling back to verifier-global scopes. Call only after
+ ``validate_api_key`` has already succeeded for this token β this
+ method does not itself verify the key hash or active status.
+ """
+ lookup = self._compute_lookup_hash(api_key_string) # type: ignore[attr-defined]
+ api_key = (
+ self.session.query(self.api_key_model) # type: ignore[attr-defined]
+ .filter(self.api_key_model.lookup_hash == lookup)
+ .one_or_none()
+ )
+ return api_key.scopes if api_key else None
+
+ def _validate_requested_api_key_scopes(
+ self, user: Any, scopes: Optional[str]
+ ) -> None:
+ """Raise if ``scopes`` would grant a user more than their own RBAC.
+
+ Enforces the "intersection, never broader" rule confirmed for this
+ feature: a user must never be able to mint a token scoped beyond
+ what their own role already permits, even if they hand-author the
+ scopes string themselves at issuance time.
+
+ Per-resource scopes (``superset:<resource>:<action>``) are checked
+ against the user's actual ``can_<method>`` RBAC grant for that
+ resource. Flat scopes (``superset:read``/``superset:write``, the
+ pre-per-resource form) can only be self-issued by Admins β a flat
+ scope grants a method across every resource, and there's no single
+ RBAC check that soundly proves a non-Admin has that for "every
+ resource," so it's rejected for anyone else rather than guessed at.
+ Unrecognized scope strings are rejected outright (fail closed).
+
+ NOTE: this only prevents the request from being honored; it does
+ not (yet) produce a clean 400 response, since FAB's ``ApiKeyApi``
+ has no validation hook this can plug into without replacing the API
+ registration entirely. Raising here surfaces as a 500 via FAB's
+ ``@safe`` decorator until that's addressed β tracked as a known
+ follow-up, not silently accepted.
+ """
+ if not scopes:
+ return
+ # pylint: disable-next=import-outside-toplevel
+ from superset.security.api_key_scopes import (
+ RESOURCE_SCOPE_ACTIONS,
+ RESOURCE_SCOPE_CLASS,
+ )
+
+ is_admin = any(role.name == "Admin" for role in getattr(user, "roles", []))
Review Comment:
Addressed in f9f1aba40. Flat-scope issuance now resolves the Admin role through `AUTH_ROLE_ADMIN`, consistent with `is_admin()`, with a custom-role-name regression test.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5108532502
@aminghadersohi one thing before this merges: `_validate_requested_api_key_scopes` takes `user` as a param, but the actual check (`superset/security/manager.py` around line 4863, `self.can_access(f"can_{method}", class_permission_name)`) checks `g.user`, not that argument. It happens to line up today since the only caller (FAB's `ApiKeyApi`) passes `sm.current_user`, but the whole point of the function is validating the passed-in user. Bito flagged the same line, filtered from actually posting. Worth swapping to `self._has_view_access(user, f"can_{method}", class_permission_name)` so it checks the argument, not whoever's logged in.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5244796418
Heya! `superset/security/api_key_scopes.py`'s `METHOD_PERMISSION_SCOPE_ACTION` still has no `update` entry (Bito flagged this too). Nothing uses `method_permission_name="update"` today so it fails closed rather than leaking anything, but whoever adds the first update-style tool is going to be confused why scoped tokens get silently denied. Worth a quick add now while it's fresh.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5042191158
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/42297?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `13.11475%` with `53 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 65.13%. Comparing base ([`60a7c18`](https://app.codecov.io/gh/apache/superset/commit/60a7c18204baffd11a7c61711d39cefa5eefdbb0?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`612e184`](https://app.codecov.io/gh/apache/superset/commit/612e18488fc4a8bb012c1d9a658318f38fdc7a97?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 1 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/42297?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [superset/security/manager.py](https://app.codecov.io/gh/apache/superset/pull/42297?src=pr&el=tree&filepath=superset%2Fsecurity%2Fmanager.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvc2VjdXJpdHkvbWFuYWdlci5weQ==) | 12.90% | [27 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/42297?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/mcp\_service/auth.py](https://app.codecov.io/gh/apache/superset/pull/42297?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fauth.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvYXV0aC5weQ==) | 15.78% | [16 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/42297?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/mcp\_service/composite\_token\_verifier.py](https://app.codecov.io/gh/apache/superset/pull/42297?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fcomposite_token_verifier.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvY29tcG9zaXRlX3Rva2VuX3ZlcmlmaWVyLnB5) | 9.09% | [10 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/42297?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #42297 +/- ##
==========================================
- Coverage 65.15% 65.13% -0.02%
==========================================
Files 2789 2789
Lines 157543 157595 +52
Branches 35864 35876 +12
==========================================
+ Hits 102644 102647 +3
- Misses 52931 52979 +48
- Partials 1968 1969 +1
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Ξ | |
|---|---|---|
| [hive](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `38.72% <13.11%> (-0.02%)` | :arrow_down: |
| [mysql](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.62% <13.11%> (-0.04%)` | :arrow_down: |
| [postgres](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.67% <13.11%> (-0.04%)` | :arrow_down: |
| [presto](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `40.63% <13.11%> (-0.02%)` | :arrow_down: |
| [python](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `59.05% <13.11%> (-0.04%)` | :arrow_down: |
| [sqlite](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.29% <13.11%> (-0.04%)` | :arrow_down: |
| [unit](https://app.codecov.io/gh/apache/superset/pull/42297/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `100.00% <ΓΈ> (ΓΈ)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/42297?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #42297:
URL: https://github.com/apache/superset/pull/42297#discussion_r3781490000
##########
superset/mcp_service/auth.py:
##########
@@ -223,12 +250,16 @@ def _log_scope_denial(
cyclomatic complexity in check.
"""
required_scope = _METHOD_TO_REQUIRED_SCOPE.get(method_permission_name)
+ resource_scope = _required_resource_scope(
+ class_permission_name, method_permission_name
+ )
+ scope_desc = resource_scope or required_scope
Review Comment:
`_log_scope_denial` can log a required scope of `None` when a scoped token hits an unmapped `method_permission_name` (since `_METHOD_TO_REQUIRED_SCOPE.get(...)` returns None). This makes the log message less actionable; using an explicit fallback string keeps logs clear while still failing closed.
##########
superset/security/manager.py:
##########
@@ -4926,6 +4927,111 @@ def parse_jwt_guest_token(self, raw_token: str) -> dict[str, Any]:
raw_token, secret, algorithms=[algo], audience=audience
)
+ def get_api_key_scopes(self, api_key_string: str) -> Optional[str]:
+ """Return the ``scopes`` value for a validated API key.
+
+ FAB's ``validate_api_key`` resolves the matching ``ApiKey`` row
+ internally (by lookup hash) but only returns the associated
+ ``User`` β the row's ``scopes`` column is otherwise unreachable by
+ callers. This repeats the same cheap, indexed lookup so MCP's
+ ``CompositeTokenVerifier`` can propagate per-key scopes instead of
+ silently falling back to verifier-global scopes. Call only after
+ ``validate_api_key`` has already succeeded for this token β this
+ method does not itself verify the key hash or active status.
+ """
+ lookup = self._compute_lookup_hash(api_key_string) # type: ignore[attr-defined]
+ api_key = (
+ self.session.query(self.api_key_model) # type: ignore[attr-defined]
+ .filter(self.api_key_model.lookup_hash == lookup)
+ .one_or_none()
+ )
+ return api_key.scopes if api_key else None
+
+ def _validate_requested_api_key_scopes(
+ self, user: Any, scopes: Optional[str]
+ ) -> None:
+ """Raise if ``scopes`` would grant a user more than their own RBAC.
+
+ Enforces the "intersection, never broader" rule confirmed for this
+ feature: a user must never be able to mint a token scoped beyond
+ what their own role already permits, even if they hand-author the
+ scopes string themselves at issuance time.
+
+ Per-resource scopes (``superset:<resource>:<action>``) are checked
+ against the user's actual ``can_<method>`` RBAC grant for that
+ resource. Flat scopes (``superset:read``/``superset:write``, the
+ pre-per-resource form) can only be self-issued by Admins β a flat
+ scope grants a method across every resource, and there's no single
+ RBAC check that soundly proves a non-Admin has that for "every
+ resource," so it's rejected for anyone else rather than guessed at.
+ Unrecognized scope strings are rejected outright (fail closed).
+
+ NOTE: this only prevents the request from being honored; it does
+ not (yet) produce a clean 400 response, since FAB's ``ApiKeyApi``
+ has no validation hook this can plug into without replacing the API
+ registration entirely. Raising here surfaces as a 500 via FAB's
+ ``@safe`` decorator until that's addressed β tracked as a known
+ follow-up, not silently accepted.
+ """
+ if not scopes:
+ return
+ # pylint: disable-next=import-outside-toplevel
+ from superset.security.api_key_scopes import (
+ RESOURCE_SCOPE_ACTIONS,
+ RESOURCE_SCOPE_CLASS,
+ )
+
+ is_admin = any(role.name == "Admin" for role in getattr(user, "roles", []))
+ for raw_scope in scopes.split(","):
+ scope = raw_scope.strip()
+ if not scope:
+ continue
+ parts = scope.split(":")
+ if len(parts) == 3 and parts[0] == "superset":
+ _, resource_slug, action = parts
+ class_permission_name = RESOURCE_SCOPE_CLASS.get(resource_slug)
+ if class_permission_name is None:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"resource '{resource_slug}'"
+ )
+ if action not in RESOURCE_SCOPE_ACTIONS:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"action '{action}'"
+ )
+ if self._has_view_access(user, f"can_{action}", class_permission_name):
+ continue
+ raise ValueError(
+ f"Requested scope '{scope}' exceeds the issuing user's "
+ "own permissions"
+ )
+ if len(parts) == 2 and parts[0] == "superset" and is_admin:
+ continue
+ raise ValueError(
+ f"Requested scope '{scope}' is not a recognized "
+ "superset:<resource>:<action> scope, or requires Admin to "
Review Comment:
`_validate_requested_api_key_scopes` currently treats any 2-part scope of the form `superset:<anything>` as valid for Admin users. That allows an Admin to mint keys with unrecognized flat scopes (e.g. `superset:garbage`), contradicting the "fail closed" intent and making enforcement behavior undefined for those tokens. Restrict flat scopes to the supported action vocabulary (read/write).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5263055525
Friendly nudge β review was requested here on 2026-07-27 (16 days ago) and this is still `REVIEW_REQUIRED`. CI is green (43 checks passing) and the branch is up to date.
@mistercrunch @rusackas @villebro β if any of you has bandwidth for a pass on the per-resource token scopes / user-permission intersection logic, that would unblock it. If this is not the right reviewer set, say so and we will re-route.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5320177632
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5098427919
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5186204303
Addressed in 9ea986e3517afba3445466d5197ecf8acac4df1e. `_validate_requested_api_key_scopes` now calls `_has_view_access(user, ...)`, so authorization is evaluated against the passed-in user rather than `g.user`. I also updated the unit tests to assert that the requested user is forwarded to the RBAC check.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5262202890
@rusackas Done in 033454c20bbc716e0a8c76c992c534a4825df3b2 β added `"update": "write"` to the canonical method-permission scope mapping and a regression assertion that `Chart/update` resolves to `superset:chart:write`. Thanks for calling this out.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5324710523
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5186264113
Follow-up review improvements are in 169afa3d7f456c542712c939fb92f2481d9d4c2e:
- Moved the canonical method/action and class/resource mappings into `superset.security.api_key_scopes`, avoiding the security manager depending on MCP internals and eliminating duplicated mapping logic.
- Issuance now rejects unsupported action strings instead of accepting values such as `delete`, `update`, or arbitrary text that runtime enforcement can never match. The supported contract in this PR is explicitly the coarse `read`/`write` action model.
- Added regression coverage for unsupported actions.
I also audited the concern that mutate tools might inherit read access. That is already handled by `create_tool_decorator`: when `method_permission_name` is omitted, a `mutate` tag sets `_method_permission_name` to `write` (`superset/core/mcp/core_mcp_injection.py`). Therefore the cited delete/update tools require write scope despite omitting the explicit decorator argument.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5263580088
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5291538479
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5041641104
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #42297:
URL: https://github.com/apache/superset/pull/42297#discussion_r3717204811
##########
superset/mcp_service/auth.py:
##########
@@ -398,7 +467,9 @@ def check_tool_permission( # noqa: C901
# advertises scopes. Tokens/deployments that don't use scopes (API keys,
# scope-less JWTs, dev-mode) fall through to RBAC-only behavior β see
# ``_token_scope_allows``.
- if has_permission and not _token_scope_allows(method_permission_name):
+ if has_permission and not _token_scope_allows(
+ method_permission_name, class_permission_name
+ ):
_log_scope_denial(
Review Comment:
Fixed in 6af6c99791a2504ac47e3d40cc058b9dbc309fa5. `get_schema` now intersects its dynamic per-model RBAC check with `_token_scope_allows("read", class_permission)`, and a regression test proves RBAC access alone cannot bypass a mismatched token resource scope.
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -168,32 +181,38 @@ async def verify_token(self, token: str) -> AccessToken | None:
if any(token.startswith(prefix) for prefix in self._api_key_prefixes):
if self._app is not None:
loop = asyncio.get_running_loop()
- username = await loop.run_in_executor(
+ result = await loop.run_in_executor(
None, self._validate_api_key_sync, token
)
- if username is None:
+ if result is None:
logger.debug(
"API key rejected at transport layer (invalid or expired)"
)
return None
+ username, key_scopes = result
logger.debug(
"API key validated at transport layer for user=%s", username
)
return AccessToken(
token=token,
client_id="api_key",
- scopes=list(self.required_scopes or []),
+ # Prefer the key's own scopes over verifier-global
+ # required_scopes. Empty list = no scopes set = "no scopes
+ # advertised" back-compat per auth.py's
+ # _get_token_scopes()/_token_scope_allows().
+ scopes=key_scopes or list(self.required_scopes or []),
Review Comment:
Fixed in 6af6c99791a2504ac47e3d40cc058b9dbc309fa5. Transport-validated API keys now preserve `key_scopes` exactly, including an empty list for legacy unscoped/RBAC-only keys, rather than substituting verifier-global JWT requirements. The test now covers a global required scope being configured while the API key remains unscoped.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5187301660
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #42297:
URL: https://github.com/apache/superset/pull/42297#discussion_r3781790433
##########
superset/security/manager.py:
##########
@@ -4926,6 +4927,111 @@ def parse_jwt_guest_token(self, raw_token: str) -> dict[str, Any]:
raw_token, secret, algorithms=[algo], audience=audience
)
+ def get_api_key_scopes(self, api_key_string: str) -> Optional[str]:
+ """Return the ``scopes`` value for a validated API key.
+
+ FAB's ``validate_api_key`` resolves the matching ``ApiKey`` row
+ internally (by lookup hash) but only returns the associated
+ ``User`` β the row's ``scopes`` column is otherwise unreachable by
+ callers. This repeats the same cheap, indexed lookup so MCP's
+ ``CompositeTokenVerifier`` can propagate per-key scopes instead of
+ silently falling back to verifier-global scopes. Call only after
+ ``validate_api_key`` has already succeeded for this token β this
+ method does not itself verify the key hash or active status.
+ """
+ lookup = self._compute_lookup_hash(api_key_string) # type: ignore[attr-defined]
+ api_key = (
+ self.session.query(self.api_key_model) # type: ignore[attr-defined]
+ .filter(self.api_key_model.lookup_hash == lookup)
+ .one_or_none()
+ )
+ return api_key.scopes if api_key else None
+
+ def _validate_requested_api_key_scopes(
+ self, user: Any, scopes: Optional[str]
+ ) -> None:
+ """Raise if ``scopes`` would grant a user more than their own RBAC.
+
+ Enforces the "intersection, never broader" rule confirmed for this
+ feature: a user must never be able to mint a token scoped beyond
+ what their own role already permits, even if they hand-author the
+ scopes string themselves at issuance time.
+
+ Per-resource scopes (``superset:<resource>:<action>``) are checked
+ against the user's actual ``can_<method>`` RBAC grant for that
+ resource. Flat scopes (``superset:read``/``superset:write``, the
+ pre-per-resource form) can only be self-issued by Admins β a flat
+ scope grants a method across every resource, and there's no single
+ RBAC check that soundly proves a non-Admin has that for "every
+ resource," so it's rejected for anyone else rather than guessed at.
+ Unrecognized scope strings are rejected outright (fail closed).
+
+ NOTE: this only prevents the request from being honored; it does
+ not (yet) produce a clean 400 response, since FAB's ``ApiKeyApi``
+ has no validation hook this can plug into without replacing the API
+ registration entirely. Raising here surfaces as a 500 via FAB's
+ ``@safe`` decorator until that's addressed β tracked as a known
+ follow-up, not silently accepted.
+ """
+ if not scopes:
+ return
+ # pylint: disable-next=import-outside-toplevel
+ from superset.security.api_key_scopes import (
+ RESOURCE_SCOPE_ACTIONS,
+ RESOURCE_SCOPE_CLASS,
+ )
+
+ is_admin = any(role.name == "Admin" for role in getattr(user, "roles", []))
+ for raw_scope in scopes.split(","):
+ scope = raw_scope.strip()
+ if not scope:
+ continue
+ parts = scope.split(":")
+ if len(parts) == 3 and parts[0] == "superset":
+ _, resource_slug, action = parts
+ class_permission_name = RESOURCE_SCOPE_CLASS.get(resource_slug)
+ if class_permission_name is None:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"resource '{resource_slug}'"
+ )
+ if action not in RESOURCE_SCOPE_ACTIONS:
+ raise ValueError(
+ f"Requested scope '{scope}' names an unrecognized "
+ f"action '{action}'"
+ )
+ if self._has_view_access(user, f"can_{action}", class_permission_name):
+ continue
+ raise ValueError(
+ f"Requested scope '{scope}' exceeds the issuing user's "
+ "own permissions"
+ )
+ if len(parts) == 2 and parts[0] == "superset" and is_admin:
+ continue
+ raise ValueError(
+ f"Requested scope '{scope}' is not a recognized "
+ "superset:<resource>:<action> scope, or requires Admin to "
Review Comment:
Fixed in 0efacae626a80f9b1e7c4362a5c7c709d2b92037. Admin flat scopes are now accepted only when the action is in the supported read/write vocabulary; undefined values such as `superset:garbage` fail closed. Added regression coverage.
##########
superset/mcp_service/auth.py:
##########
@@ -223,12 +250,16 @@ def _log_scope_denial(
cyclomatic complexity in check.
"""
required_scope = _METHOD_TO_REQUIRED_SCOPE.get(method_permission_name)
+ resource_scope = _required_resource_scope(
+ class_permission_name, method_permission_name
+ )
+ scope_desc = resource_scope or required_scope
Review Comment:
Fixed in 0efacae626a80f9b1e7c4362a5c7c709d2b92037. Scope-denial logs now use an explicit `unmapped method permission <name>` fallback instead of logging a required scope of `None`, with regression coverage.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #42297:
URL: https://github.com/apache/superset/pull/42297#discussion_r3798792578
##########
superset-frontend/scripts/bundle-size-summary.js:
##########
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+// Reduces a webpack `--json` stats file down to the handful of headline
+// numbers worth tracking over time, in the flat array format
+// benchmark-action/github-action-benchmark expects for its
+// "customSmallerIsBetter" tool. The full stats file also includes a
+// `modules`/`chunks` graph across ~15k modules, which is enormous and not
+// useful for this purpose, so we only ever read `entrypoints`.
+//
+// Usage: node scripts/bundle-size-summary.js <path-to-stats.json>
+
+const fs = require('fs');
+
+// Entrypoints worth tracking: the two user-facing app shells. `menu`,
+// `preamble`, `theme`, and `service-worker` are small, low-variance
+// infrastructure chunks, not where bundle bloat actually shows up.
+const TRACKED_ENTRYPOINTS = ['spa', 'embedded'];
+
+function entrypointSizeByExt(entrypoint, ext) {
+ return (entrypoint.assets || [])
+ .filter(asset => asset.name.endsWith(ext))
+ .reduce((total, asset) => total + asset.size, 0);
+}
+
+function main() {
+ const statsPath = process.argv[2];
+ if (!statsPath) {
+ console.error('Usage: bundle-size-summary.js <path-to-stats.json>');
+ process.exit(1);
+ }
+
+ const stats = JSON.parse(fs.readFileSync(statsPath, 'utf8'));
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Validate fs readFileSync path argument</b></div>
<div id="fix">
Security: `readFileSync` uses a non-literal path argument (`statsPath` from CLI), which could allow path traversal attacks if the script is used with untrusted input.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
if (!statsPath) {
console.error('Usage: bundle-size-summary.js <path-to-stats.json>');
process.exit(1);
}
// Validate and sanitize the file path
const path = require('path');
const resolvedPath = path.resolve(statsPath);
if (!resolvedPath.endsWith('.json')) {
console.error('Error: Only JSON files are allowed.');
process.exit(1);
}
const stats = JSON.parse(fs.readFileSync(statsPath, 'utf8'));
````
</div>
</details>
</div>
<small><i>Code Review Run #0c5f62</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset/mcp_service/system/tool/get_schema.py:
##########
@@ -235,9 +235,10 @@ async def get_schema(
from superset import security_manager
- if current_app.config.get("MCP_RBAC_ENABLED", True) and not (
- security_manager.can_access("can_read", class_permission)
- ):
+ rbac_allows = not current_app.config.get(
+ "MCP_RBAC_ENABLED", True
+ ) or security_manager.can_access("can_read", class_permission)
+ if not (rbac_allows and _token_scope_allows("read", class_permission)):
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>CWE-285: RBAC Logic Bypass</b></div>
<div id="fix">
The refactor changed the RBAC logic. When `MCP_RBAC_ENABLED=False`, the original code denies access (`False and not(...) = False`), but the new code may allow access depending on token scopes. This bypasses the intended feature flag behavior. ([CWE-285](https://cwe.mitre.org/data/definitions/285.html))
</div>
</div>
<small><i>Code Review Run #0c5f62</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset-frontend/scripts/bundle-size-summary.js:
##########
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+// Reduces a webpack `--json` stats file down to the handful of headline
+// numbers worth tracking over time, in the flat array format
+// benchmark-action/github-action-benchmark expects for its
+// "customSmallerIsBetter" tool. The full stats file also includes a
+// `modules`/`chunks` graph across ~15k modules, which is enormous and not
+// useful for this purpose, so we only ever read `entrypoints`.
+//
+// Usage: node scripts/bundle-size-summary.js <path-to-stats.json>
+
+const fs = require('fs');
+
+// Entrypoints worth tracking: the two user-facing app shells. `menu`,
+// `preamble`, `theme`, and `service-worker` are small, low-variance
+// infrastructure chunks, not where bundle bloat actually shows up.
+const TRACKED_ENTRYPOINTS = ['spa', 'embedded'];
+
+function entrypointSizeByExt(entrypoint, ext) {
+ return (entrypoint.assets || [])
+ .filter(asset => asset.name.endsWith(ext))
+ .reduce((total, asset) => total + asset.size, 0);
+}
+
+function main() {
+ const statsPath = process.argv[2];
+ if (!statsPath) {
+ console.error('Usage: bundle-size-summary.js <path-to-stats.json>');
+ process.exit(1);
+ }
+
+ const stats = JSON.parse(fs.readFileSync(statsPath, 'utf8'));
+ const { entrypoints } = stats;
+ if (!entrypoints) {
+ console.error(
+ 'stats.json has no `entrypoints` key -- was it built with ' +
+ '`BUNDLE_SIZE_STATS=true` set? Without it, webpack.config.js uses ' +
+ '`stats: "minimal"`, which omits `entrypoints`.',
+ );
+ process.exit(1);
+ }
+
+ const results = [];
+ TRACKED_ENTRYPOINTS.forEach(name => {
+ const entrypoint = entrypoints[name];
+ if (!entrypoint) {
+ console.error(`stats.json is missing the "${name}" entrypoint`);
+ process.exit(1);
+ }
+ results.push({
+ name: `${name} entrypoint (JS)`,
+ unit: 'bytes',
+ value: entrypointSizeByExt(entrypoint, '.js'),
+ });
+ results.push({
+ name: `${name} entrypoint (CSS)`,
+ unit: 'bytes',
+ value: entrypointSizeByExt(entrypoint, '.css'),
+ });
+ });
+
+ console.log(JSON.stringify(results, null, 2));
+}
+
+if (require.main === module) {
+ main();
+}
+
+module.exports = { entrypointSizeByExt, main, TRACKED_ENTRYPOINTS };
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing unit tests for new tool</b></div>
<div id="fix">
Add unit tests covering success paths, error scenarios, and edge cases. The script currently has no test coverage, which increases regression risk for this critical CI instrumentation. Rule [11730] requires comprehensive tests for new tools.
</div>
</div>
<small><i>Code Review Run #0c5f62</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset-frontend/scripts/bundle-size-summary.js:
##########
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+// Reduces a webpack `--json` stats file down to the handful of headline
+// numbers worth tracking over time, in the flat array format
+// benchmark-action/github-action-benchmark expects for its
+// "customSmallerIsBetter" tool. The full stats file also includes a
+// `modules`/`chunks` graph across ~15k modules, which is enormous and not
+// useful for this purpose, so we only ever read `entrypoints`.
+//
+// Usage: node scripts/bundle-size-summary.js <path-to-stats.json>
+
+const fs = require('fs');
+
+// Entrypoints worth tracking: the two user-facing app shells. `menu`,
+// `preamble`, `theme`, and `service-worker` are small, low-variance
+// infrastructure chunks, not where bundle bloat actually shows up.
+const TRACKED_ENTRYPOINTS = ['spa', 'embedded'];
+
+function entrypointSizeByExt(entrypoint, ext) {
+ return (entrypoint.assets || [])
+ .filter(asset => asset.name.endsWith(ext))
+ .reduce((total, asset) => total + asset.size, 0);
+}
+
+function main() {
+ const statsPath = process.argv[2];
+ if (!statsPath) {
+ console.error('Usage: bundle-size-summary.js <path-to-stats.json>');
+ process.exit(1);
+ }
+
+ const stats = JSON.parse(fs.readFileSync(statsPath, 'utf8'));
+ const { entrypoints } = stats;
+ if (!entrypoints) {
+ console.error(
+ 'stats.json has no `entrypoints` key -- was it built with ' +
+ '`BUNDLE_SIZE_STATS=true` set? Without it, webpack.config.js uses ' +
+ '`stats: "minimal"`, which omits `entrypoints`.',
+ );
+ process.exit(1);
+ }
+
+ const results = [];
+ TRACKED_ENTRYPOINTS.forEach(name => {
+ const entrypoint = entrypoints[name];
+ if (!entrypoint) {
+ console.error(`stats.json is missing the "${name}" entrypoint`);
+ process.exit(1);
+ }
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>CWE-1321: Validate property access to prevent injection</b></div>
<div id="fix">
Security: Dynamic property access using variable `name` on `entrypoints` object could be exploited if `TRACKED_ENTRYPOINTS` is bypassed ([CWE-1321](https://cwe.mitre.org/data/definitions/1321.html)).
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
}
const results = [];
TRACKED_ENTRYPOINTS.forEach(name => {
if (!TRACKED_ENTRYPOINTS.includes(name)) {
console.error(`Invalid entrypoint: "${name}"`);
process.exit(1);
}
const entrypoint = entrypoints[name];
if (!entrypoint) {
console.error(`stats.json is missing the "${name}" entrypoint`);
process.exit(1);
}
````
</div>
</details>
</div>
<small><i>Code Review Run #0c5f62</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5320188705
### Scope drift and regression guardrails
Leaving this maintenance note for future MCP/API-key work:
- `superset/security/api_key_scopes.py` is the canonical backend source for resource slugs, FAB method-to-`read`/`write` mapping, inverse issuance checks, and scope construction. New MCP code should consume it rather than recreate mappings.
- The UI catalog in `superset-frontend/src/features/apiKeys/apiKeyScopes.ts` necessarily mirrors that backend vocabulary. `test_frontend_scope_catalog_matches_backend_contract` fails if the two catalogs diverge; update both together.
- MCP tool permission metadata is security-sensitive. New or changed tools need the correct `class_permission_name` and `method_permission_name`; mutations must map to write, and unknown mappings must remain fail-closed. Permission-less protected tools require a flat scope.
- Invocation, `tools/list`, tool search/proxy, and dynamic schema discovery must enforce the same scope/RBAC intersection. A new dispatch/discovery path needs matching regression coverage.
- RBAC and credential scopes are independent restrictions. `MCP_RBAC_ENABLED=False` must not erase token scopes, and token-context errors must fail closed.
- These are **MCP scopes**. They do not restrict ordinary REST API requests; comprehensive REST scope enforcement is a separate project.
- Unscoped keys intentionally retain legacy RBAC-only behavior. Flat `superset:read`/`superset:write` remain supported, with flat self-issuance restricted to Admins.
Checklist when adding a resource/action: update the canonical mapping, UI picker, tool metadata, issuance tests, runtime authorization tests, visibility/discovery tests, and operator documentation.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5321722422
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): per-resource token scopes with user-permission intersection [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42297:
URL: https://github.com/apache/superset/pull/42297#issuecomment-5297148095
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org