← Back to Pull requests

[History Server] Authenticate users against the Kubernetes TokenReview API #5204

Open
KunWuLuan opened this pull request with 803 lines diff across 7 files
View on GitHub
KunWuLuan KunWuLuan commented on Aug 27, 2026 12:10 UTC
Author

Why are these changes needed?

The History Server serves stored session data -- job logs, actor state, node and
event history -- to anyone who can reach its port. There is no authentication of
its own today: the only credential in the codebase is the one it presents to a
live cluster's dashboard (--use-auth-token-mode). Anything already collected
into object storage is readable by any caller.

This adds an opt-in check of the caller's own Kubernetes identity in front of
every data path, via the TokenReview API. It is off by default (--enable-auth),
so existing deployments are unaffected.

The two credentials stay separate: the user's Kubernetes token is never derived
from, nor forwarded as, the Ray auth token, and the egress path strips it before
proxying.

What's in it:

  • auth.go: TokenReview-backed Authenticator with a hash-keyed expirable LRU,

  • so raw tokens are never retained; a container-level AuthFilter gating every
    go-restful WebService; /login and /logout registered outside the filter
    chain so they stay reachable while unauthenticated
  • fail-closed semantics: an invalid token is 401, but a TokenReview outage is

  • 503 -- an unreachable API server must never be mistaken for a valid token
  • header-first extraction: a non-Bearer Authorization header is a hard 401

  • rather than a silent fallback to the cookie, so a misconfigured client cannot
    end up authenticated as whoever the browser session belongs to
  • browser navigations get 302 /login?next=..., XHR callers get the

  • {code,message} JSON error contract. /select_cluster checks explicitly rather
    than rendering a selector whose fetch('/clusters') would 401
  • login validates the token before issuing any Set-Cookie, and the post-login

  • redirect target is constrained to this origin
  • egress hardening: with auth enabled, the Authorization /

  • x-ray-authorization strip on the proxy path becomes unconditional, and
    hs_auth_token is removed from the outgoing Cookie header
  • config/service_account_auth.yaml binds the built-in system:auth-delegator

  • ClusterRole, which is all TokenReview needs

    Scope, and where I'd like input

    This is authentication, not authorization. Any token the cluster accepts can
    read every session the History Server holds -- which matches how the server reads
    storage today: one identity, unaware of who is asking. Restricting a user to the
    namespaces they can already see needs a SubjectAccessReview per request against
    the owning RayCluster; I left that for a follow-up and said so in the README, so
    nobody mistakes --enable-auth for tenant isolation. Happy to fold it into this
    PR instead if you'd rather it land as one piece.

    Two other things I'd rather settle in review than defend later:

    1. The built-in login page. It exists so a single link keeps working in a
    browser, and it takes a pasted kubectl create token value. The alternative is
    to serve only 401/403 and let an OIDC-aware proxy in front handle the human
    flow. I went with the self-contained option because it needs no extra
    infrastructure, but I'll drop it if you'd rather not own login UI here.
    2. restful.Filter as the gate. A container-level filter means new
    WebServices are authenticated by default rather than by remembering to opt in.
    The cost is that /select_cluster, which is a raw http.Handle, needs the
    same check written out explicitly.

    Related issue number

    None.

    Labels

  • If this PR has user-facing changes that require documentation updates at release time, I have added the doc-updates-required label.

  • If this PR contains breaking changes, I have added the breaking-change label.
  • (No label permissions here. This is user-facing but off by default and documented
    in historyserver/README.md; doc-updates-required may still be worth adding at
    release time. Not breaking.)

    Checks

  • I've made sure the tests are passing.

  • Testing Strategy

  • - [x] Unit tests
    - [ ] Manual tests

    auth_test.go covers 401 vs 503 mapping, review caching, header precedence and
    the hard failure on a bad scheme, cookie stripping (including a similarly named
    cookie that must survive), off-origin redirect rejection, the browser-vs-XHR
    branch, and the selector's four states (unauthenticated, authenticated,
    TokenReview down, auth disabled).

    go test ./pkg/...        # whole module passes
    gofmt -l / go vet        # clean on the touched files
    

    Diff: 803 lines (+795 / -8) across 7 files Reviewer: chiayi Review duration: 58051m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.82) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.82 · 803 lines diff across 7 files
    0.82
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.98 · 5 substantive comment(s)
    0.98
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    92%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Sensitive Paths sensitive_paths
    0.082
    Real PR Conversation Timeline
    10 items
    cursor[bot] cursor[bot] commented on code on Aug 27, 2026 12:19 UTC
    Code Review
    historyserver/pkg/historyserver/auth.go:1
    @@ -0,0 +1,312 @@
    +package historyserver
    +
    +import (
    +	"context"
    +	"crypto/sha256"
    +	"encoding/hex"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"html"
    +	"net/http"
    +	"net/url"
    +	"strings"
    +	"time"
    +
    +	"github.com/emicklei/go-restful/v3"
    +	lru "github.com/hashicorp/golang-lru/v2/expirable"
    +	"github.com/sirupsen/logrus"
    +	authv1 "k8s.io/api/authentication/v1"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/client-go/kubernetes"
    +	"k8s.io/client-go/rest"
    +)
    +
    +const (
    +	// AuthCookieName holds the user's own Kubernetes bearer token. It never
    +	// leaves the history server trust domain: the egress path strips it before
    +	// proxying to a live Ray cluster.
    +	AuthCookieName = "hs_auth_token"
    +
    +	// LoginPath and LogoutPath are raw handlers registered outside the
    +	// go-restful filter chain, so they stay reachable without a credential.
    +	LoginPath  = "/login"
    +	LogoutPath = "/logout"
    +
    +	// authCacheSize bounds the number of cached TokenReview results.
    +	authCacheSize = 1024
    +)
    +
    +const (
    +	// DefaultAuthCacheTTL caps how long a revoked token can still be accepted.
    +	DefaultAuthCacheTTL = 60 * time.Second
    +	// DefaultAuthCookieMaxAge matches the lifetime of the cluster context cookies.
    +	DefaultAuthCookieMaxAge = 600 * time.Second
    +)
    +
    +// Authenticator validates user-supplied Kubernetes bearer tokens via the
    +// TokenReview API and caches the outcome for a short window.
    +//
    +// Failure semantics are deliberately asymmetric:
    +//   - an invalid or expired token is a client error (401),
    +//   - a TokenReview infrastructure failure is a server error (503), never a
    +//     silent pass-through. Authentication fails closed.
    +type Authenticator struct {
    +	client kubernetes.Interface
    +	// cache maps sha256(token) -> authenticated username, so raw credentials
    +	// are not retained in memory.
    +	cache *lru.LRU[string, string]
    +}
    +
    +// NewAuthenticator builds an Authenticator from the primary cluster config.
    +func NewAuthenticator(cfg *rest.Config, cacheTTL time.Duration) (*Authenticator, error) {
    +	clientset, err := kubernetes.NewForConfig(cfg)
    +	if err != nil {
    +		return nil, fmt.Errorf("build kubernetes clientset for TokenReview: %w", err)
    +	}
    +	return &Authenticator{
    +		client: clientset,
    +		cache:  lru.NewLRU[string, string](authCacheSize, nil, cacheTTL),
    +	}, nil
    +}
    +
    +// hashToken keys the cache without retaining the raw credential.
    +func hashToken(token string) string {
    +	sum := sha256.Sum256([]byte(token))
    +	return hex.EncodeToString(sum[:])
    +}
    +
    +// authError distinguishes "bad credential" from "cannot tell right now".
    +type authError struct {
    +	msg    string
    +	status int
    +}
    +
    +func (e *authError) Error() string { return e.msg }
    +
    +// authStatus returns the HTTP status an error should map to, defaulting to 401.
    +func authStatus(err error) int {
    +	var aerr *authError
    +	if errors.As(err, &aerr) {
    +		return aerr.status
    +	}
    +	return http.StatusUnauthorized
    +}
    +
    +// Authenticate validates the token and returns the authenticated username.
    +func (a *Authenticator) Authenticate(ctx context.Context, token string) (string, error) {
    +	if token == "" {
    +		return "", &authError{status: http.StatusUnauthorized, msg: "missing authentication token"}
    +	}
    +
    +	key := hashToken(token)
    +	if user, ok := a.cache.Get(key); ok {
    +		return user, nil
    +	}
    +
    +	review := &authv1.TokenReview{Spec: authv1.TokenReviewSpec{Token: token}}
    +	result, err := a.client.AuthenticationV1().TokenReviews().Create(ctx, review, metav1.CreateOptions{})
    +	if err != nil {
    +		// The API server could not answer: refuse rather than guess.
    +		logrus.Errorf("TokenReview request failed: %v", err)
    +		return "", &authError{status: http.StatusServiceUnavailable, msg: "authentication backend unavailable"}
    +	}
    +	if !result.Status.Authenticated {
    +		reason := result.Status.Error
    +		if reason == "" {
    +			reason = "token is not authenticated"
    +		}
    +		return "", &authError{status: http.StatusUnauthorized, msg: reason}
    +	}
    +
    +	user := result.Status.User.Username
    +	a.cache.Add(key, user)
    +	return user, nil
    +}
    +
    +// extractToken pulls the credential from the request, header first.
    +//
    +// A malformed Authorization header is a hard failure instead of falling back to
    +// the cookie: a misconfigured client should fail loudly rather than silently
    +// authenticate as whoever the browser session belongs to.
    +func extractToken(req *http.Request) (string, error) {
    +	if raw := req.Header.Get("Authorization"); raw != "" {
    +		const prefix = "Bearer "
    +		if !strings.HasPrefix(raw, prefix) {
    +			return "", &authError{status: http.StatusUnauthorized, msg: "Authorization header must use the Bearer scheme"}
    +		}
    +		token := strings.TrimSpace(strings.TrimPrefix(raw, prefix))
    +		if token == "" {
    +			return "", &authError{status: http.StatusUnauthorized, msg: "Authorization header carries an empty bearer token"}
    +		}
    +		return token, nil
    +	}
    +	if cookie, err := req.Cookie(AuthCookieName); err == nil && cookie.Value != "" {
    +		return cookie.Value, nil
    +	}
    +	return "", &authError{status: http.StatusUnauthorized, msg: "missing authentication token"}
    +}
    +
    +// wantsHTML reports whether the request is a browser navigation, which should
    +// be redirected to the login page instead of receiving a bare 401.
    +func wantsHTML(req *http.Request) bool {
    +	if req.Header.Get("X-Requested-With") != "" {
    +		return false
    +	}
    +	if mode := req.Header.Get("Sec-Fetch-Mode"); mode != "" {
    +		return mode == "navigate"
    +	}
    +	return strings.Contains(req.Header.Get("Accept"), "text/html")
    +}
    +
    +// AuthFilter authenticates every request flowing through the go-restful
    +// container. It runs before any handler, so dead-cluster serving and live
    +// pass-through are both gated by it.
    +func (s *ServerHandler) AuthFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
    +	if s.authenticator == nil {
    +		chain.ProcessFilter(req, resp)
    +		return
    +	}
    +
    +	token, err := extractToken(req.Request)
    +	if err == nil {
    +		var user string
    +		if user, err = s.authenticator.Authenticate(req.Request.Context(), token); err == nil {
    +			req.SetAttribute(ATTRIBUTE_AUTH_USER, user)
    +			chain.ProcessFilter(req, resp)
    +			return
    +		}
    +	}
    +
    +	status := authStatus(err)
    +	// Browser navigations get a login round-trip so a single link keeps working;
    +	// XHR callers get a machine-readable error instead of an HTML page.
    +	if status == http.StatusUnauthorized && wantsHTML(req.Request) {
    +		next := req.Request.URL.RequestURI()
    +		http.Redirect(resp.ResponseWriter, req.Request, LoginPath+"?next="+url.QueryEscape(next), http.StatusFound)
    +		return
    +	}
    +	writeAuthError(resp.ResponseWriter, status, err.Error())
    +}
    +
    +// writeAuthError follows the repository-wide error contract {"code","message"}.
    +func writeAuthError(w http.ResponseWriter, status int, msg string) {
    +	w.Header().Set("Content-Type", restful.MIME_JSON)
    +	w.WriteHeader(status)
    +	_ = json.NewEncoder(w).Encode(map[string]any{"code": status, "message": msg})
    +}
    +
    +// authCookie builds the session cookie. It is HttpOnly so page scripts cannot
    +// read the Kubernetes token, and SameSite=Lax so it survives a top-level
    +// navigation arriving from an external link.
    +func (s *ServerHandler) authCookie(value string, maxAge int) *http.Cookie {
    +	return &http.Cookie{
    +		Name:     AuthCookieName,
    +		Value:    value,
    +		Path:     "/",
    +		MaxAge:   maxAge,
    +		HttpOnly: true,
    +		Secure:   s.authCookieSecure,
    +		SameSite: http.SameSiteLaxMode,
    +	}
    +}
    +
    +// safeNext keeps the post-login redirect inside this origin, so a crafted link
    +// cannot bounce a freshly authenticated browser to another host.
    +func safeNext(raw string) string {
    +	if raw == "" {
    +		return "/"
    +	}
    +	u, err := url.Parse(raw)
    +	if err != nil || u.IsAbs() || u.Host != "" || !strings.HasPrefix(u.Path, "/") {
    +		return "/"
    +	}
    +	return u.String()
    +}
    +
    +// routerAuth registers /login and /logout as raw handlers, deliberately outside
    +// the go-restful filter chain so they remain reachable while unauthenticated.
    +func routerAuth(s *ServerHandler) {
    +	http.HandleFunc(LoginPath, func(w http.ResponseWriter, r *http.Request) {
    +		if s.authenticator == nil {
    +			http.Redirect(w, r, safeNext(r.URL.Query().Get("next")), http.StatusFound)
    +			return
    +		}
    +
    +		switch r.Method {
    +		case http.MethodGet:
    +			w.Header().Set("Content-Type", "text/html; charset=utf-8")
    +			w.Header().Set("X-Frame-Options", "DENY")
    +			w.Header().Set("X-Content-Type-Options", "nosniff")
    +			w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'")
    +			w.Write(loginPageHTML(safeNext(r.URL.Query().Get("next"))))
    +		case http.MethodPost:
    +			if err := r.ParseForm(); err != nil {
    +				writeAuthError(w, http.StatusBadRequest, "cannot parse login form")
    +				return
    +			}
    +			token := strings.TrimSpace(r.PostFormValue("token"))
    +			next := safeNext(r.PostFormValue("next"))
    +
    +			// Validate before setting any cookie: a rejected credential must not
    +			// leave state behind in the browser.
    +			if _, err := s.authenticator.Authenticate(r.Context(), token); err != nil {
    +				writeAuthError(w, authStatus(err), err.Error())
    +				return

    Login form errors return JSON

    Medium Severity

    <!-- DESCRIPTION START -->
    A failed browser POST to /login responds with a JSON body instead of the HTML login form. The form is the intended human sign-in path, so an invalid or expired token replaces the page with raw JSON and leaves no in-page way to retry.
    <!-- DESCRIPTION END -->

    <!-- BUGBOT_BUG_ID: d1b84ad7-35b9-4cce-a56d-bc198c0efa9f -->

    <!-- LOCATIONS START
    historyserver/pkg/historyserver/auth.go#L252-L255
    historyserver/pkg/historyserver/auth.go#L243-L246
    LOCATIONS END -->
    <details>
    <summary>Additional Locations (1)</summary>

  • historyserver/pkg/historyserver/auth.go#L243-L246
  • </details>

    <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmUwZTkwZTcxLTc4MWQtNGFmZi1iMWNjLTEwZTY3NTZhMDQ1NCIsImVuY3J5cHRpb25LZXkiOiJRNmpaZ1JROXNOYl9vb3RzN015Ylk4bEVjNzFuU0F0S3RPR2FIOWVXc1BjIiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmUwZTkwZTcxLTc4MWQtNGFmZi1iMWNjLTEwZTY3NTZhMDQ1NCIsImVuY3J5cHRpb25LZXkiOiJRNmpaZ1JROXNOYl9vb3RzN015Ylk4bEVjNzFuU0F0S3RPR2FIOWVXc1BjIiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwck51bWJlciI6NTIwNCwiY29tbWl0U2hhIjoiOGE2Yjc4ZDdkOGQxYzk1ZDg1Yzk1NTI0ZDk3MmE3MDYzODhhNmIwZCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

    <sup>Reviewed by Cursor Bugbot for commit 8a6b78d7d8d1c95d85c95524d972a706388a6b0d. Configure here.</sup>

    cursor[bot] cursor[bot] commented on code on Aug 27, 2026 12:19 UTC
    Code Review
    historyserver/pkg/historyserver/auth.go:1
    @@ -0,0 +1,312 @@
    +package historyserver
    +
    +import (
    +	"context"
    +	"crypto/sha256"
    +	"encoding/hex"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"html"
    +	"net/http"
    +	"net/url"
    +	"strings"
    +	"time"
    +
    +	"github.com/emicklei/go-restful/v3"
    +	lru "github.com/hashicorp/golang-lru/v2/expirable"
    +	"github.com/sirupsen/logrus"
    +	authv1 "k8s.io/api/authentication/v1"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/client-go/kubernetes"
    +	"k8s.io/client-go/rest"
    +)
    +
    +const (
    +	// AuthCookieName holds the user's own Kubernetes bearer token. It never
    +	// leaves the history server trust domain: the egress path strips it before
    +	// proxying to a live Ray cluster.
    +	AuthCookieName = "hs_auth_token"
    +
    +	// LoginPath and LogoutPath are raw handlers registered outside the
    +	// go-restful filter chain, so they stay reachable without a credential.
    +	LoginPath  = "/login"
    +	LogoutPath = "/logout"
    +
    +	// authCacheSize bounds the number of cached TokenReview results.
    +	authCacheSize = 1024
    +)
    +
    +const (
    +	// DefaultAuthCacheTTL caps how long a revoked token can still be accepted.
    +	DefaultAuthCacheTTL = 60 * time.Second
    +	// DefaultAuthCookieMaxAge matches the lifetime of the cluster context cookies.
    +	DefaultAuthCookieMaxAge = 600 * time.Second
    +)
    +
    +// Authenticator validates user-supplied Kubernetes bearer tokens via the
    +// TokenReview API and caches the outcome for a short window.
    +//
    +// Failure semantics are deliberately asymmetric:
    +//   - an invalid or expired token is a client error (401),
    +//   - a TokenReview infrastructure failure is a server error (503), never a
    +//     silent pass-through. Authentication fails closed.
    +type Authenticator struct {
    +	client kubernetes.Interface
    +	// cache maps sha256(token) -> authenticated username, so raw credentials
    +	// are not retained in memory.
    +	cache *lru.LRU[string, string]
    +}
    +
    +// NewAuthenticator builds an Authenticator from the primary cluster config.
    +func NewAuthenticator(cfg *rest.Config, cacheTTL time.Duration) (*Authenticator, error) {
    +	clientset, err := kubernetes.NewForConfig(cfg)
    +	if err != nil {
    +		return nil, fmt.Errorf("build kubernetes clientset for TokenReview: %w", err)
    +	}
    +	return &Authenticator{
    +		client: clientset,
    +		cache:  lru.NewLRU[string, string](authCacheSize, nil, cacheTTL),
    +	}, nil

    Zero TTL caches tokens forever

    Medium Severity

    <!-- DESCRIPTION START -->
    --auth-cache-ttl is passed straight into the expirable LRU, where a TTL of 0 or a negative duration means entries never expire. That contradicts the flag text that a revoked token works for at most this long, and unlike --session-cache-ttl the value is not validated.
    <!-- DESCRIPTION END -->

    <!-- BUGBOT_BUG_ID: 9af2273e-b6d7-4193-b17b-2df23083cb0f -->

    <!-- LOCATIONS START
    historyserver/pkg/historyserver/auth.go#L66-L70
    historyserver/cmd/historyserver/main.go#L51-L52
    LOCATIONS END -->
    <details>
    <summary>Additional Locations (1)</summary>

  • historyserver/cmd/historyserver/main.go#L51-L52
  • </details>

    <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjRlNjU5MTRiLTc3MjQtNDA4OC04YjZmLTRmMmZlN2QyOTVkNCIsImVuY3J5cHRpb25LZXkiOiJ4aGU1eVZsc29VTFItenFqM21xVk1SSkVfcFdwRXNWX1hmTTBuSGFTVEhRIiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjRlNjU5MTRiLTc3MjQtNDA4OC04YjZmLTRmMmZlN2QyOTVkNCIsImVuY3J5cHRpb25LZXkiOiJ4aGU1eVZsc29VTFItenFqM21xVk1SSkVfcFdwRXNWX1hmTTBuSGFTVEhRIiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwck51bWJlciI6NTIwNCwiY29tbWl0U2hhIjoiOGE2Yjc4ZDdkOGQxYzk1ZDg1Yzk1NTI0ZDk3MmE3MDYzODhhNmIwZCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

    <sup>Reviewed by Cursor Bugbot for commit 8a6b78d7d8d1c95d85c95524d972a706388a6b0d. Configure here.</sup>

    cursor[bot] cursor[bot] commented on code on Aug 27, 2026 12:29 UTC
    Code Review
    historyserver/pkg/historyserver/auth.go:1
    @@ -0,0 +1,312 @@
    +package historyserver
    +
    +import (
    +	"context"
    +	"crypto/sha256"
    +	"encoding/hex"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"html"
    +	"net/http"
    +	"net/url"
    +	"strings"
    +	"time"
    +
    +	"github.com/emicklei/go-restful/v3"
    +	lru "github.com/hashicorp/golang-lru/v2/expirable"
    +	"github.com/sirupsen/logrus"
    +	authv1 "k8s.io/api/authentication/v1"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/client-go/kubernetes"
    +	"k8s.io/client-go/rest"
    +)
    +
    +const (
    +	// AuthCookieName holds the user's own Kubernetes bearer token. It never
    +	// leaves the history server trust domain: the egress path strips it before
    +	// proxying to a live Ray cluster.
    +	AuthCookieName = "hs_auth_token"
    +
    +	// LoginPath and LogoutPath are raw handlers registered outside the
    +	// go-restful filter chain, so they stay reachable without a credential.
    +	LoginPath  = "/login"
    +	LogoutPath = "/logout"
    +
    +	// authCacheSize bounds the number of cached TokenReview results.
    +	authCacheSize = 1024
    +)
    +
    +const (
    +	// DefaultAuthCacheTTL caps how long a revoked token can still be accepted.
    +	DefaultAuthCacheTTL = 60 * time.Second
    +	// DefaultAuthCookieMaxAge matches the lifetime of the cluster context cookies.
    +	DefaultAuthCookieMaxAge = 600 * time.Second
    +)
    +
    +// Authenticator validates user-supplied Kubernetes bearer tokens via the
    +// TokenReview API and caches the outcome for a short window.
    +//
    +// Failure semantics are deliberately asymmetric:
    +//   - an invalid or expired token is a client error (401),
    +//   - a TokenReview infrastructure failure is a server error (503), never a
    +//     silent pass-through. Authentication fails closed.
    +type Authenticator struct {
    +	client kubernetes.Interface
    +	// cache maps sha256(token) -> authenticated username, so raw credentials
    +	// are not retained in memory.
    +	cache *lru.LRU[string, string]
    +}
    +
    +// NewAuthenticator builds an Authenticator from the primary cluster config.
    +func NewAuthenticator(cfg *rest.Config, cacheTTL time.Duration) (*Authenticator, error) {
    +	clientset, err := kubernetes.NewForConfig(cfg)
    +	if err != nil {
    +		return nil, fmt.Errorf("build kubernetes clientset for TokenReview: %w", err)
    +	}
    +	return &Authenticator{
    +		client: clientset,
    +		cache:  lru.NewLRU[string, string](authCacheSize, nil, cacheTTL),
    +	}, nil
    +}
    +
    +// hashToken keys the cache without retaining the raw credential.
    +func hashToken(token string) string {
    +	sum := sha256.Sum256([]byte(token))
    +	return hex.EncodeToString(sum[:])
    +}
    +
    +// authError distinguishes "bad credential" from "cannot tell right now".
    +type authError struct {
    +	msg    string
    +	status int
    +}
    +
    +func (e *authError) Error() string { return e.msg }
    +
    +// authStatus returns the HTTP status an error should map to, defaulting to 401.
    +func authStatus(err error) int {
    +	var aerr *authError
    +	if errors.As(err, &aerr) {
    +		return aerr.status
    +	}
    +	return http.StatusUnauthorized
    +}
    +
    +// Authenticate validates the token and returns the authenticated username.
    +func (a *Authenticator) Authenticate(ctx context.Context, token string) (string, error) {
    +	if token == "" {
    +		return "", &authError{status: http.StatusUnauthorized, msg: "missing authentication token"}
    +	}
    +
    +	key := hashToken(token)
    +	if user, ok := a.cache.Get(key); ok {
    +		return user, nil
    +	}
    +
    +	review := &authv1.TokenReview{Spec: authv1.TokenReviewSpec{Token: token}}
    +	result, err := a.client.AuthenticationV1().TokenReviews().Create(ctx, review, metav1.CreateOptions{})
    +	if err != nil {
    +		// The API server could not answer: refuse rather than guess.
    +		logrus.Errorf("TokenReview request failed: %v", err)
    +		return "", &authError{status: http.StatusServiceUnavailable, msg: "authentication backend unavailable"}
    +	}
    +	if !result.Status.Authenticated {
    +		reason := result.Status.Error
    +		if reason == "" {
    +			reason = "token is not authenticated"
    +		}
    +		return "", &authError{status: http.StatusUnauthorized, msg: reason}
    +	}
    +
    +	user := result.Status.User.Username
    +	a.cache.Add(key, user)
    +	return user, nil
    +}
    +
    +// extractToken pulls the credential from the request, header first.
    +//
    +// A malformed Authorization header is a hard failure instead of falling back to
    +// the cookie: a misconfigured client should fail loudly rather than silently
    +// authenticate as whoever the browser session belongs to.
    +func extractToken(req *http.Request) (string, error) {
    +	if raw := req.Header.Get("Authorization"); raw != "" {
    +		const prefix = "Bearer "
    +		if !strings.HasPrefix(raw, prefix) {
    +			return "", &authError{status: http.StatusUnauthorized, msg: "Authorization header must use the Bearer scheme"}
    +		}
    +		token := strings.TrimSpace(strings.TrimPrefix(raw, prefix))
    +		if token == "" {
    +			return "", &authError{status: http.StatusUnauthorized, msg: "Authorization header carries an empty bearer token"}
    +		}
    +		return token, nil
    +	}
    +	if cookie, err := req.Cookie(AuthCookieName); err == nil && cookie.Value != "" {
    +		return cookie.Value, nil
    +	}
    +	return "", &authError{status: http.StatusUnauthorized, msg: "missing authentication token"}
    +}
    +
    +// wantsHTML reports whether the request is a browser navigation, which should
    +// be redirected to the login page instead of receiving a bare 401.
    +func wantsHTML(req *http.Request) bool {
    +	if req.Header.Get("X-Requested-With") != "" {
    +		return false
    +	}
    +	if mode := req.Header.Get("Sec-Fetch-Mode"); mode != "" {
    +		return mode == "navigate"
    +	}
    +	return strings.Contains(req.Header.Get("Accept"), "text/html")
    +}
    +
    +// AuthFilter authenticates every request flowing through the go-restful
    +// container. It runs before any handler, so dead-cluster serving and live
    +// pass-through are both gated by it.
    +func (s *ServerHandler) AuthFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
    +	if s.authenticator == nil {
    +		chain.ProcessFilter(req, resp)
    +		return
    +	}
    +
    +	token, err := extractToken(req.Request)
    +	if err == nil {
    +		var user string
    +		if user, err = s.authenticator.Authenticate(req.Request.Context(), token); err == nil {
    +			req.SetAttribute(ATTRIBUTE_AUTH_USER, user)
    +			chain.ProcessFilter(req, resp)
    +			return
    +		}
    +	}
    +
    +	status := authStatus(err)
    +	// Browser navigations get a login round-trip so a single link keeps working;
    +	// XHR callers get a machine-readable error instead of an HTML page.
    +	if status == http.StatusUnauthorized && wantsHTML(req.Request) {
    +		next := req.Request.URL.RequestURI()
    +		http.Redirect(resp.ResponseWriter, req.Request, LoginPath+"?next="+url.QueryEscape(next), http.StatusFound)
    +		return
    +	}
    +	writeAuthError(resp.ResponseWriter, status, err.Error())
    +}
    +
    +// writeAuthError follows the repository-wide error contract {"code","message"}.
    +func writeAuthError(w http.ResponseWriter, status int, msg string) {
    +	w.Header().Set("Content-Type", restful.MIME_JSON)
    +	w.WriteHeader(status)
    +	_ = json.NewEncoder(w).Encode(map[string]any{"code": status, "message": msg})
    +}
    +
    +// authCookie builds the session cookie. It is HttpOnly so page scripts cannot
    +// read the Kubernetes token, and SameSite=Lax so it survives a top-level
    +// navigation arriving from an external link.
    +func (s *ServerHandler) authCookie(value string, maxAge int) *http.Cookie {
    +	return &http.Cookie{
    +		Name:     AuthCookieName,
    +		Value:    value,
    +		Path:     "/",
    +		MaxAge:   maxAge,
    +		HttpOnly: true,
    +		Secure:   s.authCookieSecure,
    +		SameSite: http.SameSiteLaxMode,
    +	}
    +}
    +
    +// safeNext keeps the post-login redirect inside this origin, so a crafted link
    +// cannot bounce a freshly authenticated browser to another host.
    +func safeNext(raw string) string {
    +	if raw == "" {
    +		return "/"
    +	}
    +	u, err := url.Parse(raw)
    +	if err != nil || u.IsAbs() || u.Host != "" || !strings.HasPrefix(u.Path, "/") {
    +		return "/"
    +	}
    +	return u.String()
    +}

    Post-login redirect allows off-origin bounce

    Medium Severity

    <!-- DESCRIPTION START -->
    safeNext treats a leading backslash as a same-origin path because url.Parse leaves Host empty, then that value is used as the post-login Location. Browsers treat /\evil.example as a network-path URL, so a crafted next can send a just-authenticated user off this origin after the session cookie is set.
    <!-- DESCRIPTION END -->

    <!-- BUGBOT_BUG_ID: fa4c9ace-28cc-4679-bb1e-297b465a6a70 -->

    <!-- LOCATIONS START
    historyserver/pkg/historyserver/auth.go#L215-L225
    LOCATIONS END -->
    <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmZiM2E5OTZkLWE4YzYtNDg1OC05NmRjLWJlMjJmNWYyYTk1OSIsImVuY3J5cHRpb25LZXkiOiI2MU15ZDZNQUFSbTl3cXVPbFh4YnhqazNOYmpyUTBodTRZcFR2dzgxSTBBIiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmZiM2E5OTZkLWE4YzYtNDg1OC05NmRjLWJlMjJmNWYyYTk1OSIsImVuY3J5cHRpb25LZXkiOiI2MU15ZDZNQUFSbTl3cXVPbFh4YnhqazNOYmpyUTBodTRZcFR2dzgxSTBBIiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwck51bWJlciI6NTIwNCwiY29tbWl0U2hhIjoiYWM1ZDRmN2MyNDM1NzYwNDBlYzVmYmVlOWQwMzBkZjdjNTJjZWU2OCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

    <sup>Reviewed by Cursor Bugbot for commit ac5d4f7c243576040ec5fbee9d030df7c52cee68. Configure here.</sup>

    cursor[bot] cursor[bot] commented on code on Aug 27, 2026 12:29 UTC
    Code Review
    historyserver/pkg/historyserver/auth.go:1
    @@ -0,0 +1,312 @@
    +package historyserver
    +
    +import (
    +	"context"
    +	"crypto/sha256"
    +	"encoding/hex"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"html"
    +	"net/http"
    +	"net/url"
    +	"strings"
    +	"time"
    +
    +	"github.com/emicklei/go-restful/v3"
    +	lru "github.com/hashicorp/golang-lru/v2/expirable"
    +	"github.com/sirupsen/logrus"
    +	authv1 "k8s.io/api/authentication/v1"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/client-go/kubernetes"
    +	"k8s.io/client-go/rest"
    +)
    +
    +const (
    +	// AuthCookieName holds the user's own Kubernetes bearer token. It never
    +	// leaves the history server trust domain: the egress path strips it before
    +	// proxying to a live Ray cluster.
    +	AuthCookieName = "hs_auth_token"
    +
    +	// LoginPath and LogoutPath are raw handlers registered outside the
    +	// go-restful filter chain, so they stay reachable without a credential.
    +	LoginPath  = "/login"
    +	LogoutPath = "/logout"
    +
    +	// authCacheSize bounds the number of cached TokenReview results.
    +	authCacheSize = 1024
    +)
    +
    +const (
    +	// DefaultAuthCacheTTL caps how long a revoked token can still be accepted.
    +	DefaultAuthCacheTTL = 60 * time.Second
    +	// DefaultAuthCookieMaxAge matches the lifetime of the cluster context cookies.
    +	DefaultAuthCookieMaxAge = 600 * time.Second
    +)
    +
    +// Authenticator validates user-supplied Kubernetes bearer tokens via the
    +// TokenReview API and caches the outcome for a short window.
    +//
    +// Failure semantics are deliberately asymmetric:
    +//   - an invalid or expired token is a client error (401),
    +//   - a TokenReview infrastructure failure is a server error (503), never a
    +//     silent pass-through. Authentication fails closed.
    +type Authenticator struct {
    +	client kubernetes.Interface
    +	// cache maps sha256(token) -> authenticated username, so raw credentials
    +	// are not retained in memory.
    +	cache *lru.LRU[string, string]
    +}
    +
    +// NewAuthenticator builds an Authenticator from the primary cluster config.
    +func NewAuthenticator(cfg *rest.Config, cacheTTL time.Duration) (*Authenticator, error) {
    +	clientset, err := kubernetes.NewForConfig(cfg)
    +	if err != nil {
    +		return nil, fmt.Errorf("build kubernetes clientset for TokenReview: %w", err)
    +	}
    +	return &Authenticator{
    +		client: clientset,
    +		cache:  lru.NewLRU[string, string](authCacheSize, nil, cacheTTL),
    +	}, nil
    +}
    +
    +// hashToken keys the cache without retaining the raw credential.
    +func hashToken(token string) string {
    +	sum := sha256.Sum256([]byte(token))
    +	return hex.EncodeToString(sum[:])
    +}
    +
    +// authError distinguishes "bad credential" from "cannot tell right now".
    +type authError struct {
    +	msg    string
    +	status int
    +}
    +
    +func (e *authError) Error() string { return e.msg }
    +
    +// authStatus returns the HTTP status an error should map to, defaulting to 401.
    +func authStatus(err error) int {
    +	var aerr *authError
    +	if errors.As(err, &aerr) {
    +		return aerr.status
    +	}
    +	return http.StatusUnauthorized
    +}
    +
    +// Authenticate validates the token and returns the authenticated username.
    +func (a *Authenticator) Authenticate(ctx context.Context, token string) (string, error) {
    +	if token == "" {
    +		return "", &authError{status: http.StatusUnauthorized, msg: "missing authentication token"}
    +	}
    +
    +	key := hashToken(token)
    +	if user, ok := a.cache.Get(key); ok {
    +		return user, nil
    +	}
    +
    +	review := &authv1.TokenReview{Spec: authv1.TokenReviewSpec{Token: token}}
    +	result, err := a.client.AuthenticationV1().TokenReviews().Create(ctx, review, metav1.CreateOptions{})
    +	if err != nil {
    +		// The API server could not answer: refuse rather than guess.
    +		logrus.Errorf("TokenReview request failed: %v", err)
    +		return "", &authError{status: http.StatusServiceUnavailable, msg: "authentication backend unavailable"}
    +	}
    +	if !result.Status.Authenticated {
    +		reason := result.Status.Error
    +		if reason == "" {
    +			reason = "token is not authenticated"
    +		}
    +		return "", &authError{status: http.StatusUnauthorized, msg: reason}
    +	}
    +
    +	user := result.Status.User.Username
    +	a.cache.Add(key, user)
    +	return user, nil
    +}
    +
    +// extractToken pulls the credential from the request, header first.
    +//
    +// A malformed Authorization header is a hard failure instead of falling back to
    +// the cookie: a misconfigured client should fail loudly rather than silently
    +// authenticate as whoever the browser session belongs to.
    +func extractToken(req *http.Request) (string, error) {
    +	if raw := req.Header.Get("Authorization"); raw != "" {
    +		const prefix = "Bearer "
    +		if !strings.HasPrefix(raw, prefix) {
    +			return "", &authError{status: http.StatusUnauthorized, msg: "Authorization header must use the Bearer scheme"}
    +		}
    +		token := strings.TrimSpace(strings.TrimPrefix(raw, prefix))
    +		if token == "" {
    +			return "", &authError{status: http.StatusUnauthorized, msg: "Authorization header carries an empty bearer token"}
    +		}
    +		return token, nil
    +	}
    +	if cookie, err := req.Cookie(AuthCookieName); err == nil && cookie.Value != "" {
    +		return cookie.Value, nil
    +	}
    +	return "", &authError{status: http.StatusUnauthorized, msg: "missing authentication token"}
    +}
    +
    +// wantsHTML reports whether the request is a browser navigation, which should
    +// be redirected to the login page instead of receiving a bare 401.
    +func wantsHTML(req *http.Request) bool {
    +	if req.Header.Get("X-Requested-With") != "" {
    +		return false
    +	}
    +	if mode := req.Header.Get("Sec-Fetch-Mode"); mode != "" {
    +		return mode == "navigate"
    +	}
    +	return strings.Contains(req.Header.Get("Accept"), "text/html")
    +}
    +
    +// AuthFilter authenticates every request flowing through the go-restful
    +// container. It runs before any handler, so dead-cluster serving and live
    +// pass-through are both gated by it.
    +func (s *ServerHandler) AuthFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
    +	if s.authenticator == nil {
    +		chain.ProcessFilter(req, resp)
    +		return
    +	}
    +
    +	token, err := extractToken(req.Request)
    +	if err == nil {
    +		var user string
    +		if user, err = s.authenticator.Authenticate(req.Request.Context(), token); err == nil {
    +			req.SetAttribute(ATTRIBUTE_AUTH_USER, user)
    +			chain.ProcessFilter(req, resp)
    +			return
    +		}
    +	}
    +
    +	status := authStatus(err)
    +	// Browser navigations get a login round-trip so a single link keeps working;
    +	// XHR callers get a machine-readable error instead of an HTML page.
    +	if status == http.StatusUnauthorized && wantsHTML(req.Request) {
    +		next := req.Request.URL.RequestURI()
    +		http.Redirect(resp.ResponseWriter, req.Request, LoginPath+"?next="+url.QueryEscape(next), http.StatusFound)
    +		return
    +	}
    +	writeAuthError(resp.ResponseWriter, status, err.Error())
    +}
    +
    +// writeAuthError follows the repository-wide error contract {"code","message"}.
    +func writeAuthError(w http.ResponseWriter, status int, msg string) {
    +	w.Header().Set("Content-Type", restful.MIME_JSON)
    +	w.WriteHeader(status)
    +	_ = json.NewEncoder(w).Encode(map[string]any{"code": status, "message": msg})
    +}
    +
    +// authCookie builds the session cookie. It is HttpOnly so page scripts cannot
    +// read the Kubernetes token, and SameSite=Lax so it survives a top-level
    +// navigation arriving from an external link.
    +func (s *ServerHandler) authCookie(value string, maxAge int) *http.Cookie {
    +	return &http.Cookie{
    +		Name:     AuthCookieName,
    +		Value:    value,
    +		Path:     "/",
    +		MaxAge:   maxAge,
    +		HttpOnly: true,
    +		Secure:   s.authCookieSecure,
    +		SameSite: http.SameSiteLaxMode,
    +	}
    +}
    +
    +// safeNext keeps the post-login redirect inside this origin, so a crafted link
    +// cannot bounce a freshly authenticated browser to another host.
    +func safeNext(raw string) string {
    +	if raw == "" {
    +		return "/"
    +	}
    +	u, err := url.Parse(raw)
    +	if err != nil || u.IsAbs() || u.Host != "" || !strings.HasPrefix(u.Path, "/") {
    +		return "/"
    +	}
    +	return u.String()
    +}

    Login success lands on missing page

    Medium Severity

    <!-- DESCRIPTION START -->
    safeNext defaults an empty or rejected next to /, and logout sends the browser to /login with no next. There is no handler for / (routerRoot is commented out), so the documented paste-a-token flow and every re-login after logout finish on a 404 instead of the cluster selector.
    <!-- DESCRIPTION END -->

    <!-- BUGBOT_BUG_ID: d68364cd-21b6-439b-9fe9-447db9776f5b -->

    <!-- LOCATIONS START
    historyserver/pkg/historyserver/auth.go#L215-L225
    historyserver/pkg/historyserver/auth.go#L265-L269
    LOCATIONS END -->
    <details>
    <summary>Additional Locations (1)</summary>

  • historyserver/pkg/historyserver/auth.go#L265-L269
  • </details>

    <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmNlZTU4MjZmLTdlMTgtNGY0ZS1hODk0LTYwMWM2ZjE5MDcwMCIsImVuY3J5cHRpb25LZXkiOiIwUWNBbUMwSUFrSnJmT2E5X2ZBLTR4cTR6dlNTMXJIY2FKdGtQeWZiUko4IiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmNlZTU4MjZmLTdlMTgtNGY0ZS1hODk0LTYwMWM2ZjE5MDcwMCIsImVuY3J5cHRpb25LZXkiOiIwUWNBbUMwSUFrSnJmT2E5X2ZBLTR4cTR6dlNTMXJIY2FKdGtQeWZiUko4IiwiYnJhbmNoIjoiZmVhdC9ocy10b2tlbnJldmlldy1hdXRoIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwck51bWJlciI6NTIwNCwiY29tbWl0U2hhIjoiYWM1ZDRmN2MyNDM1NzYwNDBlYzVmYmVlOWQwMzBkZjdjNTJjZWU2OCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

    <sup>Reviewed by Cursor Bugbot for commit ac5d4f7c243576040ec5fbee9d030df7c52cee68. Configure here.</sup>

    cursor[bot] cursor[bot] commented on Aug 27, 2026 12:29 UTC
    Reviewer

    <!-- BUGBOT_REVIEW -->
    Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

    There are 4 total unresolved issues (including 2 from previous reviews).

    <!-- BUGBOT_FIX_ALL -->
    <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo0MzA2ZjA1ZC1iZmZhLTRmZTQtYjY3Yy00MDNiZTlhYjdkOTIiLCJlbmNyeXB0aW9uS2V5IjoiNzJoLUxRaEgyaVRHZ08tWVR3Y2VVQnpuVk96bmlRanpPdnpfYS1yQWVPYyIsImJyYW5jaCI6ImZlYXQvaHMtdG9rZW5yZXZpZXctYXV0aCIsInJlcG9Pd25lciI6InJheS1wcm9qZWN0IiwicmVwb05hbWUiOiJrdWJlcmF5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
    <!-- /BUGBOT_FIX_ALL -->

    <sup>Reviewed by Cursor Bugbot for commit ac5d4f7c243576040ec5fbee9d030df7c52cee68. Configure here.</sup>

    chiayi chiayi commented on code on Sep 29, 2026 23:50 UTC
    Code Review
    historyserver/cmd/historyserver/main.go:1
    @@ -46,6 +50,10 @@ func main() {
     	flag.IntVar(&sessionCacheSize, "session-cache-size", historyserver.DefaultSessionCacheSize, "Max number of dead-session snapshots held in the LRU cache.")
     	flag.StringVar(&sessionCacheMaxMemory, "session-cache-max-memory", historyserver.DefaultSessionCacheMaxMemory, `Soft cap on memory held by cached snapshots, as a Kubernetes quantity (e.g. "1Gi"); tune under pod memory. "0" disables the bound.`)
     	flag.DurationVar(&sessionCacheTTL, "session-cache-ttl", historyserver.DefaultSessionCacheTTL, "How long a dead-session snapshot stays cached after last access. 0 disables TTL.")
    +	flag.BoolVar(&enableAuth, "enable-auth", false, "Authenticate users against the Kubernetes TokenReview API before serving any cluster data.")
    +	flag.DurationVar(&authCacheTTL, "auth-cache-ttl", historyserver.DefaultAuthCacheTTL, "How long a successful TokenReview result stays cached. A revoked token keeps working for at most this long.")

    Should we also validate authCacheTTL > 0 and authCookieMaxAge > 0 as well when enableAuth is true? It seems like expirable.NewLRU treats ttl <= 0 as no expiration, which would cache tokens indefinitely.

    chiayi chiayi commented on Sep 30, 2026 00:03 UTC
    Reviewer

    To answer your questions:
    For the scoping: keeping this separate from the SubjectAccessReview makes sense to me. Could you open a follow-up issue to track the work including this one?

    I'm also on the side of a built in login page. But I curious about how it would work with the Cookies we currently have (since I believe, it isn't completely migrated yet). And also if there's a login, is there also a logout as well?

    For the filter gate, I think that makes sense to me, but want to hear thoughts of others.

    Please also take a look at the Cursor bot comments, I think the safeNext defaulting is valid.

    KunWuLuan KunWuLuan commented on Sep 30, 2026 08:16 UTC
    Author

    @chiayi The follow up issue has been created. #5355

    KunWuLuan KunWuLuan commented on Sep 30, 2026 08:40 UTC
    Author

    The two cookie families are independent: hs_auth_token is checked by the container-level AuthFilter, the five context cookies (cluster_name / cluster_namespace / session_name / owner_kind / owner_name) by the per-route CookieHandle. This PR does not read or write the context cookies. /login and /logout are raw handlers outside the filter chain so they stay reachable unauthenticated, and /select_cluster repeats the check inline. There is a logout — it clears hs_auth_token and redirects to /login.

    Is #5065 the migration you meant? If it is a different one, tell me which and I will re-check.

    Reviewers
    Assignees
    KunWuLuan KunWuLuan
    Labels
    risk: low confidence: 92.1% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 82.0% (HIGH) · Higher = larger blast radius
    82.0%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 92.1% · Lower = rushed or shallow review
    92.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.5% · Safe to merge
    6.5%