codeant-ai-for-open-source[bot] commented on code in PR #43431:
URL: https://github.com/apache/superset/pull/43431#discussion_r3838929911


##########
superset/constants.py:
##########
@@ -29,6 +29,7 @@
 
 CHANGE_ME_SECRET_KEY = "CHANGE_ME_TO_A_COMPLEX_RANDOM_SECRET"  # noqa: S105
 CHANGE_ME_GUEST_TOKEN_JWT_SECRET = "test-guest-secret-change-me"  # noqa: S105
+CHANGE_ME_WEBSOCKET_JWT_SECRET = "test-ws-secret-change-me"  # noqa: S105

Review Comment:
   **Suggestion:** This introduces a known, fixed signing key for websocket 
authentication. Any deployment that enables the websocket transport without 
explicitly overriding `WEBSOCKET_JWT_SECRET` allows anyone who knows this 
public default to forge a JWT for arbitrary `user:<id>` channels and receive 
sensitive per-principal events. Do not use a known fallback secret for an 
authentication token; fail startup when a strong deployment-specific key is not 
configured. [security]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Forged sockets can subscribe to arbitrary user channels.
   - ❌ Sensitive per-principal chart events may be exposed.
   - ⚠️ Production configuration permits startup with the known fallback.
   ```
   </details>
   
   [![Use CodeAnt 
Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/constants.py
   **Line:** 32:32
   **Comment:**
        *Security: This introduces a known, fixed signing key for websocket 
authentication. Any deployment that enables the websocket transport without 
explicitly overriding `WEBSOCKET_JWT_SECRET` allows anyone who knows this 
public default to forge a JWT for arbitrary `user:<id>` channels and receive 
sensitive per-principal events. Do not use a known fallback secret for an 
authentication token; fail startup when a strong deployment-specific key is not 
configured.
   
   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%2F43431&comment_hash=e3c77d8e1e870c586cc45839f1c56a64e7cb61908d0f539ad62c5b08c2a2a77f&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43431&comment_hash=e3c77d8e1e870c586cc45839f1c56a64e7cb61908d0f539ad62c5b08c2a2a77f&reaction=dislike'>👎</a>



##########
superset/websocket/channel.py:
##########
@@ -0,0 +1,103 @@
+# 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.
+"""Per-principal websocket channel identity and connection tokens.
+
+The realtime transport delivers a **per-principal** channel's events only to
+that principal's sockets. A channel is derived deterministically from the
+authenticated request principal — ``user:<id>`` for a logged-in user, a stable
+HMAC for an embedded guest — so the task layer can publish a user's events to
+their channel without threading a per-request channel id (unlike the legacy
+per-session-random channel). The channel is minted into a JWT cookie that the
+``superset-websocket`` server verifies to bind a socket to its channel.
+
+This is the connection-auth tier. The lossy public list-view pub/sub
+(``entity-changes:*``) needs no per-principal channel — see
+``TaskManager.publish_entity_change``.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime, timedelta, timezone
+
+import jwt
+from flask import Flask, request, Response
+
+from superset import security_manager
+from superset.tasks.guest import get_current_guest_subscriber_key
+from superset.utils.core import get_user_id
+
+logger = logging.getLogger(__name__)
+
+
+def get_channel_id() -> str | None:
+    """Return the realtime channel for the current request principal, or 
``None``.
+
+    ``user:<id>`` for a logged-in user, ``guest:<hmac>`` for an embedded guest
+    (reusing the guest identity from ``superset.tasks.guest`` for consistency),
+    and ``None`` for an anonymous request (no channel, no cookie).
+    """
+    if security_manager.get_current_guest_user_if_guest():
+        return get_current_guest_subscriber_key()
+    if (user_id := get_user_id()) is not None:
+        return f"user:{user_id}"
+    return None
+
+
+def mint_channel_token(channel_id: str) -> str:
+    """Sign a JWT binding a websocket connection to ``channel_id``.
+
+    The ``superset-websocket`` server verifies this with the same secret and
+    reads the ``channel`` claim to route per-principal events to the socket.
+    """
+    from flask import current_app
+
+    now = datetime.now(tz=timezone.utc)
+    expiration = current_app.config["WEBSOCKET_JWT_EXPIRATION_SECONDS"]
+    payload = {"channel": channel_id, "exp": now + 
timedelta(seconds=expiration)}
+    return jwt.encode(
+        payload, current_app.config["WEBSOCKET_JWT_SECRET"], algorithm="HS256"
+    )
+
+
+def register_ws_channel_cookie(app: Flask) -> None:
+    """Set the websocket channel-token cookie on responses for channel-bearing 
users.
+
+    Mirrors the connection-auth handshake of the legacy async-events transport:
+    an ``httponly`` JWT cookie the browser sends when opening the socket, which
+    the ``superset-websocket`` server verifies. Refreshed only when missing so 
it
+    is not re-signed on every request.
+    """
+    cookie_name = app.config["WEBSOCKET_JWT_COOKIE_NAME"]
+
+    @app.after_request
+    def set_ws_channel_cookie(response: Response) -> Response:
+        channel_id = get_channel_id()
+        if channel_id is None:
+            return response
+        if request.cookies.get(cookie_name):
+            return response

Review Comment:
   **Suggestion:** The cookie is accepted solely because a value with this name 
exists; its JWT is never checked against the current principal or expiration. 
After logout/login, the browser can keep the previous user's token, so the 
websocket server binds the new session to a stale channel and may expose the 
previous user's per-principal events to the newly logged-in user. Decode and 
validate the existing token's channel against `channel_id`, or replace/delete 
it whenever the principal changes. [security]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Cross-user websocket sessions can receive private events.
   - ❌ Dashboard chart-data completion details may leak.
   - ⚠️ Logout/login does not rotate the channel cookie.
   ```
   </details>
   
   [![Use CodeAnt 
Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/websocket/channel.py
   **Line:** 92:93
   **Comment:**
        *Security: The cookie is accepted solely because a value with this name 
exists; its JWT is never checked against the current principal or expiration. 
After logout/login, the browser can keep the previous user's token, so the 
websocket server binds the new session to a stale channel and may expose the 
previous user's per-principal events to the newly logged-in user. Decode and 
validate the existing token's channel against `channel_id`, or replace/delete 
it whenever the principal changes.
   
   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%2F43431&comment_hash=65d665e2609b3123d1103b6cde9f2c0ca04943a2b3efbb38fd0a72bfde83da45&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43431&comment_hash=65d665e2609b3123d1103b6cde9f2c0ca04943a2b3efbb38fd0a72bfde83da45&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to