Skip to content

Security: Harden WebSocket Connection Logic #21

@fred-maina

Description

@fred-maina

Description

The ChatWebSocketHandler has two potential issues:

  1. Token in Query Param: extractUsernameFromJWT looks for the JWT in a query parameter (?token=...). This is a common pattern, but it's less secure than using headers (which WebSockets don't easily support) or a one-time ticket system. The token can be logged in server logs, proxy logs, and browser history.
  2. Anonymous ID Extraction: extractAnonSessionId tries to get the ID from cookies, but falls back to a query parameter (?anonSessionId=...). This is flexible but also creates two different ways to connect.

A more secure approach for authenticated users is to have them hit a standard REST endpoint (/api/ws/ticket) to get a short-lived, one-time-use ticket, and then connect to the WebSocket with ?ticket=....

Acceptance Criteria

  1. Create a new endpoint (e.g., POST /api/auth/ws-ticket) that is secured (requires Authorization header).
  2. When a user hits this endpoint, generate a short-lived (e.g., 30 seconds), one-time-use ticket (e.g., a random UUID) and store it in Redis or a cache with the user's email/ID as the value (e.g., cache.put(ticket, email)).
  3. Modify ChatWebSocketHandler.extractUsernameFromJWT:
    • Rename it to extractUserFromTicket.
    • Change it to look for a ticket query parameter.
    • Validate the ticket against the cache. If it exists, retrieve the user's email/ID and immediately evict the ticket from the cache to prevent reuse.
  4. Remove the token query param logic.
  5. Update documentation (README.md) to reflect this new, more secure connection flow for authenticated users.
  6. The anonSessionId logic can remain as-is, but the query param fallback should be considered for removal in favor of cookies-only.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions