Skip to content

Shared backend auth validator#3857

Closed
timmo001 wants to merge 1 commit into
devfrom
shared-auth-helper
Closed

Shared backend auth validator#3857
timmo001 wants to merge 1 commit into
devfrom
shared-auth-helper

Conversation

@timmo001

@timmo001 timmo001 commented May 6, 2026

Copy link
Copy Markdown
Owner

Note

The following is an LLM summary

This pull request introduces a unified API token authentication mechanism across the backend by creating a reusable auth package and refactoring all HTTP and WebSocket endpoints to use it. The authentication logic is now centralized, making it easier to maintain and extend. Comprehensive tests have been added for the new authentication flows.

The most important changes are:

Authentication Refactor and Centralization:

  • Introduced a new auth package that provides a Validator type, token extraction utilities (supporting Bearer, legacy headers, and query tokens), and standardized error responses. All authentication logic is now handled through this package (backend/auth/auth.go, backend/auth/auth_test.go). [1] [2]
  • Refactored all backend endpoints (HTTP, WebSocket, and MCP) to use the new Validator for token validation, replacing previous scattered and duplicated logic (backend/backend.go, backend/http/data.go, backend/http/media.go, backend/mcp/server.go, backend/mcp/transport.go, backend/websocket/websocket.go, backend/websocket/handlers.go). [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15]

Improved Token Extraction:

  • Enhanced token extraction to prefer Bearer tokens, then legacy headers, and finally (optionally) query parameters, ensuring backward compatibility and flexibility for clients (backend/auth/auth.go).

Testing Enhancements:

  • Added thorough unit tests for the new authentication logic and its integration with the module data, media file, and MCP endpoints (backend/auth/auth_test.go, backend/http/data_test.go, backend/http/media_test.go, backend/mcp/transport_test.go). [1] [2] [3] [4]

Consistent Error Handling:

  • Standardized authentication error responses using JSON error payloads and appropriate HTTP status codes across all endpoints (backend/auth/auth.go, refactored handlers).

Simplification and Code Cleanup:

  • Removed redundant code and utilities related to token loading and validation from various modules, now handled centrally by the auth package (backend/http/data.go, backend/http/media.go). [1] [2]

These changes make authentication more robust, maintainable, and easier to test across the backend.

@vercel

vercel Bot commented May 6, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
system-bridge Ready Ready Preview, Comment May 6, 2026 9:49pm

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR centralizes backend API token authentication into a new reusable backend/auth package, then refactors HTTP, WebSocket, and MCP endpoints to use the shared token extraction + validation helpers, with new unit/integration tests to cover the updated auth flows.

Changes:

  • Added backend/auth with a Validator, token extraction helpers (Bearer + legacy headers + optional query token), and standardized JSON auth error writers.
  • Refactored HTTP data/media handlers, MCP transport auth, and WebSocket message auth to use the new validator/utilities.
  • Added focused tests covering token extraction precedence and endpoint-level authorization behavior.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
backend/auth/auth.go New centralized auth validator, token extraction utilities, and standardized JSON error helpers.
backend/auth/auth_test.go Unit tests for token parsing/extraction precedence and validator behavior.
backend/backend.go Wires shared validator into HTTP handlers and updates media/data route registration.
backend/http/data.go Uses centralized auth utilities for module data endpoint authorization.
backend/http/data_test.go Adds authorization and error-shape tests for the module data endpoint.
backend/http/media.go Converts media handler to a validator-based handler factory and uses centralized token extraction.
backend/http/media_test.go Adds authorization-path tests for media endpoint (Bearer + legacy query token).
backend/mcp/server.go Replaces raw token storage with centralized validator usage.
backend/mcp/transport.go Uses centralized token extraction + standardized unauthorized response for MCP WebSocket auth.
backend/mcp/transport_test.go Adds auth rejection tests for MCP connection handling.
backend/websocket/websocket.go Replaces stored token with centralized validator instance in WebSocket server.
backend/websocket/handlers.go Uses validator-based token validation for incoming WebSocket messages.

Comment thread backend/auth/auth.go
Comment on lines +66 to +70
func writeJSONError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
}
Comment thread backend/http/media.go
Comment on lines +44 to 48
token := backend_auth.TokenFromRequest(r, backend_auth.RequestTokenOptions{AllowQuery: true})
if !validator.ValidateToken(token) {
backend_auth.WriteUnauthorized(w)
return
}
Comment thread backend/http/data.go
Comment on lines +15 to 20
func GetModuleDataHandler(dataStore *data.DataStore, validator *backend_auth.Validator) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
expectedToken, err := utils.LoadToken()
if err != nil {
slog.Error("Failed to load token for authentication", "error", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
if err := json.NewEncoder(w).Encode(map[string]string{"error": "Authentication error"}); err != nil {
slog.Error("Failed to encode response", "error", err)
}
return
}

// Check for API token in both X-API-Token and token headers
token := r.Header.Get("X-API-Token")
if token == "" {
token = r.Header.Get("token")
}
if token != expectedToken {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
if err := json.NewEncoder(w).Encode(map[string]string{"error": "Invalid API token"}); err != nil {
slog.Error("Failed to encode response", "error", err)
}
token := backend_auth.TokenFromRequest(r, backend_auth.RequestTokenOptions{})
if !validator.ValidateToken(token) {
backend_auth.WriteUnauthorized(w)
return
Comment on lines 59 to 63
// Validate token
if msg.Token != ws.token {
if !ws.validator.ValidateToken(msg.Token) {
slog.Error("Invalid token received")
ws.SendError(conn, msg, "BAD_TOKEN", "Invalid token")
continue
Comment thread backend/http/media.go
if err := json.NewEncoder(w).Encode(map[string]string{"error": "Method not allowed"}); err != nil {
slog.Error("Failed to encode response", "error", err)
func ServeMediaFileDataHandler(validator *backend_auth.Validator) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
@timmo001 timmo001 closed this May 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants