fix: isolate kandev cookies between instances on one host (#2813)

Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Clément Fiere
2026-08-19 23:47:54 +02:00
committed by GitHub
parent 6c97e0a237
commit 0630a02841
75 changed files with 4026 additions and 1272 deletions
+1 -1
View File
@@ -170,7 +170,7 @@ Standalone agentctl is launched in its own process group so terminal Ctrl+C is h
**Remote SSH lifecycle:** Resolve and run remote preparation, then verify the canonical checkout, origin, and `HEAD` before starting agentctl. Retain the remote task directory in session state for stop/resume; terminal archive/delete/cascade cleanup runs over the live SSH connection before teardown, while ordinary stop and backend shutdown preserve the workspace.
**Opt-in authentication & per-user scoping** (`internal/auth/`): auth is OFF by default; the global middleware (`auth/httpmw`, installed after CORS in `backendapp.buildHTTPServer`) then injects a synthetic admin identity for the pre-auth single user, so behavior is unchanged. Enablement is the `features.auth` runtime flag (`KANDEV_FEATURES_AUTH`, Settings > System > Feature Toggles) — the auth service derives its mode from `cfg.Features.Auth` (`disabled` / `setup` = flag-on-no-admin / `enabled` = flag-on-admin-exists); there is no separate `auth.mode` setting. When enabled, requests authenticate via a `kandev_session` cookie (opaque token, SHA-256 at rest, DB-backed) or a `kandev_pat_*` bearer token. Scoping rules:
**Opt-in authentication & per-user scoping** (`internal/auth/`): auth is OFF by default; the global middleware (`auth/httpmw`, installed after CORS in `backendapp.buildHTTPServer`) then injects a synthetic admin identity for the pre-auth single user, so behavior is unchanged. Enablement is the `features.auth` runtime flag (`KANDEV_FEATURES_AUTH`, Settings > System > Feature Toggles) — the auth service derives its mode from `cfg.Features.Auth` (`disabled` / `setup` = flag-on-no-admin / `enabled` = flag-on-admin-exists); there is no separate `auth.mode` setting. When enabled, requests authenticate via the session cookie (base name `kandev_session`; the effective name is derived from the request host — port-scoped on a ported host via `internal/common/httpcookie`, plain on a default-port host) or a `kandev_pat_*` bearer token. Scoping rules:
- **Identity travels in the request context** (`authn.IdentityFromContext`). No identity = internal caller (pollers, event bus, office schedulers) = unscoped. Synthetic identity = auth disabled = unscoped.
- **In-session agent MCP is scoped to the task owner.** The MCP tools an agent gets inside its own session are relayed over the agent's WebSocket stream, which carries no credential of its own. `internal/mcp/scope` resolves the stream's task → workspace → owner and attaches that user's real identity before dispatch (`lifecycle.Manager.SetMCPIdentityScoper`), so the same `authorize*` checks apply as for the PAT-authenticated `/mcp` endpoint. The owning task comes from the `AgentExecution`, never from the agent-supplied payload — do not "improve" this by reading `session_id`/`task_id` out of the request. Tool handlers stay identity-agnostic. Under enforced auth every dispatch is scoped to *somebody*: a resolvable active owner gets their identity; an unowned workspace gets a sentinel user ID that reaches unowned rows only; anything unresolvable (missing task/workspace row, or an owner whose account was deleted or disabled) is **denied**. Never return an identity-free context from this path — the task service reads that as an internal caller and grants everything.
- **Workspaces are per-user** (`workspaces.owner_id`); the task service filters/denies at the service layer with `*NotFound` sentinels (no existence leak). Unowned rows (`owner_id=''`) stay visible until the setup wizard claims them for the admin.
+13 -3
View File
@@ -93,7 +93,7 @@ func (h *Handlers) setup(c *gin.Context) {
h.writeAuthError(c, err)
return
}
setSessionCookie(c, h.svc.CookieName(), token, h.svc.SessionTTL())
setSessionCookie(c, h.svc.CookieNameForRequest(c.Request), token, h.svc.SessionTTL())
c.JSON(http.StatusOK, gin.H{"user": user})
}
@@ -108,10 +108,14 @@ func (h *Handlers) login(c *gin.Context) {
h.writeAuthError(c, err)
return
}
setSessionCookie(c, h.svc.CookieName(), token, h.svc.SessionTTL())
setSessionCookie(c, h.svc.CookieNameForRequest(c.Request), token, h.svc.SessionTTL())
c.JSON(http.StatusOK, gin.H{"user": user})
}
// logout terminates the current session (if any) and clears its port-scoped
// session cookie. The unprefixed base name is deliberately left untouched —
// on a host serving a default-port instance it is that instance's live
// session cookie (see spec: no proactive legacy scrubbing).
func (h *Handlers) logout(c *gin.Context) {
identity, ok := authn.FromGin(c)
if ok && identity.SessionID != "" {
@@ -120,7 +124,13 @@ func (h *Handlers) logout(c *gin.Context) {
return
}
}
clearSessionCookie(c, h.svc.CookieName())
// Clear only the effective (port-scoped) name. The unprefixed base name is
// deliberately left alone: on a host serving a default-port instance (or a
// not-yet-upgraded one), it is that instance's LIVE session cookie, not an
// inert legacy jar — expiring it would log the other instance out (see
// docs/specs/fix-multi-instance-cookie-isolation/spec.md: the upgraded
// instance does not proactively delete the legacy cookie).
clearSessionCookie(c, h.svc.CookieNameForRequest(c.Request))
c.Status(http.StatusNoContent)
}
@@ -128,7 +128,7 @@ func (h *Handlers) acceptInvite(c *gin.Context) {
h.writeAuthError(c, err)
return
}
setSessionCookie(c, h.svc.CookieName(), token, h.svc.SessionTTL())
setSessionCookie(c, h.svc.CookieNameForRequest(c.Request), token, h.svc.SessionTTL())
c.JSON(http.StatusOK, gin.H{"user": user})
}
@@ -12,23 +12,31 @@ import (
"github.com/gin-gonic/gin"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/auth"
authhttpmw "github.com/kandev/kandev/internal/auth/httpmw"
authstore "github.com/kandev/kandev/internal/auth/store"
"github.com/kandev/kandev/internal/common/config"
commonhttpmw "github.com/kandev/kandev/internal/common/httpmw"
"github.com/kandev/kandev/internal/common/logger"
userstore "github.com/kandev/kandev/internal/user/store"
)
// newAPIFixture builds the full production HTTP stack for auth: global
// middleware + auth API routes on one router. authEnabled maps to the
// features.auth flag (on ⇒ setup mode until the wizard runs). The router
// mirrors production by default: gin.New() trusts all proxies, so
// SetTrustedProxies is called with the variadic trusted list (nil clears the
// insecure default) exactly like buildHTTPServer does.
func newAPIFixture(t *testing.T, authEnabled bool, trustedProxies ...string) (*gin.Engine, *auth.Service) {
// testLogger returns a discard logger for fixtures that must pass one.
func testLogger(t *testing.T) *logger.Logger {
t.Helper()
log, err := logger.NewFromZap(zap.NewNop())
if err != nil {
t.Fatalf("nop logger: %v", err)
}
return log
}
// newAuthService builds an auth service from cfg over an in-memory store
// pair. Shared by the plain and CORS-gated fixtures.
func newAuthService(t *testing.T, cfg *config.Config) *auth.Service {
t.Helper()
gin.SetMode(gin.TestMode)
conn, err := sqlx.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("open sqlite: %v", err)
@@ -43,15 +51,35 @@ func newAPIFixture(t *testing.T, authEnabled bool, trustedProxies ...string) (*g
if err != nil {
t.Fatalf("auth store: %v", err)
}
cfg := &config.Config{}
cfg.Features.Auth = authEnabled
cfg.Auth.SessionTTLHours = 720
svc, err := auth.NewService(context.Background(), auth.Deps{
Cfg: cfg, Store: store, Users: users,
})
if err != nil {
t.Fatalf("auth service: %v", err)
}
return svc
}
// newAPIFixture builds the full production HTTP stack for auth: global
// middleware + auth API routes on one router. authEnabled maps to the
// features.auth flag (on ⇒ setup mode until the wizard runs). The router
// mirrors production by default: gin.New() trusts all proxies, so
// SetTrustedProxies is called with the variadic trusted list (nil clears the
// insecure default) exactly like buildHTTPServer does.
func newAPIFixture(t *testing.T, authEnabled bool, trustedProxies ...string) (*gin.Engine, *auth.Service) {
t.Helper()
cfg := &config.Config{}
cfg.Features.Auth = authEnabled
cfg.Auth.SessionTTLHours = 720
return newAPIFixtureWithCfg(t, cfg, trustedProxies...)
}
// newAPIFixtureWithCfg is newAPIFixture with an explicit config (custom
// auth.cookieName, loaded defaults, …).
func newAPIFixtureWithCfg(t *testing.T, cfg *config.Config, trustedProxies ...string) (*gin.Engine, *auth.Service) {
t.Helper()
gin.SetMode(gin.TestMode)
svc := newAuthService(t, cfg)
router := gin.New()
if len(trustedProxies) == 0 {
trustedProxies = nil
@@ -64,10 +92,40 @@ func newAPIFixture(t *testing.T, authEnabled bool, trustedProxies ...string) (*g
return router, svc
}
// newCORSGatedAPIFixture mirrors the production stack: the CORS/WS origin
// gate (httpmw.AllowedOrigin, the same decision branch as
// newCORSGatedAPIFixture mirrors the production chain for the reverse-proxy
// contract tests: the CORS origin gate (as in backendapp.corsMiddleware) runs
// before the auth middleware, as in buildHTTPServer, and — like
// buildHTTPServer — X-Forwarded-Host is honored only when the request's peer
// is in the given trusted-proxy list (mirroring KANDEV_TRUSTED_PROXIES).
func newCORSGatedAPIFixture(t *testing.T, cfg *config.Config, trustedProxies ...string) (*gin.Engine, *auth.Service) {
t.Helper()
gin.SetMode(gin.TestMode)
svc := newAuthService(t, cfg)
router := gin.New()
router.Use(authhttpmw.StripUntrustedForwardedHost(trustedProxies, testLogger(t)))
router.Use(func(c *gin.Context) {
if origin := c.GetHeader("Origin"); origin != "" {
if !commonhttpmw.AllowedOrigin(origin, c.Request.Host) {
c.AbortWithStatus(http.StatusForbidden)
return
}
}
c.Next()
})
router.Use(authhttpmw.Middleware(svc))
RegisterRoutes(router, svc, nil)
return router, svc
}
type apiClient struct {
t *testing.T
router *gin.Engine
cookie *http.Cookie
// cookiePrefix filters the session Set-Cookie names this client captures
// (default "kandev_session"); custom-name tests override it.
cookiePrefix string
}
func (c *apiClient) do(method, path string, body any, mutate ...func(*http.Request)) *httptest.ResponseRecorder {
@@ -93,8 +151,12 @@ func (c *apiClient) do(method, path string, body any, mutate ...func(*http.Reque
rec := httptest.NewRecorder()
c.router.ServeHTTP(rec, req)
// Capture session cookie updates (login/setup/logout).
prefix := c.cookiePrefix
if prefix == "" {
prefix = "kandev_session"
}
for _, cookie := range rec.Result().Cookies() {
if strings.Contains(cookie.Name, "kandev_session") {
if strings.Contains(cookie.Name, prefix) {
if cookie.MaxAge < 0 {
c.cookie = nil
} else {
@@ -105,6 +167,47 @@ func (c *apiClient) do(method, path string, body any, mutate ...func(*http.Reque
return rec
}
// assertSessionCookieNames asserts the response's session cookies (names
// containing filter) are exactly want, in order — a positive-only assertion
// would miss an implementation emitting both the scoped and unprefixed names.
func assertSessionCookieNames(t *testing.T, rec *httptest.ResponseRecorder, filter string, want ...string) {
t.Helper()
var got []string
for _, cookie := range rec.Result().Cookies() {
if strings.Contains(cookie.Name, filter) {
got = append(got, cookie.Name)
}
}
if !equalStrings(got, want) {
t.Fatalf("session Set-Cookie names = %v, want %v", got, want)
}
}
// equalStrings reports whether two string slices are identical, in order.
func equalStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// setupOn logs the admin in via the setup wizard on the given request Host.
func setupOn(t *testing.T, client *apiClient, host string) *httptest.ResponseRecorder {
t.Helper()
rec := client.do(http.MethodPost, "/api/v1/auth/setup", map[string]any{
"email": "admin@x.dev", "password": "adminpass123", "display_name": "Admin",
}, func(req *http.Request) { req.Host = host })
if rec.Code != http.StatusOK {
t.Fatalf("setup: %d body=%s", rec.Code, rec.Body.String())
}
return rec
}
// loginSessionIP bootstraps the admin via setup, performs a login request
// with the given transport attributes, and returns the stored IP of the
// current session (the login cookie is current; the setup session stays in
@@ -363,3 +466,396 @@ func TestValidationErrors(t *testing.T) {
t.Fatalf("short password: %d", rec.Code)
}
}
// TestSessionCookieScopedToPortedHost pins the core isolation contract: login
// on a ported Host sets kandev_session_<port>, a request carrying only the
// legacy unprefixed cookie is rejected (mixed-version tier 1), and the scoped
// cookie authenticates subsequent requests.
func TestSessionCookieScopedToPortedHost(t *testing.T) {
router, _ := newAPIFixture(t, true)
client := &apiClient{t: t, router: router}
host := "127.0.0.1:8443"
rec := setupOn(t, client, host)
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session_8443")
if client.cookie == nil || client.cookie.Name != "kandev_session_8443" {
t.Fatalf("captured cookie = %+v, want kandev_session_8443", client.cookie)
}
// A request carrying only the legacy unprefixed cookie is rejected on the
// ported host (old→new rejection; pre-change it authenticated).
legacy := &apiClient{t: t, router: router}
rec = legacy.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = host
req.Header.Set("Cookie", "kandev_session="+client.cookie.Value)
})
if rec.Code != http.StatusUnauthorized {
t.Fatalf("legacy cookie on ported host: %d, want 401", rec.Code)
}
// The scoped cookie authenticates on the ported host (and only there).
rec = client.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = host
})
if rec.Code != http.StatusOK {
t.Fatalf("scoped cookie on ported host: %d, want 200", rec.Code)
}
if rec := client.do(http.MethodGet, "/api/v1/users", nil); rec.Code != http.StatusUnauthorized {
t.Fatalf("scoped cookie on default-port host: %d, want 401", rec.Code)
}
}
// TestSessionCookieLogoutClearsScopedName pins the logout/clear path: the
// same scoped name login wrote is cleared, and the unprefixed base name is
// left untouched — on a host serving a default-port instance it is that
// instance's live session cookie (see spec: no proactive legacy scrubbing).
func TestSessionCookieLogoutClearsScopedName(t *testing.T) {
router, _ := newAPIFixture(t, true)
client := &apiClient{t: t, router: router}
host := "127.0.0.1:8443"
setupOn(t, client, host)
rec := client.do(http.MethodPost, "/api/v1/auth/logout", nil, func(req *http.Request) {
req.Host = host
})
if rec.Code != http.StatusNoContent {
t.Fatalf("logout: %d", rec.Code)
}
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session_8443")
for _, cookie := range rec.Result().Cookies() {
if cookie.Name == "kandev_session_8443" && cookie.MaxAge >= 0 {
t.Fatalf("logout did not expire the scoped cookie: %+v", cookie)
}
}
if client.cookie != nil {
t.Fatal("logout must clear the client cookie")
}
if rec := client.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = host
}); rec.Code != http.StatusUnauthorized {
t.Fatalf("post-logout ported request: %d, want 401", rec.Code)
}
}
// TestInviteAcceptSetsScopedCookie covers the invite-accept set path (there
// is no separate admin-login handler — the first admin's login flows through
// setup).
func TestInviteAcceptSetsScopedCookie(t *testing.T) {
router, _ := newAPIFixture(t, true)
admin := &apiClient{t: t, router: router}
host := "127.0.0.1:8443"
setupOn(t, admin, host)
rec := admin.do(http.MethodPost, "/api/v1/auth/invites", map[string]any{"email": "m@x.dev", "role": "member"},
func(req *http.Request) { req.Host = host })
if rec.Code != http.StatusCreated {
t.Fatalf("create invite: %d body=%s", rec.Code, rec.Body.String())
}
token := strings.TrimPrefix(decode(t, rec)["url"].(string), "/invite?token=")
member := &apiClient{t: t, router: router}
rec = member.do(http.MethodPost, "/api/v1/auth/invites/accept", map[string]any{
"token": token, "email": "m@x.dev", "password": "memberpass123", "display_name": "M",
}, func(req *http.Request) { req.Host = host })
if rec.Code != http.StatusOK {
t.Fatalf("accept invite: %d body=%s", rec.Code, rec.Body.String())
}
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session_8443")
if member.cookie == nil || member.cookie.Name != "kandev_session_8443" {
t.Fatalf("member cookie = %+v, want kandev_session_8443", member.cookie)
}
}
// TestSessionCookieSuffixWithLoadedDefaultConfig pins the config-default
// regression: with the loaded default config (empty auth.cookieName) login on
// a ported Host still sets kandev_session_<port> — a seeded non-empty default
// must not suppress suffixing in production.
func TestSessionCookieSuffixWithLoadedDefaultConfig(t *testing.T) {
t.Setenv("KANDEV_AUTH_COOKIE_NAME", "")
cfg, err := config.LoadWithPath(t.TempDir())
if err != nil {
t.Fatalf("load config: %v", err)
}
if cfg.Auth.CookieName != "" {
t.Fatalf("loaded default auth.cookieName = %q, want empty", cfg.Auth.CookieName)
}
cfg.Features.Auth = true
router, _ := newAPIFixtureWithCfg(t, cfg)
client := &apiClient{t: t, router: router}
rec := setupOn(t, client, "127.0.0.1:8443")
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session_8443")
}
// TestCustomCookieNameUsedVerbatim pins the custom-name contract: an
// explicitly configured auth.cookieName is never suffixed, and authenticates
// through the same middleware path.
func TestCustomCookieNameUsedVerbatim(t *testing.T) {
cfg := &config.Config{}
cfg.Features.Auth = true
cfg.Auth.SessionTTLHours = 720
cfg.Auth.CookieName = "my_session"
router, _ := newAPIFixtureWithCfg(t, cfg)
client := &apiClient{t: t, router: router, cookiePrefix: "my_session"}
rec := setupOn(t, client, "127.0.0.1:8443")
assertSessionCookieNames(t, rec, "my_session", "my_session")
if client.cookie == nil || client.cookie.Name != "my_session" {
t.Fatalf("captured cookie = %+v, want my_session (verbatim)", client.cookie)
}
rec = client.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = "127.0.0.1:8443"
})
if rec.Code != http.StatusOK {
t.Fatalf("custom-name cookie on ported host: %d, want 200", rec.Code)
}
}
// TestSessionCookiePlainOnDefaultPort covers the no-port branch through the
// real handlers: login on a default-port Host sets the plain kandev_session,
// the middleware authenticates with it, and logout clears it (invariant
// back-compat guard: identical before and after the change).
func TestSessionCookiePlainOnDefaultPort(t *testing.T) {
router, _ := newAPIFixture(t, true)
client := &apiClient{t: t, router: router}
rec := client.do(http.MethodPost, "/api/v1/auth/setup", map[string]any{
"email": "admin@x.dev", "password": "adminpass123", "display_name": "Admin",
})
if rec.Code != http.StatusOK {
t.Fatalf("setup: %d body=%s", rec.Code, rec.Body.String())
}
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session")
if client.cookie == nil || client.cookie.Name != "kandev_session" {
t.Fatalf("captured cookie = %+v, want plain kandev_session", client.cookie)
}
if rec := client.do(http.MethodGet, "/api/v1/users", nil); rec.Code != http.StatusOK {
t.Fatalf("default-port session: %d, want 200", rec.Code)
}
rec = client.do(http.MethodPost, "/api/v1/auth/logout", nil)
if rec.Code != http.StatusNoContent {
t.Fatalf("logout: %d", rec.Code)
}
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session")
}
// TestSessionCookieForeignPortRejectedOnPortedHost is the tier-1b rollback
// guard: a request carrying a cookie under a name the resolver does not
// derive for its Host is rejected both before and after the change, so a
// regression where the middleware matches any scoped name regardless of port
// cannot slip in.
func TestSessionCookieForeignPortRejectedOnPortedHost(t *testing.T) {
router, _ := newAPIFixture(t, true)
client := &apiClient{t: t, router: router}
setupOn(t, client, "127.0.0.1:8443")
foreign := &apiClient{t: t, router: router}
rec := foreign.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = "127.0.0.1:8443"
req.Header.Set("Cookie", "kandev_session_9443="+client.cookie.Value)
})
if rec.Code != http.StatusUnauthorized {
t.Fatalf("foreign-port scoped cookie: %d, want 401", rec.Code)
}
}
// TestTwoInstancesSessionIsolation drives the two-instance behavioral
// regression: independent stores and request Hosts 127.0.0.1:8443 /
// 127.0.0.1:9443. Logging into one must not authenticate (or invalidate) the
// other, and each instance authenticates only with its own port's cookie
// name.
func TestTwoInstancesSessionIsolation(t *testing.T) {
routerA, _ := newAPIFixture(t, true)
routerB, _ := newAPIFixture(t, true)
clientA := &apiClient{t: t, router: routerA}
clientB := &apiClient{t: t, router: routerB}
setupOn(t, clientA, "127.0.0.1:8443")
if clientA.cookie == nil || clientA.cookie.Name != "kandev_session_8443" {
t.Fatalf("A cookie = %+v, want kandev_session_8443", clientA.cookie)
}
// B rejects A's scoped cookie (failing-before: pre-change both wrote the
// same unprefixed name, so A's token authenticated on B).
rec := clientB.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = "127.0.0.1:9443"
req.Header.Set("Cookie", clientA.cookie.Name+"="+clientA.cookie.Value)
})
if rec.Code != http.StatusUnauthorized {
t.Fatalf("B with A's cookie: %d, want 401", rec.Code)
}
// Logging into B keeps A's session intact.
setupOn(t, clientB, "127.0.0.1:9443")
if clientB.cookie == nil || clientB.cookie.Name != "kandev_session_9443" {
t.Fatalf("B cookie = %+v, want kandev_session_9443", clientB.cookie)
}
if rec := clientA.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = "127.0.0.1:8443"
}); rec.Code != http.StatusOK {
t.Fatalf("A after B login: %d, want 200 (A's session must survive)", rec.Code)
}
if rec := clientB.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = "127.0.0.1:9443"
}); rec.Code != http.StatusOK {
t.Fatalf("B after B login: %d, want 200", rec.Code)
}
}
// authFixtureConfig is the minimal auth-enabled config for the proxy-contract
// fixtures.
func authFixtureConfig() *config.Config {
cfg := &config.Config{}
cfg.Features.Auth = true
cfg.Auth.SessionTTLHours = 720
return cfg
}
// TestProxyContractPreservedHost drives the compliant reverse-proxy setup (a):
// the proxy preserves the full Host (host:port). The origin gate passes
// (hostname match) — reachability is invariant — and the failing-before
// assertion is the paired Set-Cookie: kandev_session_8443.
func TestProxyContractPreservedHost(t *testing.T) {
router, _ := newCORSGatedAPIFixture(t, authFixtureConfig())
client := &apiClient{t: t, router: router}
host := "public.example:8443"
origin := "https://public.example:8443"
rec := client.do(http.MethodPost, "/api/v1/auth/setup", map[string]any{
"email": "admin@x.dev", "password": "adminpass123", "display_name": "Admin",
}, func(req *http.Request) {
req.Host = host
req.Header.Set("Origin", origin)
})
if rec.Code != http.StatusOK {
t.Fatalf("setup through preserved Host: %d body=%s", rec.Code, rec.Body.String())
}
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session_8443")
if rec := client.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = host
req.Header.Set("Origin", origin)
}); rec.Code != http.StatusOK {
t.Fatalf("authenticated call through preserved Host: %d, want 200", rec.Code)
}
}
// TestProxyContractPortRewriteDerivesPublicPortFromXFH drives the compliant
// setup (b): a same-hostname port rewrite with a correct X-Forwarded-Host
// from a TRUSTED reverse proxy (peer inside KANDEV_TRUSTED_PROXIES, as in
// buildHTTPServer). The gate passes (ports are not compared) and the
// failing-before assertion is the cookie resolver deriving _8443 from XFH,
// not _38429 from the internal Host.
func TestProxyContractPortRewriteDerivesPublicPortFromXFH(t *testing.T) {
router, _ := newCORSGatedAPIFixture(t, authFixtureConfig(), "10.0.0.0/8")
client := &apiClient{t: t, router: router}
rec := client.do(http.MethodPost, "/api/v1/auth/setup", map[string]any{
"email": "admin@x.dev", "password": "adminpass123", "display_name": "Admin",
}, func(req *http.Request) {
req.RemoteAddr = "10.0.0.5:5555" // inside the trusted proxy range
req.Host = "public.example:38429"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
req.Header.Set("Origin", "https://public.example:8443")
})
if rec.Code != http.StatusOK {
t.Fatalf("setup through port rewrite: %d body=%s", rec.Code, rec.Body.String())
}
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session_8443")
if rec := client.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.RemoteAddr = "10.0.0.5:5555"
req.Host = "public.example:38429"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
req.Header.Set("Origin", "https://public.example:8443")
}); rec.Code != http.StatusOK {
t.Fatalf("authenticated call through port rewrite: %d, want 200", rec.Code)
}
}
// TestProxyContractPortRewriteUntrustedXFHIgnored pins the secure default:
// an UNTRUSTED peer's X-Forwarded-Host is stripped before the cookie resolver
// runs (browsers never send the header, so only proxies or scripts do), and
// the suffix falls back to the request Host. This is the silent no-op the
// pre-fix resolver would have performed; the strip middleware now drops the
// header with a warning instead.
func TestProxyContractPortRewriteUntrustedXFHIgnored(t *testing.T) {
router, _ := newCORSGatedAPIFixture(t, authFixtureConfig())
client := &apiClient{t: t, router: router}
rec := client.do(http.MethodPost, "/api/v1/auth/setup", map[string]any{
"email": "admin@x.dev", "password": "adminpass123", "display_name": "Admin",
}, func(req *http.Request) {
req.Host = "public.example:38429"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
req.Header.Set("Origin", "https://public.example:8443")
})
if rec.Code != http.StatusOK {
t.Fatalf("setup through untrusted XFH: %d body=%s", rec.Code, rec.Body.String())
}
assertSessionCookieNames(t, rec, "kandev_session", "kandev_session_38429")
if rec := client.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = "public.example:38429"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
req.Header.Set("Origin", "https://public.example:8443")
}); rec.Code != http.StatusOK {
t.Fatalf("authenticated call through untrusted XFH: %d, want 200", rec.Code)
}
}
// TestProxyContractHostnameRewriteRejected403 drives the non-compliant
// reverse-proxy setup: the proxy rewrites a non-loopback hostname (Host is a
// DIFFERENT non-loopback hostname, not a different port). The origin gate
// compares Origin hostname to Host and ignores X-Forwarded-Host, so the
// request is rejected 403 before auth — an invariant branch that must not be
// weakened by this fix.
func TestProxyContractHostnameRewriteRejected403(t *testing.T) {
router, _ := newCORSGatedAPIFixture(t, authFixtureConfig())
client := &apiClient{t: t, router: router}
rec := client.do(http.MethodPost, "/api/v1/auth/setup", map[string]any{
"email": "admin@x.dev", "password": "adminpass123", "display_name": "Admin",
}, func(req *http.Request) {
req.Host = "internal:38429" // different non-loopback hostname
req.Header.Set("X-Forwarded-Host", "public.example:8443")
req.Header.Set("Origin", "https://public.example:8443")
})
if rec.Code != http.StatusForbidden {
t.Fatalf("hostname rewrite: %d, want 403 (origin gate rejects before auth)", rec.Code)
}
assertSessionCookieNames(t, rec, "kandev_session")
}
// TestSameCustomCookieNameStillConflicts pins the documented exception: a
// custom auth.cookieName disables automatic port isolation, so two instances
// configured with the same name on one cookie host write the identical cookie
// name regardless of port (and would overwrite each other in a shared jar).
func TestSameCustomCookieNameStillConflicts(t *testing.T) {
makeCfg := func() *config.Config {
cfg := authFixtureConfig()
cfg.Auth.CookieName = "shared_session"
return cfg
}
routerA, _ := newAPIFixtureWithCfg(t, makeCfg())
routerB, _ := newAPIFixtureWithCfg(t, makeCfg())
clientA := &apiClient{t: t, router: routerA, cookiePrefix: "shared_session"}
clientB := &apiClient{t: t, router: routerB, cookiePrefix: "shared_session"}
rec := setupOn(t, clientA, "127.0.0.1:8443")
assertSessionCookieNames(t, rec, "shared_session", "shared_session")
rec = setupOn(t, clientB, "127.0.0.1:9443")
assertSessionCookieNames(t, rec, "shared_session", "shared_session")
// Same name on both ports: no isolation — B's middleware looks up the
// same cookie name A wrote (a browser jar would hold exactly one).
if clientA.cookie.Name != clientB.cookie.Name {
t.Fatalf("custom names differ across ports (%q vs %q), isolation must be disabled by design",
clientA.cookie.Name, clientB.cookie.Name)
}
if rec := clientB.do(http.MethodGet, "/api/v1/users", nil, func(req *http.Request) {
req.Host = "127.0.0.1:9443"
}); rec.Code != http.StatusOK {
t.Fatalf("B's own custom-name session: %d, want 200", rec.Code)
}
}
+113 -1
View File
@@ -13,13 +13,17 @@
package httpmw
import (
"net"
"net/http"
"net/netip"
"strings"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/auth"
"github.com/kandev/kandev/internal/auth/authn"
"github.com/kandev/kandev/internal/common/logger"
userstore "github.com/kandev/kandev/internal/user/store"
)
@@ -49,6 +53,114 @@ func Middleware(svc *auth.Service) gin.HandlerFunc {
}
}
// StripUntrustedForwardedHost removes X-Forwarded-Host from requests whose
// immediate peer is not a trusted proxy. It is a pure header-modifier: it
// never aborts, so gin continues to the next handler automatically once the
// function returns (no c.Next() call needed). Browsers never send
// X-Forwarded-Host; only a reverse proxy in front of the backend should, and
// only to carry the browser's original host:port through a port-rewrite to
// the port-scoped cookie-name resolver (httpcookie.PortSuffix). Without this
// gate a non-browser client could pick its own forwarded host, and with it
// its own port-scoped cookie name, by setting the header directly. The same
// trusted list that gates X-Forwarded-For (gin's ClientIP via
// SetTrustedProxies) gates this header so the two trust decisions cannot
// diverge; an untrusted value is dropped (with a warning) and the resolver
// falls back to the request Host. backendapp passes the list returned by its
// configureTrustedProxies, so the two uses share one configuration.
func StripUntrustedForwardedHost(trusted []string, log *logger.Logger) gin.HandlerFunc {
matcher := newTrustedProxyMatcher(trusted)
return func(c *gin.Context) {
if c.GetHeader("X-Forwarded-Host") == "" {
return
}
peer := remoteAddrHost(c.Request.RemoteAddr)
if matcher.contains(peer) {
return
}
log.Warn("ignoring X-Forwarded-Host from untrusted peer",
zap.String("peer", peer),
zap.String("forwarded_host", c.GetHeader("X-Forwarded-Host")))
c.Request.Header.Del("X-Forwarded-Host")
}
}
// trustedProxyMatcher matches a peer IP against the trusted-proxy list (bare
// IPs and CIDRs, the same entries configureTrustedProxies handed to gin).
type trustedProxyMatcher struct {
addresses []netip.Addr
prefixes []netip.Prefix
}
// newTrustedProxyMatcher indexes the trusted-proxy list (bare IPs and CIDRs)
// for O(1) peer matching. IPv4-mapped entries are normalized to their IPv4
// form so the matcher agrees with gin's trust decision (see contains).
func newTrustedProxyMatcher(trusted []string) *trustedProxyMatcher {
m := &trustedProxyMatcher{}
for _, entry := range trusted {
if strings.Contains(entry, "/") {
prefix, err := netip.ParsePrefix(entry)
if err != nil {
continue
}
if prefix.Addr().Is4In6() {
// gin normalizes IPv4-mapped CIDRs to their IPv4 form
// (::ffff:10.0.0.0/120 → 10.0.0.0/24, mask sliced 96 bits
// shorter); mirror it so the two trust decisions cannot
// diverge. A mapped-form CIDR with exactly 96 bits
// degenerates to 0.0.0.0/0 in gin (trusts every IPv4 peer)
// and is mirrored as such; with fewer than 96 bits gin's
// entry matches no IPv4-form peer and the matcher skips it,
// failing closed (unsupported configuration).
prefix = netip.PrefixFrom(prefix.Addr().Unmap(), prefix.Bits()-96)
}
if prefix.IsValid() {
m.prefixes = append(m.prefixes, prefix)
}
continue
}
if addr, err := netip.ParseAddr(entry); err == nil {
m.addresses = append(m.addresses, addr.Unmap())
}
}
return m
}
// contains reports whether host is one of the trusted addresses or inside one
// of the trusted prefixes. Unparsable peers (Unix sockets, empty RemoteAddr)
// are never trusted. IPv4-mapped IPv6 peers are unmapped so the matcher
// agrees with gin's trust decision (which compares the IPv4 form): if the two
// ever diverged, the strip would fail CLOSED (dropping a header gin trusts),
// breaking the port-rewrite cookie flow rather than security.
func (m *trustedProxyMatcher) contains(host string) bool {
addr, err := netip.ParseAddr(host)
if err != nil {
return false
}
addr = addr.Unmap()
for _, a := range m.addresses {
if a == addr {
return true
}
}
for _, p := range m.prefixes {
if p.Contains(addr) {
return true
}
}
return false
}
// remoteAddrHost returns the host part of a RemoteAddr ("IP:port"), or the
// whole value when it has no port.
// remoteAddrHost returns the host part of a RemoteAddr ("IP:port"), or the
// whole value when it has no port.
func remoteAddrHost(remoteAddr string) string {
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
return host
}
return remoteAddr
}
// SyntheticIdentity is the implicit identity used while auth is disabled.
func SyntheticIdentity() authn.Identity {
return authn.Identity{UserID: userstore.DefaultUserID, Role: authn.RoleAdmin, Synthetic: true}
@@ -58,7 +170,7 @@ func SyntheticIdentity() authn.Identity {
// bearer. Shared with the WS gateway's upgrade-time check.
func ResolveRequest(c *gin.Context, svc *auth.Service) (authn.Identity, bool) {
ctx := c.Request.Context()
if cookie, err := c.Cookie(svc.CookieName()); err == nil && cookie != "" {
if cookie, err := c.Cookie(svc.CookieNameForRequest(c.Request)); err == nil && cookie != "" {
if identity, ok := svc.ResolveSessionToken(ctx, cookie); ok {
return identity, true
}
@@ -10,11 +10,15 @@ import (
"github.com/gin-gonic/gin"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"github.com/kandev/kandev/internal/auth"
"github.com/kandev/kandev/internal/auth/authn"
authstore "github.com/kandev/kandev/internal/auth/store"
"github.com/kandev/kandev/internal/common/config"
"github.com/kandev/kandev/internal/common/logger"
userstore "github.com/kandev/kandev/internal/user/store"
)
@@ -300,6 +304,224 @@ func TestInvalidCredentialsAreRejected(t *testing.T) {
}
}
// TestEnabledModeScopedSessionCookieAuthenticates pins the middleware's
// request-aware cookie resolution: on a ported Host it reads the
// port-scoped session cookie name.
func TestEnabledModeScopedSessionCookieAuthenticates(t *testing.T) {
svc := newTestService(t, true)
token := setupAdmin(t, svc)
router := newTestRouter(svc)
rec := doRequest(router, http.MethodGet, "/api/v1/probe", func(r *http.Request) {
r.Host = "127.0.0.1:8443"
r.AddCookie(&http.Cookie{Name: "kandev_session_8443", Value: token})
})
if rec.Code != http.StatusOK {
t.Fatalf("probe with scoped session: %d body=%s", rec.Code, rec.Body.String())
}
if contains(rec.Body.String(), `"synthetic":true`) {
t.Fatal("real session must not be synthetic")
}
}
// TestEnabledModeRejectsForeignPortSessionCookie pins per-port resolution: a
// token carried under another port's scoped name is not read for this Host.
func TestEnabledModeRejectsForeignPortSessionCookie(t *testing.T) {
svc := newTestService(t, true)
token := setupAdmin(t, svc)
router := newTestRouter(svc)
rec := doRequest(router, http.MethodGet, "/api/v1/probe", func(r *http.Request) {
r.Host = "127.0.0.1:8443"
r.AddCookie(&http.Cookie{Name: "kandev_session_9443", Value: token})
})
if rec.Code != http.StatusUnauthorized {
t.Fatalf("probe with foreign-port session: %d, want 401", rec.Code)
}
}
func contains(haystack, needle string) bool {
return strings.Contains(haystack, needle)
}
// echoXFH handler reports whether X-Forwarded-Host reached the handler.
// echoXFH reports whether X-Forwarded-Host reached the handler.
func echoXFH(c *gin.Context) {
if xfh := c.GetHeader("X-Forwarded-Host"); xfh != "" {
c.String(http.StatusOK, xfh)
return
}
c.String(http.StatusOK, "stripped")
}
// stripRouter builds a gin router with the X-Forwarded-Host strip middleware
// (trusted list as given) and an echoXFH handler that reports what reached it.
func stripRouter(trusted ...string) *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(StripUntrustedForwardedHost(trusted, mustNopLogger()))
router.GET("/", echoXFH)
return router
}
// mustNopLogger returns a discard logger for strip-middleware tests.
func mustNopLogger() *logger.Logger {
log, err := logger.NewFromZap(zap.NewNop())
if err != nil {
panic(err)
}
return log
}
// TestStripUntrustedForwardedHostUntrustedPeerStrips pins the secure default:
// without a trusted-proxy list, an X-Forwarded-Host presented by the peer is
// dropped before the handler (and the cookie resolver) sees it.
func TestStripUntrustedForwardedHostUntrustedPeerStrips(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
stripRouter().ServeHTTP(rec, req)
if got := rec.Body.String(); got != "stripped" {
t.Fatalf("untrusted XFH body = %q, want stripped", got)
}
}
// TestStripUntrustedForwardedHostTrustedPeerKeeps pins the opt-in behavior: a
// peer inside the trusted list may carry X-Forwarded-Host (the proxy-authored
// browser host:port) through to the cookie resolver.
func TestStripUntrustedForwardedHostTrustedPeerKeeps(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "10.0.0.5:5555"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
stripRouter("10.0.0.0/8").ServeHTTP(rec, req)
if got := rec.Body.String(); got != "public.example:8443" {
t.Fatalf("trusted XFH body = %q, want public.example:8443", got)
}
}
// TestStripUntrustedForwardedHostIPv4MappedPeerKeeps pins the IPv4-mapped
// IPv6 equivalence: gin compares the IPv4 form of an IPv4-mapped peer against
// the trusted list, and the matcher must agree (fail-closed here would break
// the port-rewrite cookie flow for dual-stack proxies).
func TestStripUntrustedForwardedHostIPv4MappedPeerKeeps(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "[::ffff:10.0.0.5]:5555"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
stripRouter("10.0.0.0/8", "10.0.0.5").ServeHTTP(rec, req)
if got := rec.Body.String(); got != "public.example:8443" {
t.Fatalf("IPv4-mapped trusted XFH body = %q, want public.example:8443", got)
}
}
// TestStripUntrustedForwardedHostMappedFormCIDRKeeps pins the mapped-form
// CIDR normalization: gin treats ::ffff:10.0.0.0/120 as 10.0.0.0/24 and
// trusts peers under it in either representation; the matcher must agree.
func TestStripUntrustedForwardedHostMappedFormCIDRKeeps(t *testing.T) {
for _, peer := range []string{"10.0.0.5:5555", "[::ffff:10.0.0.5]:5555"} {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = peer
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
stripRouter("::ffff:10.0.0.0/120").ServeHTTP(rec, req)
if got := rec.Body.String(); got != "public.example:8443" {
t.Fatalf("mapped-form CIDR peer %q: XFH body = %q, want public.example:8443", peer, got)
}
}
}
// TestStripUntrustedForwardedHostDegenerateMappedCIDRFailsClosed pins the
// unsupported corner: a mapped-form CIDR with fewer than 96 bits matches no
// IPv4-form peer in gin (dead entry); the matcher mirrors that by skipping it
// (fail closed) rather than silently trusting something gin would not.
func TestStripUntrustedForwardedHostDegenerateMappedCIDRFailsClosed(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "203.0.113.9:5555"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
stripRouter("::ffff:10.0.0.0/90").ServeHTTP(rec, req)
if got := rec.Body.String(); got != "stripped" {
t.Fatalf("degenerate mapped CIDR body = %q, want stripped", got)
}
}
// TestStripUntrustedForwardedHostMappedForm96MirrorsGin pins the /96
// boundary: a mapped-form /96 degenerates to 0.0.0.0/0 in gin (trusts every
// IPv4 peer), and the matcher mirrors that trust instead of failing closed —
// failing closed there would strip a header gin trusts and break the
// port-rewrite cookie flow for the config.
func TestStripUntrustedForwardedHostMappedForm96MirrorsGin(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "203.0.113.9:5555" // any IPv4 peer
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
stripRouter("::ffff:10.0.0.0/96").ServeHTTP(rec, req)
if got := rec.Body.String(); got != "public.example:8443" {
t.Fatalf("mapped /96 body = %q, want public.example:8443 (gin trusts all IPv4)", got)
}
}
// TestStripUntrustedForwardedHostCIDRExcludesOutOfRangePeer pins the CIDR
// boundary: the peer just outside the trusted prefix is untrusted.
func TestStripUntrustedForwardedHostCIDRExcludesOutOfRangePeer(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "192.168.1.7:5555"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
stripRouter("192.168.0.0/24").ServeHTTP(rec, req)
if got := rec.Body.String(); got != "stripped" {
t.Fatalf("out-of-CIDR XFH body = %q, want stripped", got)
}
}
// TestStripUntrustedForwardedHostNoHeaderUntouched pins the no-op path: a
// request without the header passes through unchanged.
func TestStripUntrustedForwardedHostNoHeaderUntouched(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
stripRouter().ServeHTTP(rec, req)
if got := rec.Body.String(); got != "stripped" {
t.Fatalf("no-header body = %q, want stripped (handler default)", got)
}
}
// TestStripUntrustedForwardedHostWarns pins the operator signal: stripping an
// untrusted X-Forwarded-Host emits a warning naming the peer, so a
// misconfigured proxy (or a client trying to pick its own cookie scope) is
// visible in the logs instead of silently no-opping.
func TestStripUntrustedForwardedHostWarns(t *testing.T) {
core, logs := observer.New(zapcore.WarnLevel)
log, err := logger.NewFromZap(zap.New(core))
if err != nil {
t.Fatalf("observer logger: %v", err)
}
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(StripUntrustedForwardedHost(nil, log))
router.GET("/", echoXFH)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "203.0.113.9:5555"
req.Header.Set("X-Forwarded-Host", "public.example:8443")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if got := rec.Body.String(); got != "stripped" {
t.Fatalf("warn-test body = %q, want stripped", got)
}
warned := false
for _, entry := range logs.All() {
if !strings.Contains(entry.Message, "X-Forwarded-Host") {
continue
}
warned = true
for _, field := range entry.Context {
if field.Key == "peer" && field.String != "203.0.113.9" {
t.Fatalf("warning peer = %q, want 203.0.113.9", field.String)
}
}
}
if !warned {
t.Fatal("no X-Forwarded-Host warning was logged")
}
}
+28 -2
View File
@@ -11,6 +11,7 @@ package auth
import (
"context"
"errors"
"net/http"
"strings"
"sync"
"sync/atomic"
@@ -19,6 +20,7 @@ import (
"github.com/kandev/kandev/internal/auth/authn"
"github.com/kandev/kandev/internal/auth/store"
"github.com/kandev/kandev/internal/common/config"
"github.com/kandev/kandev/internal/common/httpcookie"
"github.com/kandev/kandev/internal/common/logger"
usermodels "github.com/kandev/kandev/internal/user/models"
userstore "github.com/kandev/kandev/internal/user/store"
@@ -47,6 +49,13 @@ const (
sessionTouchInterval = time.Minute
maxUserAgentLen = 256
// baseSessionCookieName is the session cookie base name. The effective
// name is request-host derived (see CookieNameForRequest): port-scoped on
// a ported host so multiple instances on one host keep isolated sessions,
// plain on a default-port host. An explicit auth.cookieName config value
// replaces the base name entirely (verbatim, never suffixed).
baseSessionCookieName = "kandev_session"
)
// Sentinel errors surfaced to HTTP handlers.
@@ -128,12 +137,29 @@ func (s *Service) Mode() Mode {
return ModeDisabled
}
// CookieName returns the configured session cookie name.
// CookieName returns the configured session cookie name (request-less form).
// An explicitly configured auth.cookieName is returned verbatim; the empty
// default resolves to the base name. Contexts without a request (tests) must
// pass this form or use CookieNameForRequest with a request.
func (s *Service) CookieName() string {
if name := strings.TrimSpace(s.cfg.Auth.CookieName); name != "" {
return name
}
return "kandev_session"
return baseSessionCookieName
}
// CookieNameForRequest returns the session cookie name for a specific
// request. A non-empty configured auth.cookieName is returned verbatim —
// custom names disable automatic port isolation and must be unique per
// cookie host. The empty default is port-scoped from the request host
// (kandev_session_<port> on a ported host, plain kandev_session otherwise)
// so two instances on one host (same IP, different ports) keep isolated
// sessions instead of overwriting each other's token.
func (s *Service) CookieNameForRequest(r *http.Request) string {
if name := strings.TrimSpace(s.cfg.Auth.CookieName); name != "" {
return name
}
return httpcookie.ScopedName(r, baseSessionCookieName)
}
// SessionTTL returns the sliding session lifetime.
+2 -2
View File
@@ -62,8 +62,8 @@ type ExternalIdentity struct {
// New users are always provisioned as members; external login never creates or
// elevates an admin (role changes stay with admin user management). A disabled
// account is rejected. The returned string is the raw session token to place
// in the kandev_session cookie — the caller (the plugin webhook relay) sets the
// cookie; the plugin never receives this token.
// in the session cookie (name derived from the request host) — the caller (the
// plugin webhook relay) sets the cookie; the plugin never receives this token.
func (s *Service) AuthenticateExternal(ctx context.Context, ext ExternalIdentity, userAgent, ip string) (*usermodels.User, string, error) {
if s.Mode() != ModeEnabled {
return nil, "", ErrSSONotEnabled
+2 -1
View File
@@ -24,7 +24,8 @@ type LoginIdentity struct {
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
// Session is a browser session backed by the kandev_session cookie.
// Session is a browser session backed by the session cookie (base name
// kandev_session; effective name derived from the request host).
type Session struct {
ID string `db:"id" json:"id"`
UserID string `db:"user_id" json:"user_id"`
+5 -5
View File
@@ -20,10 +20,10 @@ import (
// pluginSSOBridge adapts the auth service to plugins.AuthLoginBridge: it
// authenticates a plugin-asserted external identity (OIDC/SAML) and sets the
// kandev_session cookie, so an auth-capable plugin can complete SSO login
// without ever holding the raw session token. AuthenticateExternal enforces
// that auth is enabled, so this returns an error (surfaced as 403 by the
// plugin webhook relay) when it is not.
// session cookie (name derived from the request host), so an auth-capable
// plugin can complete SSO login without ever holding the raw session token.
// AuthenticateExternal enforces that auth is enabled, so this returns an error
// (surfaced as 403 by the plugin webhook relay) when it is not.
type pluginSSOBridge struct {
auth *auth.Service
}
@@ -38,7 +38,7 @@ func (b pluginSSOBridge) LoginExternal(c *gin.Context, provider, subject, email,
if err != nil {
return err
}
authhttpapi.SetSessionCookie(c, b.auth.CookieName(), token, b.auth.SessionTTL())
authhttpapi.SetSessionCookie(c, b.auth.CookieNameForRequest(c.Request), token, b.auth.SessionTTL())
return nil
}
@@ -0,0 +1,118 @@
package backendapp
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"github.com/kandev/kandev/internal/auth"
authstore "github.com/kandev/kandev/internal/auth/store"
"github.com/kandev/kandev/internal/common/config"
userstore "github.com/kandev/kandev/internal/user/store"
)
// newEnabledAuthService builds an auth service in ModeEnabled (features.auth
// on + an admin identity exists) over an in-memory store pair — the state the
// plugin SSO bridge requires.
func newEnabledAuthService(t *testing.T, cfg *config.Config) *auth.Service {
t.Helper()
conn, err := sqlx.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
t.Cleanup(func() { _ = conn.Close() })
users, cleanup, err := userstore.Provide(conn, conn)
if err != nil {
t.Fatalf("user store: %v", err)
}
t.Cleanup(func() { _ = cleanup() })
st, err := authstore.New(conn, conn)
if err != nil {
t.Fatalf("auth store: %v", err)
}
svc, err := auth.NewService(context.Background(), auth.Deps{Cfg: cfg, Store: st, Users: users})
if err != nil {
t.Fatalf("auth service: %v", err)
}
if _, _, err := svc.Setup(context.Background(), "admin@x.dev", "adminpass123", "Admin", "", ""); err != nil {
t.Fatalf("setup admin: %v", err)
}
if svc.Mode() != auth.ModeEnabled {
t.Fatalf("mode = %s, want enabled", svc.Mode())
}
return svc
}
// ssoBridgeCookieNames runs the real pluginSSOBridge LoginExternal on a Gin
// context whose request Host carries the given host, and returns the session
// cookie names set on the response.
func ssoBridgeCookieNames(t *testing.T, svc *auth.Service, host string) []string {
t.Helper()
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/api/plugins/p/webhooks/cb", nil)
c.Request.Host = host
bridge := pluginSSOBridge{auth: svc}
if err := bridge.LoginExternal(c, "oidc:iss", "sub-1", "alice@x.dev", "Alice"); err != nil {
t.Fatalf("LoginExternal: %v", err)
}
var names []string
for _, cookie := range rec.Result().Cookies() {
names = append(names, cookie.Name)
}
return names
}
// TestPluginSSOBridgeSetsScopedSessionCookie drives the REAL bridge
// (backendapp/auth.go), not the plugins-package fake: LoginExternal on a Gin
// request Host 127.0.0.1:8443 must set kandev_session_8443. A stale bridge
// call to b.auth.CookieName() would pass resolver tests while emitting the
// plain name for ported SSO.
func TestPluginSSOBridgeSetsScopedSessionCookie(t *testing.T) {
cfg := &config.Config{}
cfg.Features.Auth = true
cfg.Auth.SessionTTLHours = 720
svc := newEnabledAuthService(t, cfg)
names := ssoBridgeCookieNames(t, svc, "127.0.0.1:8443")
if len(names) != 1 || names[0] != "kandev_session_8443" {
t.Fatalf("SSO Set-Cookie names = %v, want exactly [kandev_session_8443]", names)
}
}
// TestPluginSSOBridgeCustomCookieNameVerbatim pins the custom-name contract
// through the real bridge: a configured auth.cookieName is set verbatim on a
// ported Host (never suffixed).
func TestPluginSSOBridgeCustomCookieNameVerbatim(t *testing.T) {
cfg := &config.Config{}
cfg.Features.Auth = true
cfg.Auth.SessionTTLHours = 720
cfg.Auth.CookieName = "sso_session"
svc := newEnabledAuthService(t, cfg)
names := ssoBridgeCookieNames(t, svc, "127.0.0.1:8443")
if len(names) != 1 || names[0] != "sso_session" {
t.Fatalf("SSO Set-Cookie names = %v, want exactly [sso_session]", names)
}
}
// TestPluginSSOBridgeDefaultPortPlainName pins the no-port branch through the
// real bridge: a default-port Host keeps the plain base name.
func TestPluginSSOBridgeDefaultPortPlainName(t *testing.T) {
cfg := &config.Config{}
cfg.Features.Auth = true
cfg.Auth.SessionTTLHours = 720
svc := newEnabledAuthService(t, cfg)
names := ssoBridgeCookieNames(t, svc, "example.com")
if len(names) != 1 || names[0] != "kandev_session" {
t.Fatalf("SSO Set-Cookie names = %v, want exactly [kandev_session]", names)
}
}
@@ -8,6 +8,7 @@ import (
"go.uber.org/zap"
"github.com/kandev/kandev/internal/common/httpcookie"
officedashboard "github.com/kandev/kandev/internal/office/dashboard"
taskdto "github.com/kandev/kandev/internal/task/dto"
taskmodels "github.com/kandev/kandev/internal/task/models"
@@ -391,7 +392,10 @@ func (b bootStateBuilder) addOfficeRouteState(ctx context.Context, req *http.Req
state["office"] = b.officeState(ctx, activeID)
}
// officeWorkspaces resolves the office workspaces and the active workspace id from the request cookie.
// officeWorkspaces resolves the office workspaces and the active workspace id
// from the request cookies and user settings. Candidates, each validated
// against the office workspace set: general cookie (when it names an office
// workspace) → office cookie → settings → first office workspace.
func (b bootStateBuilder) officeWorkspaces(ctx context.Context, req *http.Request) ([]taskdto.WorkspaceDTO, string, error) {
if b.p.taskSvc == nil {
return nil, "", nil
@@ -412,7 +416,16 @@ func (b bootStateBuilder) officeWorkspaces(ctx context.Context, req *http.Reques
officeItems = append(officeItems, item)
}
}
return items, resolveActiveOfficeWorkspaceID(officeItems, readActiveWorkspaceCookie(req)), nil
settingsWorkspaceID := ""
if settings, ok := b.userSettings(ctx); ok {
settingsWorkspaceID = settings.Settings.WorkspaceID
}
return items, resolveActiveOfficeWorkspaceID(
officeItems,
readActiveWorkspaceCookie(req),
readOfficeWorkspaceCookie(req),
settingsWorkspaceID,
), nil
}
// officeState assembles the office boot state (agents, projects, inbox, dashboard) for the active workspace.
@@ -778,11 +791,20 @@ func mapTaskCreateLastUsed(value usermodels.TaskCreateLastUsed) map[string]any {
}
}
// resolveActiveOfficeWorkspaceID returns the cookie workspace id when it is valid, otherwise the first workspace id.
func resolveActiveOfficeWorkspaceID(workspaces []taskdto.WorkspaceDTO, cookieWorkspaceID string) string {
for _, workspace := range workspaces {
if workspace.ID == cookieWorkspaceID {
return workspace.ID
// resolveActiveOfficeWorkspaceID returns the first candidate — general cookie,
// office cookie, settings — that names a valid office workspace, otherwise the
// first office workspace id.
func resolveActiveOfficeWorkspaceID(
workspaces []taskdto.WorkspaceDTO,
generalCookieID string,
officeCookieID string,
settingsID string,
) string {
for _, candidate := range []string{generalCookieID, officeCookieID, settingsID} {
for _, workspace := range workspaces {
if workspace.ID == candidate {
return workspace.ID
}
}
}
if len(workspaces) > 0 {
@@ -857,12 +879,50 @@ func tasksListGroupForRoute(queryValue, settingsValue string) string {
return usermodels.NormalizeTasksListGroup(settingsValue)
}
// readActiveWorkspaceCookie reads the active workspace id from the cookies.
// readActiveWorkspaceCookie reads the active workspace id from the GENERAL
// cookie family only: the port-scoped name first, then the legacy unprefixed
// name as a read-only fallback (a pre-upgrade selection survives). The
// office-family cookies are deliberately not consulted — generic boot paths
// resolve settings/first when only an office cookie exists (parity with the
// frontend generic reader). The suffix derives from the request host
// (X-Forwarded-Host precedence), the same port the SPA derives from the API
// base URL.
func readActiveWorkspaceCookie(req *http.Request) string {
if req == nil {
return ""
}
for _, name := range []string{activeWorkspaceCookie, legacyOfficeWorkspaceCookie} {
// On a default-port host the scoped name IS the legacy name; reading the
// same cookie twice is a no-op, so only probe the legacy name when the
// port actually scopes it.
names := []string{httpcookie.ScopedName(req, activeWorkspaceCookie)}
if scoped := names[0]; scoped != activeWorkspaceCookie {
names = append(names, activeWorkspaceCookie)
}
for _, name := range names {
cookie, err := req.Cookie(name)
if err == nil {
if value := strings.TrimSpace(cookie.Value); value != "" {
return value
}
}
}
return ""
}
// readOfficeWorkspaceCookie reads the active workspace id from the OFFICE
// cookie family only: the port-scoped name first, then the legacy unprefixed
// name as a read-only fallback. The general cookie is never consulted here.
func readOfficeWorkspaceCookie(req *http.Request) string {
if req == nil {
return ""
}
// Same default-port dedupe as readActiveWorkspaceCookie: the scoped name
// equals the legacy name when the Host carries no (non-default) port.
names := []string{httpcookie.ScopedName(req, legacyOfficeWorkspaceCookie)}
if scoped := names[0]; scoped != legacyOfficeWorkspaceCookie {
names = append(names, legacyOfficeWorkspaceCookie)
}
for _, name := range names {
cookie, err := req.Cookie(name)
if err == nil {
if value := strings.TrimSpace(cookie.Value); value != "" {
@@ -1,11 +1,16 @@
package backendapp
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/kandev/kandev/internal/task/models"
taskservice "github.com/kandev/kandev/internal/task/service"
userservice "github.com/kandev/kandev/internal/user/service"
"github.com/kandev/kandev/internal/webapp"
)
@@ -92,3 +97,411 @@ func TestBootInitialStateSettingsPrefersTheActiveWorkspaceCookie(t *testing.T) {
t.Fatalf("activeId = %v, want %s", got, created.ID)
}
}
// scopedRequest builds a GET request on the given ported Host with the given
// cookies set (browser-jar style: several cookies may coexist).
func scopedRequest(host string, cookies ...http.Cookie) *http.Request {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Host = host
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
return req
}
func bootStateActiveID(t *testing.T, req *http.Request, params routeParams, route webapp.RouteName) string {
t.Helper()
state := bootInitialState(t.Context(), req, params, webapp.RouteClassification{Route: route})
block, ok := state["workspaces"].(map[string]any)
if !ok {
t.Fatalf("route %s: no workspaces block in state %v", route, state)
}
activeID, _ := block["activeId"].(string)
return activeID
}
// TestReadActiveWorkspaceCookiePrefersScopedName pins the reader contract:
// the port-scoped general name wins over the legacy unprefixed one on a
// ported Host.
func TestReadActiveWorkspaceCookiePrefersScopedName(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "kandev-active-workspace", Value: "legacy-1"},
http.Cookie{Name: "kandev-active-workspace_8443", Value: "scoped-1"},
)
if got := readActiveWorkspaceCookie(req); got != "scoped-1" {
t.Fatalf("readActiveWorkspaceCookie = %q, want scoped-1", got)
}
}
// TestReadActiveWorkspaceCookieFallsBackToLegacy pins the read-only legacy
// fallback: a pre-upgrade selection survives when no scoped cookie exists.
func TestReadActiveWorkspaceCookieFallsBackToLegacy(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "kandev-active-workspace", Value: "legacy-1"},
)
if got := readActiveWorkspaceCookie(req); got != "legacy-1" {
t.Fatalf("readActiveWorkspaceCookie = %q, want legacy-1", got)
}
}
// TestReadActiveWorkspaceCookieIgnoresOfficeFamily pins family separation:
// the general reader never consults the office-family cookies (pre-change it
// read the legacy office name — fails pre-change).
func TestReadActiveWorkspaceCookieIgnoresOfficeFamily(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "office-active-workspace_8443", Value: "office-scoped"},
http.Cookie{Name: "office-active-workspace", Value: "office-legacy"},
)
if got := readActiveWorkspaceCookie(req); got != "" {
t.Fatalf("readActiveWorkspaceCookie = %q, want empty (office family must be ignored)", got)
}
}
// TestReadOfficeWorkspaceCookieScopedFirstLegacyFallback pins the office
// reader: scoped office name first, legacy office name as fallback.
func TestReadOfficeWorkspaceCookieScopedFirstLegacyFallback(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "office-active-workspace", Value: "legacy"},
http.Cookie{Name: "office-active-workspace_8443", Value: "scoped"},
)
if got := readOfficeWorkspaceCookie(req); got != "scoped" {
t.Fatalf("readOfficeWorkspaceCookie = %q, want scoped", got)
}
req = scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "office-active-workspace", Value: "legacy"},
)
if got := readOfficeWorkspaceCookie(req); got != "legacy" {
t.Fatalf("readOfficeWorkspaceCookie = %q, want legacy", got)
}
}
// TestReadOfficeWorkspaceCookieIgnoresGeneralFamily pins the office reader's
// family boundary: the general cookie is never an office candidate.
func TestReadOfficeWorkspaceCookieIgnoresGeneralFamily(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "kandev-active-workspace_8443", Value: "general-scoped"},
http.Cookie{Name: "kandev-active-workspace", Value: "general-legacy"},
)
if got := readOfficeWorkspaceCookie(req); got != "" {
t.Fatalf("readOfficeWorkspaceCookie = %q, want empty (general family must be ignored)", got)
}
}
// TestBootActiveWorkspaceCookieIsolatedPerHost models the browser jar: BOTH
// ports' scoped cookies are present in one request, and each Host resolves
// its own port's selection. Failing-before: the reader ignored all scoped
// names, so both requests resolved the first workspace (non-first fixtures).
func TestBootActiveWorkspaceCookieIsolatedPerHost(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
repo := harness.taskRepo
for _, workspace := range []*models.Workspace{
{ID: "ws-first", Name: "First"},
{ID: "ws-a", Name: "A"},
{ID: "ws-b", Name: "B"},
} {
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
t.Fatalf("CreateWorkspace(%s): %v", workspace.ID, err)
}
}
params := routeParams{taskSvc: harness.taskSvc, userCtrl: harness.userCtrl}
jar := []http.Cookie{
{Name: "kandev-active-workspace_8443", Value: "ws-a"},
{Name: "kandev-active-workspace_9443", Value: "ws-b"},
}
if got := bootStateActiveID(t, scopedRequest("127.0.0.1:8443", jar...), params, webapp.RouteHome); got != "ws-a" {
t.Fatalf("Host 8443 activeId = %q, want ws-a", got)
}
if got := bootStateActiveID(t, scopedRequest("127.0.0.1:9443", jar...), params, webapp.RouteHome); got != "ws-b" {
t.Fatalf("Host 9443 activeId = %q, want ws-b", got)
}
}
// TestBootActiveWorkspaceLegacyFallbackAndScopedPrecedence covers the
// downstream boot-state regression (scenario 3): with no scoped cookie a
// VALID unprefixed legacy id is selected (invariant), a foreign/invalid
// legacy id falls through to the instance-owned fallback (invariant), and
// when both exist the scoped value wins (failing-before).
func TestBootActiveWorkspaceLegacyFallbackAndScopedPrecedence(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
repo := harness.taskRepo
// ListWorkspaces orders by created_at DESC, so ws-first (created last) is
// the fallback "first workspace" — distinct from the legacy selection.
for _, workspace := range []*models.Workspace{
{ID: "ws-legacy", Name: "Legacy"},
{ID: "ws-first", Name: "First"},
} {
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
t.Fatalf("CreateWorkspace(%s): %v", workspace.ID, err)
}
}
params := routeParams{taskSvc: harness.taskSvc, userCtrl: harness.userCtrl}
// Invariant: valid unprefixed legacy id selected when no scoped cookie.
req := scopedRequest("127.0.0.1:8443", http.Cookie{Name: "kandev-active-workspace", Value: "ws-legacy"})
if got := bootStateActiveID(t, req, params, webapp.RouteHome); got != "ws-legacy" {
t.Fatalf("valid legacy id: activeId = %q, want ws-legacy", got)
}
// Invariant: foreign/invalid legacy id falls to the first workspace.
req = scopedRequest("127.0.0.1:8443", http.Cookie{Name: "kandev-active-workspace", Value: "ws-foreign"})
if got := bootStateActiveID(t, req, params, webapp.RouteHome); got != "ws-first" {
t.Fatalf("foreign legacy id: activeId = %q, want ws-first", got)
}
// Failing-before: scoped + legacy both present — the scoped value wins.
req = scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "kandev-active-workspace", Value: "ws-legacy"},
http.Cookie{Name: "kandev-active-workspace_8443", Value: "ws-first"},
)
if got := bootStateActiveID(t, req, params, webapp.RouteHome); got != "ws-first" {
t.Fatalf("scoped over legacy: activeId = %q, want ws-first", got)
}
}
// TestBootGenericRoutesIgnoreOfficeCookies drives the downstream generic-route
// family separation: every generic route that resolves an active workspace id
// resolves settings/first — never the office id — when only office-family
// cookies are present. The legacy-office row fails before the change (the old
// generic reader consulted the legacy office name); the scoped-office row is
// the paired invariant guard.
func TestBootGenericRoutesIgnoreOfficeCookies(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
repo := harness.taskRepo
for _, workspace := range []*models.Workspace{
{ID: "ws-o1", Name: "Office 1", OfficeWorkflowID: "wf-1"},
{ID: "ws-o2", Name: "Office 2", OfficeWorkflowID: "wf-2"},
{ID: "ws-kanban", Name: "Kanban"},
} {
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
t.Fatalf("CreateWorkspace(%s): %v", workspace.ID, err)
}
}
settingsID := "ws-kanban"
if _, err := harness.userSvc.UpdateUserSettings(ctx, &userservice.UpdateUserSettingsRequest{
WorkspaceID: &settingsID,
}); err != nil {
t.Fatalf("UpdateUserSettings: %v", err)
}
params := routeParams{taskSvc: harness.taskSvc, userCtrl: harness.userCtrl}
routes := []webapp.RouteName{
webapp.RouteUnknown,
webapp.RouteHome,
webapp.RouteTasks,
webapp.RouteSettings,
webapp.RouteGitHub,
webapp.RouteGitLab,
webapp.RouteJira,
webapp.RouteLinear,
webapp.RouteStats,
}
for _, route := range routes {
t.Run(string(route)+"/legacy-office-cookie", func(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "office-active-workspace", Value: "ws-o1"},
)
if got := bootStateActiveID(t, req, params, route); got != "ws-kanban" {
t.Fatalf("activeId = %q, want settings workspace ws-kanban (office cookie must be ignored)", got)
}
})
t.Run(string(route)+"/scoped-office-cookie", func(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "office-active-workspace_8443", Value: "ws-o1"},
)
if got := bootStateActiveID(t, req, params, route); got != "ws-kanban" {
t.Fatalf("activeId = %q, want settings workspace ws-kanban (scoped office cookie must be ignored)", got)
}
})
}
// Tasks routeData resolves the same settings/first workspace.
t.Run("tasks-route-data", func(t *testing.T) {
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "office-active-workspace_8443", Value: "ws-o1"},
)
routeData := bootRouteData(ctx, req, params, webapp.RouteClassification{Route: webapp.RouteTasks})
tasksPage, ok := routeData["tasksPage"].(map[string]any)
if !ok {
t.Fatalf("tasks routeData missing tasksPage: %v", routeData)
}
if got := tasksPage["activeWorkspaceId"]; got != "ws-kanban" {
t.Fatalf("tasks routeData activeWorkspaceId = %v, want ws-kanban", got)
}
})
}
// TestBootQuickChatFallsBackToSettingsWithOnlyOfficeCookies covers the
// quick-chat boot fallback separately: on a non-task route with only an
// office cookie present, quick chat follows settings/first — never the office
// id.
func TestBootQuickChatFallsBackToSettingsWithOnlyOfficeCookies(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
repo := harness.taskRepo
for _, workspace := range []*models.Workspace{
{ID: "ws-o1", Name: "Office 1", OfficeWorkflowID: "wf-1"},
{ID: "ws-kanban", Name: "Kanban"},
} {
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
t.Fatalf("CreateWorkspace(%s): %v", workspace.ID, err)
}
}
settingsID := "ws-kanban"
if _, err := harness.userSvc.UpdateUserSettings(ctx, &userservice.UpdateUserSettingsRequest{
WorkspaceID: &settingsID,
}); err != nil {
t.Fatalf("UpdateUserSettings: %v", err)
}
base := time.Date(2026, 7, 3, 12, 0, 0, 0, time.UTC)
seedBootQuickChatTask(t, repo, ctx, bootQuickChatFixture{
id: "chat-kanban", workspaceID: "ws-kanban", title: "Settings Chat",
updatedAt: base, sessionUpdatedAt: base, agentProfileID: "agent-1",
})
seedBootQuickChatTask(t, repo, ctx, bootQuickChatFixture{
id: "chat-office", workspaceID: "ws-o1", title: "Office Chat",
updatedAt: base.Add(time.Minute), sessionUpdatedAt: base.Add(time.Minute), agentProfileID: "agent-2",
})
req := scopedRequest("127.0.0.1:8443",
http.Cookie{Name: "office-active-workspace_8443", Value: "ws-o1"},
)
params := routeParams{taskSvc: harness.taskSvc, userCtrl: harness.userCtrl}
state := bootInitialState(t.Context(), req, params, webapp.RouteClassification{Route: webapp.RouteHome})
raw, err := json.Marshal(state)
if err != nil {
t.Fatalf("Marshal state: %v", err)
}
var decoded struct {
QuickChat struct {
Sessions []struct {
SessionID string `json:"sessionId"`
WorkspaceID string `json:"workspaceId"`
} `json:"sessions"`
} `json:"quickChat"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatalf("Unmarshal state: %v", err)
}
sessions := decoded.QuickChat.Sessions
if len(sessions) != 1 {
t.Fatalf("quickChat sessions = %#v, want exactly the settings workspace's session", sessions)
}
if got := sessions[0].WorkspaceID; got != "ws-kanban" {
t.Fatalf("quickChat session workspaceId = %v, want ws-kanban (settings), not the office cookie's", got)
}
}
// officeWorkspacesPrecedenceHarness builds three office workspaces and a
// kanban workspace with REAL user settings pointing at O2. ListWorkspaces
// orders by created_at DESC, so ws-o3 (created last) is the first office
// fallback — distinct from O1/O2, which the non-first fixtures need.
func officeWorkspacesPrecedenceHarness(t *testing.T) (bootStateBuilder, context.Context) {
t.Helper()
harness := newBootStateTestHarness(t)
ctx := context.Background()
repo := harness.taskRepo
for _, workspace := range []*models.Workspace{
{ID: "ws-o1", Name: "Office 1", OfficeWorkflowID: "wf-1"},
{ID: "ws-o2", Name: "Office 2", OfficeWorkflowID: "wf-2"},
{ID: "ws-o3", Name: "Office 3 (first fallback)", OfficeWorkflowID: "wf-3"},
{ID: "ws-kanban", Name: "Kanban"},
} {
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
t.Fatalf("CreateWorkspace(%s): %v", workspace.ID, err)
}
}
settingsID := "ws-o2"
if _, err := harness.userSvc.UpdateUserSettings(ctx, &userservice.UpdateUserSettingsRequest{
WorkspaceID: &settingsID,
}); err != nil {
t.Fatalf("UpdateUserSettings: %v", err)
}
return bootStateBuilder{p: routeParams{taskSvc: harness.taskSvc, userCtrl: harness.userCtrl}}, ctx
}
// TestOfficeWorkspacesScopedCookiePrecedence drives the office boot
// resolution with SCOPED cookie names: general → office → settings → first.
// Every row is failing-before — the scoped names did not exist pre-change, so
// the reader returned empty and the resolver fell back to the first office
// workspace (never the asserted non-first winner).
func TestOfficeWorkspacesScopedCookiePrecedence(t *testing.T) {
builder, ctx := officeWorkspacesPrecedenceHarness(t)
cases := []struct {
name string
cookies []http.Cookie
want string
}{
{"scoped general kanban + scoped office O2 → O2", []http.Cookie{
{Name: "kandev-active-workspace_8443", Value: "ws-kanban"},
{Name: "office-active-workspace_8443", Value: "ws-o2"},
}, "ws-o2"},
{"scoped general O1 + scoped office O2 → O1", []http.Cookie{
{Name: "kandev-active-workspace_8443", Value: "ws-o1"},
{Name: "office-active-workspace_8443", Value: "ws-o2"},
}, "ws-o1"},
{"scoped office O1 + settings O2 → O1", []http.Cookie{
{Name: "office-active-workspace_8443", Value: "ws-o1"},
}, "ws-o1"},
{"scoped general O1 only → O1", []http.Cookie{
{Name: "kandev-active-workspace_8443", Value: "ws-o1"},
}, "ws-o1"},
{"no cookies → settings O2 (new settings candidate)", nil, "ws-o2"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, activeID, err := builder.officeWorkspaces(ctx, scopedRequest("127.0.0.1:8443", tc.cookies...))
if err != nil {
t.Fatalf("officeWorkspaces: %v", err)
}
if activeID != tc.want {
t.Fatalf("activeID = %q, want %q", activeID, tc.want)
}
})
}
}
// TestOfficeWorkspacesLegacyCookiePrecedence drives the office boot
// resolution with LEGACY (unprefixed) names. The kanban-general row is
// failing-before (pre-change the office cookie was never consulted once the
// general cookie named a kanban workspace); the office-wins rows are
// invariants (office beat general-miss and settings both before and after).
func TestOfficeWorkspacesLegacyCookiePrecedence(t *testing.T) {
builder, ctx := officeWorkspacesPrecedenceHarness(t)
cases := []struct {
name string
cookies []http.Cookie
want string
}{
{"legacy general kanban + legacy office O2 → O2", []http.Cookie{
{Name: "kandev-active-workspace", Value: "ws-kanban"},
{Name: "office-active-workspace", Value: "ws-o2"},
}, "ws-o2"},
{"legacy general O1 + legacy office O2 → O1", []http.Cookie{
{Name: "kandev-active-workspace", Value: "ws-o1"},
{Name: "office-active-workspace", Value: "ws-o2"},
}, "ws-o1"},
{"legacy office O1 + settings O2 → O1", []http.Cookie{
{Name: "office-active-workspace", Value: "ws-o1"},
}, "ws-o1"},
{"legacy general O1 only → O1", []http.Cookie{
{Name: "kandev-active-workspace", Value: "ws-o1"},
}, "ws-o1"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, activeID, err := builder.officeWorkspaces(ctx, scopedRequest("127.0.0.1:8443", tc.cookies...))
if err != nil {
t.Fatalf("officeWorkspaces: %v", err)
}
if activeID != tc.want {
t.Fatalf("activeID = %q, want %q", activeID, tc.want)
}
})
}
}
@@ -2036,9 +2036,25 @@ func TestResolveActiveOfficeWorkspaceIDPrefersCookie(t *testing.T) {
{ID: "ws-b", OfficeWorkflowID: "office-b"},
}
got := resolveActiveOfficeWorkspaceID(workspaces, "ws-b")
if got != "ws-b" {
t.Fatalf("expected cookie workspace to win, got %q", got)
// General cookie wins when it names an office workspace.
if got := resolveActiveOfficeWorkspaceID(workspaces, "ws-b", "ws-a", ""); got != "ws-b" {
t.Fatalf("expected general cookie workspace to win, got %q", got)
}
// Office cookie wins over settings when the general cookie misses.
if got := resolveActiveOfficeWorkspaceID(workspaces, "ws-missing", "ws-a", "ws-b"); got != "ws-a" {
t.Fatalf("expected office cookie workspace to win, got %q", got)
}
// Settings wins when both cookies miss.
if got := resolveActiveOfficeWorkspaceID(workspaces, "", "", "ws-b"); got != "ws-b" {
t.Fatalf("expected settings workspace to win, got %q", got)
}
// A kanban general cookie (not in the office set) falls through.
if got := resolveActiveOfficeWorkspaceID(workspaces, "ws-kanban", "ws-a", "ws-b"); got != "ws-a" {
t.Fatalf("expected kanban general cookie to fall through to the office cookie, got %q", got)
}
// No candidate matches: first office workspace.
if got := resolveActiveOfficeWorkspaceID(workspaces, "", "", ""); got != "ws-a" {
t.Fatalf("expected first office workspace, got %q", got)
}
}
+5 -1
View File
@@ -1974,7 +1974,11 @@ func buildHTTPServer(
// env var to the proxy's IPs/CIDRs; a directly-reachable backend with the
// var set can have X-Forwarded-For spoofed, which also defeats the
// ClientIP-keyed login rate limiter.
configureTrustedProxies(router, log)
// X-Forwarded-Host feeds the port-scoped cookie-name resolver; honor it
// only from the same trusted proxies that may rewrite it (an untrusted
// value is stripped with a warning, so the resolver falls back to Host).
trusted := configureTrustedProxies(router, log)
router.Use(authhttpmw.StripUntrustedForwardedHost(trusted, log))
router.Use(httpmw.RequestLogger(log, kandevName))
router.Use(httpmw.OtelTracing(kandevName))
router.Use(gin.Recovery())
@@ -63,8 +63,10 @@ func resolveTrustedProxies(raw string) (trusted []string, invalid []string) {
// (SetTrustedProxies(nil)); an invalid entry logs a warning naming the bad
// value(s). gin trusts all proxies out of the box, so without this call a
// directly reachable backend would accept a spoofed X-Forwarded-For and
// defeat the ClientIP-keyed login rate limiter.
func configureTrustedProxies(router *gin.Engine, log *logger.Logger) {
// defeat the ClientIP-keyed login rate limiter. It returns the effective
// trusted list (nil when nothing is trusted) so callers can apply the same
// trust decision to other forwarded headers.
func configureTrustedProxies(router *gin.Engine, log *logger.Logger) []string {
trusted, invalid := resolveTrustedProxies(os.Getenv(trustedProxiesEnv))
if len(invalid) > 0 {
log.Warn(trustedProxiesWarningMsg, zap.Strings("invalid_entries", invalid))
@@ -73,4 +75,5 @@ func configureTrustedProxies(router *gin.Engine, log *logger.Logger) {
if err := router.SetTrustedProxies(trusted); err != nil {
log.Warn("failed to configure trusted proxies", zap.Error(err))
}
return trusted
}
+15 -4
View File
@@ -340,8 +340,12 @@ type AuthConfig struct {
// is extended whenever it is used with less than TTL-24h remaining.
SessionTTLHours int `mapstructure:"sessionTTLHours"`
// CookieName is the session cookie name. Only override for unusual
// reverse-proxy setups that need distinct cookie names per instance.
// CookieName is the session cookie base name. Empty (the default) means
// the service uses the "kandev_session" base and port-scopes it from the
// request host, isolating instances on one host (see
// auth.Service.CookieNameForRequest). Only override for unusual
// reverse-proxy setups that need a fixed cookie name; a custom value is
// used verbatim (never port-suffixed) and disables automatic isolation.
CookieName string `mapstructure:"cookieName"`
}
@@ -537,11 +541,15 @@ func setDefaults(v *viper.Viper) {
v.SetDefault("agent.standaloneHost", "localhost")
v.SetDefault("agent.standalonePort", ports.AgentCtl)
// Auth defaults
// Auth defaults. auth.cookieName defaults to empty on purpose: the auth
// service keeps the "kandev_session" base fallback internally and
// port-scopes it from the request host, so an empty default must not be
// seeded with a concrete name or the suffixing would never fire in
// production. A non-empty configured value is used verbatim.
v.SetDefault("auth.jwtSecret", "")
v.SetDefault("auth.tokenDuration", 3600) // 1 hour
v.SetDefault("auth.sessionTTLHours", 720) // 30 days, sliding
v.SetDefault("auth.cookieName", "kandev_session")
v.SetDefault("auth.cookieName", "")
// Office defaults
v.SetDefault("office.jwtSigningKey", "")
@@ -658,6 +666,9 @@ func LoadWithPath(configPath string) (*Config, error) {
_ = v.BindEnv("events.namespace", "KANDEV_EVENTS_NAMESPACE")
_ = v.BindEnv("debug.devMode", "KANDEV_DEBUG_DEV_MODE")
_ = v.BindEnv("debug.pprofEnabled", "KANDEV_DEBUG_PPROF_ENABLED")
// camelCase key, so AutomaticEnv would expose the undocumented
// KANDEV_AUTH_COOKIENAME; the canonical override is KANDEV_AUTH_COOKIE_NAME.
_ = v.BindEnv("auth.cookieName", "KANDEV_AUTH_COOKIE_NAME")
_ = v.BindEnv(
"githubCredentialBroker.publicBaseUrl",
"KANDEV_GITHUB_CREDENTIAL_BROKER_PUBLIC_BASE_URL",
@@ -506,3 +506,71 @@ func TestFeaturesConfig_JSONShape(t *testing.T) {
t.Fatal("retired appStatusBar remains in FeaturesConfig JSON")
}
}
// TestAuthCookieNameDefaultsEmpty pins the config-default contract: the
// seeded default is EMPTY so the auth service port-scopes its internal
// "kandev_session" base from the request host; a seeded non-empty default
// would suppress suffixing in production.
func TestAuthCookieNameDefaultsEmpty(t *testing.T) {
t.Setenv("KANDEV_AUTH_COOKIE_NAME", "")
cfg, err := LoadWithPath(t.TempDir())
if err != nil {
t.Fatalf("LoadWithPath: %v", err)
}
if got := cfg.Auth.CookieName; got != "" {
t.Fatalf("default auth.cookieName = %q, want empty", got)
}
}
// TestAuthCookieNameFromConfigFile pins config.yaml precedence for
// auth.cookieName.
func TestAuthCookieNameFromConfigFile(t *testing.T) {
dir := t.TempDir()
cfgYAML := "auth:\n cookieName: my_session\n"
if err := os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(cfgYAML), 0o600); err != nil {
t.Fatalf("write config.yaml: %v", err)
}
t.Setenv("KANDEV_AUTH_COOKIE_NAME", "")
cfg, err := LoadWithPath(dir)
if err != nil {
t.Fatalf("LoadWithPath: %v", err)
}
if got := cfg.Auth.CookieName; got != "my_session" {
t.Fatalf("auth.cookieName from config = %q, want %q", got, "my_session")
}
}
// TestAuthCookieNameFromEnv pins the canonical environment override
// KANDEV_AUTH_COOKIE_NAME (explicit BindEnv — the automatic camelCase
// mapping would expose the undocumented KANDEV_AUTH_COOKIENAME instead).
func TestAuthCookieNameFromEnv(t *testing.T) {
t.Setenv("KANDEV_AUTH_COOKIE_NAME", "env_session")
cfg, err := LoadWithPath(t.TempDir())
if err != nil {
t.Fatalf("LoadWithPath: %v", err)
}
if got := cfg.Auth.CookieName; got != "env_session" {
t.Fatalf("auth.cookieName from env = %q, want %q", got, "env_session")
}
}
// TestAuthCookieNameEnvOverridesFile pins precedence: environment wins over
// config.yaml for auth.cookieName.
func TestAuthCookieNameEnvOverridesFile(t *testing.T) {
dir := t.TempDir()
cfgYAML := "auth:\n cookieName: file_session\n"
if err := os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(cfgYAML), 0o600); err != nil {
t.Fatalf("write config.yaml: %v", err)
}
t.Setenv("KANDEV_AUTH_COOKIE_NAME", "env_session")
cfg, err := LoadWithPath(dir)
if err != nil {
t.Fatalf("LoadWithPath: %v", err)
}
if got := cfg.Auth.CookieName; got != "env_session" {
t.Fatalf("auth.cookieName = %q, want env override %q", got, "env_session")
}
}
@@ -0,0 +1,78 @@
// Package httpcookie derives port-scoped cookie names from a request host.
//
// Browsers match cookies by host, domain, and path — port is not part of
// cookie scope — so multiple kandev instances on one host (same IP,
// different ports) share one cookie jar. Suffixing cookie names with the
// request's port lets each instance read and write only its own cookies
// (see docs/specs/fix-multi-instance-cookie-isolation/spec.md).
package httpcookie
import (
"net"
"net/http"
"strconv"
"strings"
)
// PortSuffix returns "_<port>" derived from the request host, or "" when no
// usable port is present. X-Forwarded-Host (first value, trimmed) wins over
// Host so a proxy that rewrites only the port can carry the browser's
// host:port. The HTTP boundary (httpmw.StripUntrustedForwardedHost,
// registered in backendapp.buildHTTPServer) removes X-Forwarded-Host from
// untrusted peers, so a value present here is proxy-authored. A suffix
// requires a decimal port in 1..65535: nonnumeric service names and
// out-of-range values yield no suffix. The scheme's default port yields NO
// suffix: 443 for TLS (direct or X-Forwarded-Proto: https) and 80 otherwise.
// This mirrors the SPA's API-origin derivation, where URL.port reports "" for
// the scheme-default port only — so http://host:443 stays "_443" on both
// sides instead of splitting one instance's cookies across two names. A nil
// request yields "".
func PortSuffix(r *http.Request) string {
if r == nil {
return ""
}
host := r.Host
if xfh := r.Header.Get("X-Forwarded-Host"); xfh != "" {
host = firstValue(xfh)
}
_, port, err := net.SplitHostPort(host)
if err != nil {
return ""
}
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 {
return ""
}
if n == defaultPortForRequest(r) {
return ""
}
return "_" + port
}
// defaultPortForRequest returns the scheme's default port: 443 when the
// request arrived over TLS (directly or via X-Forwarded-Proto), 80 otherwise.
// Mirrors the Secure-cookie flag logic (requestIsTLS) so the two scheme
// decisions cannot diverge.
func defaultPortForRequest(r *http.Request) int {
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
return 443
}
return 80
}
// ScopedName returns base suffixed with the request's port suffix, or "" when
// base is empty (a suffix is meaningless without a base name).
func ScopedName(r *http.Request, base string) string {
if base == "" {
return ""
}
return base + PortSuffix(r)
}
// firstValue returns the first comma-separated value, trimmed.
func firstValue(v string) string {
if i := strings.IndexByte(v, ','); i >= 0 {
return strings.TrimSpace(v[:i])
}
return strings.TrimSpace(v)
}
@@ -0,0 +1,87 @@
package httpcookie
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
func req(host, xfh string) *http.Request {
r := httptest.NewRequest("GET", "/", nil)
r.Host = host
if xfh != "" {
r.Header.Set("X-Forwarded-Host", xfh)
}
return r
}
// tlsReq builds a request over TLS (direct), like req but with r.TLS set.
func tlsReq(host, xfh string) *http.Request {
r := req(host, xfh)
r.TLS = &tls.ConnectionState{}
return r
}
// xfpReq builds a request marked https via X-Forwarded-Proto (proxied TLS).
func xfpReq(host, xfh string) *http.Request {
r := req(host, xfh)
r.Header.Set("X-Forwarded-Proto", "https")
return r
}
func TestPortSuffix(t *testing.T) {
tests := []struct {
name string
req *http.Request
want string
}{
{"ported host", req("127.0.0.1:8443", ""), "_8443"},
{"no port", req("example.com", ""), ""},
{"default port 80 http", req("example.com:80", ""), ""},
{"default port 443 https", tlsReq("example.com:443", ""), ""},
{"default port 443 https via xfp", xfpReq("example.com:443", ""), ""},
{"non-default 443 on http", req("example.com:443", ""), "_443"},
{"non-default 80 on https", tlsReq("example.com:80", ""), "_80"},
{"XFH wins over host", req("internal:38429", "public.example:8443"), "_8443"},
{"XFH wins on conflicting ports", req("public.example:8443", "public.example:9443"), "_9443"},
{"XFH comma separated first", req("internal:38429", "public.example:8443, other:9443"), "_8443"},
{"XFH whitespace padded", req("internal:38429", " public.example:8443 , other:9443"), "_8443"},
{"XFH whitespace only", req("internal:38429", " "), ""},
{"XFH no port", req("internal:38429", "public.example"), ""},
{"XFH scheme-aware default", tlsReq("internal:38429", "public.example:443"), ""},
{"IPv6 bracket", req("[::1]:8080", ""), "_8080"},
{"IPv6 zone", req("[fe80::1%25eth0]:8080", ""), "_8080"},
{"service name port", req("example.com:http", ""), ""},
{"out of range port", req("example.com:99999", ""), ""},
{"zero port", req("example.com:0", ""), ""},
{"negative port", req("example.com:-1", ""), ""},
{"malformed host", req("example.com:abc:def", ""), ""},
{"unbracketed ipv6", req("::1", ""), ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := PortSuffix(tt.req); got != tt.want {
t.Fatalf("PortSuffix(%q) = %q, want %q", tt.req.Host, got, tt.want)
}
})
}
}
func TestPortSuffixNilRequest(t *testing.T) {
if got := PortSuffix(nil); got != "" {
t.Fatalf("PortSuffix(nil) = %q, want empty", got)
}
}
func TestScopedName(t *testing.T) {
if got := ScopedName(req("127.0.0.1:8443", ""), "kandev_session"); got != "kandev_session_8443" {
t.Fatalf("ScopedName ported = %q, want kandev_session_8443", got)
}
if got := ScopedName(req("example.com", ""), "kandev_session"); got != "kandev_session" {
t.Fatalf("ScopedName no-port = %q, want kandev_session", got)
}
if got := ScopedName(req("127.0.0.1:8443", ""), ""); got != "" {
t.Fatalf("ScopedName empty base = %q, want empty", got)
}
}
@@ -183,8 +183,10 @@ type proxyAuthGatewayResponse struct {
// proxyAuthGateway issues requests against the full production chain: CORS,
// auth middleware, gateway routes (requireConnectionAuth + port proxy), a
// token-enforcing fake agentctl, and the fake app.
func proxyAuthGateway(t *testing.T, handler http.Handler) func(method, path string, headers map[string]string) proxyAuthGatewayResponse {
// token-enforcing fake agentctl, and the fake app. It returns the request
// closure plus the fixture server URL so callers can derive the port-scoped
// session cookie name for its Host.
func proxyAuthGateway(t *testing.T, handler http.Handler) (func(method, path string, headers map[string]string) proxyAuthGatewayResponse, string) {
t.Helper()
srv := httptest.NewUnstartedServer(handler)
srv.Config.SetKeepAlivesEnabled(false)
@@ -219,7 +221,23 @@ func proxyAuthGateway(t *testing.T, handler http.Handler) func(method, path stri
t.Fatalf("read body for %s: %v", path, err)
}
return proxyAuthGatewayResponse{status: resp.StatusCode, body: string(body), headers: resp.Header}
}, srv.URL
}
// scopedSessionCookieHeader builds the Cookie header for the gateway fixture's
// Host (127.0.0.1:<random port>): the session cookie must carry the
// port-scoped name the auth middleware derives from that request Host.
func scopedSessionCookieHeader(t *testing.T, srvURL, sessionToken string) map[string]string {
t.Helper()
u, err := url.Parse(srvURL)
if err != nil {
t.Fatalf("parse server URL: %v", err)
}
port := u.Port()
if port == "" {
t.Fatal("fixture server URL has no port")
}
return map[string]string{"Cookie": "kandev_session_" + port + "=" + sessionToken}
}
var manifestLinkPattern = regexp.MustCompile(`href="([^"]*manifest\.webmanifest[^"]*)"`)
@@ -274,8 +292,8 @@ func TestPortProxyServesCredentiallessSubresourcesAfterDocumentAuth(t *testing.T
gateway.SetPortProxy(manager)
gateway.SetupRoutes(router)
request := proxyAuthGateway(t, router)
cookieHeader := map[string]string{"Cookie": svc.CookieName() + "=" + sessionToken}
request, srvURL := proxyAuthGateway(t, router)
cookieHeader := scopedSessionCookieHeader(t, srvURL, sessionToken)
// 1. The document request authenticates with the session cookie.
doc := request(http.MethodGet, "/port-proxy/sess-auth/5173/", cookieHeader)
@@ -552,9 +570,9 @@ func TestPortProxyDecompressesAndRewritesCompressedHTML(t *testing.T) {
gateway.SetPortProxy(manager)
gateway.SetupRoutes(router)
request := proxyAuthGateway(t, router)
request, srvURL := proxyAuthGateway(t, router)
headers := map[string]string{
"Cookie": svc.CookieName() + "=" + sessionToken,
"Cookie": scopedSessionCookieHeader(t, srvURL, sessionToken)["Cookie"],
"Accept-Encoding": "gzip",
}
doc := request(http.MethodGet, "/port-proxy/sess-gz/5173/", headers)
@@ -616,8 +634,8 @@ func TestPortProxyRewritesNestedCSSWithPublicBase(t *testing.T) {
gateway.SetPortProxy(manager)
gateway.SetupRoutes(router)
request := proxyAuthGateway(t, router)
headers := map[string]string{"Cookie": svc.CookieName() + "=" + sessionToken}
request, srvURL := proxyAuthGateway(t, router)
headers := map[string]string{"Cookie": scopedSessionCookieHeader(t, srvURL, sessionToken)["Cookie"]}
doc := request(http.MethodGet, "/port-proxy/sess-css/5173/css/main.css", headers)
if doc.status != http.StatusOK {
t.Fatalf("css status = %d, want %d (body=%s)", doc.status, http.StatusOK, doc.body)
+6 -5
View File
@@ -28,11 +28,12 @@ type externalLoginAssertion struct {
// AuthLoginBridge establishes an authenticated kandev browser session for an
// external identity that an auth-capable plugin has validated against an
// external IdP (OIDC/SAML SSO). The host mints and sets the kandev_session
// cookie on the response; the plugin never receives the raw session token —
// its only channel is the reserved login directive header on its webhook
// response (see handlers.go). Implemented in internal/backendapp over
// internal/auth so this package need not depend on the auth service.
// external IdP (OIDC/SAML SSO). The host mints and sets the session cookie
// (name derived from the request host) on the response; the plugin never
// receives the raw session token — its only channel is the reserved login
// directive header on its webhook response (see handlers.go). Implemented in
// internal/backendapp over internal/auth so this package need not depend on
// the auth service.
type AuthLoginBridge interface {
// LoginExternal maps the asserted external identity to a kandev user
// (linking or just-in-time provisioning as needed) and sets the session
-18
View File
@@ -1,18 +0,0 @@
import { listAgentProfiles } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../lib/get-active-workspace";
import { AgentsPageClient } from "./agents-page-client";
import type { AgentProfile } from "@/lib/state/slices/office/types";
export default async function AgentsPage() {
const workspaceId = await getActiveWorkspaceId();
let agents: AgentProfile[] = [];
if (workspaceId) {
const res = await listAgentProfiles(workspaceId, { cache: "no-store" }).catch(() => ({
agents: [],
}));
agents = res.agents ?? [];
}
return <AgentsPageClient initialAgents={agents} initialWorkspaceId={workspaceId} />;
}
@@ -94,9 +94,9 @@ function OfficePageNav({ onClose }: { onClose: () => void }) {
/**
* Office page chrome on the shared `PageShell`. List pages show a static
* title; detail pages render a portal target (#office-topbar-slot) that the
* page component fills with its breadcrumb via OfficeTopbarPortal. Both paint
* paths (`src/office-routes.tsx` and `app/office/layout.tsx`) wrap their route
* output in this shell so they cannot drift.
* page component fills with its breadcrumb via OfficeTopbarPortal. The SPA
* office paint path (`src/office-routes.tsx`) wraps every route's output in
* this shell so the chrome cannot drift.
*/
export function OfficeShell({
children,
@@ -147,9 +147,9 @@ export function OfficeShell({
the specific route, so a mis-pointed URL cannot match another
screen's anchor.
The shell owns this outlet (`scroll="none"`) so both paint paths —
`src/office-routes.tsx` and `app/office/layout.tsx` — carry the
anchor without either one re-declaring it. */}
The shell owns this outlet (`scroll="none"`) so the single SPA paint
path (`src/office-routes.tsx`) carries the anchor without
re-declaring it. */}
<main className="flex-1 min-h-0 overflow-y-auto" data-office-route={routePath ?? pathname}>
{children}
</main>
-25
View File
@@ -1,25 +0,0 @@
import { getInbox } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../lib/get-active-workspace";
import { InboxPageClient } from "./inbox-page-client";
import type { InboxItem } from "@/lib/state/slices/office/types";
export default async function InboxPage() {
const workspaceId = await getActiveWorkspaceId();
let items: InboxItem[] = [];
let count = 0;
if (workspaceId) {
// Single round-trip: getInbox returns items + total_count
// (Stream F of office optimization). Was 2 parallel calls.
const res = await getInbox(workspaceId, { cache: "no-store" }).catch(() => ({
items: [] as InboxItem[],
total_count: 0,
}));
items = res.items ?? [];
count = res.total_count ?? items.length;
}
return (
<InboxPageClient initialItems={items} initialCount={count} initialWorkspaceId={workspaceId} />
);
}
-211
View File
@@ -1,211 +0,0 @@
import { notFound } from "@/lib/routing/server-navigation";
import { TooltipProvider } from "@kandev/ui/tooltip";
import { StateHydrator } from "@/components/state-hydrator";
import { getFeatureFlagsAction } from "@/app/actions/features";
import { listWorkspaces, fetchUserSettings } from "@/lib/api";
import {
getInbox,
getMeta,
getOnboardingState,
listAgentProfiles,
listProjects,
} from "@/lib/api/domains/office-api";
import { mapUserSettingsResponse } from "@/lib/ssr/user-settings";
import { readCookies } from "@/lib/server/cookies";
import type { AppState } from "@/lib/state/store";
import { OfficeShell } from "./components/office-shell";
function resolveActiveOfficeWorkspaceId(
workspaceItems: { id: string }[],
cookieWorkspaceId: string | null,
settingsWorkspaceId: string | null,
): string | null {
return (
workspaceItems.find((w) => w.id === cookieWorkspaceId)?.id ??
workspaceItems.find((w) => w.id === settingsWorkspaceId)?.id ??
workspaceItems[0]?.id ??
null
);
}
function mapWorkspaceItem(ws: {
id: string;
name: string;
description?: string | null;
owner_id: string;
default_executor_id?: string | null;
default_environment_id?: string | null;
default_agent_profile_id?: string | null;
default_config_agent_profile_id?: string | null;
office_workflow_id?: string | null;
created_at: string;
updated_at: string;
}) {
return {
id: ws.id,
name: ws.name,
description: ws.description ?? null,
owner_id: ws.owner_id,
default_executor_id: ws.default_executor_id ?? null,
default_environment_id: ws.default_environment_id ?? null,
default_agent_profile_id: ws.default_agent_profile_id ?? null,
default_config_agent_profile_id: ws.default_config_agent_profile_id ?? null,
office_workflow_id: ws.office_workflow_id ?? null,
created_at: ws.created_at,
updated_at: ws.updated_at,
};
}
/**
* Wraps a workspace-scoped value in the `Record<workspaceId, T>` shape the
* office slice stores. No active workspace means no entry at all, rather than
* data filed under an empty-string key that nothing would ever read.
*/
function keyByWorkspace<T>(workspaceId: string | null, value: T): Record<string, T> {
return workspaceId ? { [workspaceId]: value } : {};
}
/**
* The office slice as this layout hydrates it: the four workspace-scoped
* collections filed under the workspace they were fetched for, and every other
* field at its default. `meta` is supplied by the caller.
*/
function officeHydrationState({
activeWorkspaceId,
agents,
projects,
inboxItems,
inboxCount,
}: {
activeWorkspaceId: string | null;
agents: AppState["office"]["agentProfilesByWorkspaceId"][string];
projects: AppState["office"]["projectsByWorkspaceId"][string];
inboxItems: AppState["office"]["inboxItemsByWorkspaceId"][string];
inboxCount: number;
}): Omit<AppState["office"], "meta"> {
return {
agentProfilesByWorkspaceId: keyByWorkspace(activeWorkspaceId, agents),
skills: [],
projectsByWorkspaceId: keyByWorkspace(activeWorkspaceId, projects),
approvals: [],
activity: [],
costSummary: null,
budgetPolicies: [],
routines: [],
inboxItemsByWorkspaceId: keyByWorkspace(activeWorkspaceId, inboxItems),
inboxCountByWorkspaceId: keyByWorkspace(activeWorkspaceId, inboxCount),
runs: [],
dashboardByWorkspaceId: {},
tasks: {
items: [],
filters: { statuses: [], priorities: [], assigneeIds: [], projectIds: [], search: "" },
viewMode: "list",
sortField: "updated",
sortDir: "desc",
groupBy: "none",
nestingEnabled: true,
isLoading: false,
},
isLoading: false,
refetchTrigger: null,
routing: { byWorkspace: {}, knownProviders: [], preview: { byWorkspace: {} } },
providerHealth: { byWorkspace: {} },
runAttempts: { byRunId: {} },
agentRouting: { byAgentId: {} },
};
}
export default async function OfficeLayout({ children }: { children: React.ReactNode }) {
// Feature gate: production releases ship with features.office=false and
// the backend's /api/v1/office/* routes are not registered. Return 404
// for every Office page so even a guessed URL looks like a non-existent
// route, not "you don't have permission".
// See docs/decisions/0007-runtime-feature-flags.md.
const { office: officeEnabled } = await getFeatureFlagsAction();
if (!officeEnabled) {
notFound();
}
// Check onboarding before rendering the office chrome. When not complete,
// render only the children (the setup wizard) without the workspace rail,
// sidebar, or topbar — prevents a flash of stale workspace UI.
const onboarding = await getOnboardingState({ cache: "no-store" }).catch(() => ({
completed: false,
fsWorkspaces: [],
}));
if (!onboarding.completed) {
return <>{children}</>;
}
const [workspacesResponse, userSettingsResponse, metaResponse, cookieStore] = await Promise.all([
listWorkspaces({ cache: "no-store" }).catch(() => ({ workspaces: [] })),
fetchUserSettings({ cache: "no-store" }).catch(() => null),
getMeta({ cache: "no-store" }).catch(() => null),
readCookies().catch(() => null),
]);
// Only office workspaces can be active inside /office, but hydrate every
// workspace into the shared sidebar picker so users can switch back to Kanban.
const officeWorkspaceItems = workspacesResponse.workspaces
.filter((ws) => ws.office_workflow_id)
.map(mapWorkspaceItem);
const workspaceItems = workspacesResponse.workspaces.map(mapWorkspaceItem);
const settingsWorkspaceId = userSettingsResponse?.settings?.workspace_id || null;
// office-active-workspace cookie is set by the setup wizard and workspace rail so the
// layout can load the correct workspace even when userSettings.workspace_id still points
// to a kanban workspace (we never write to userSettings from office).
const cookieWorkspaceId = cookieStore?.get("office-active-workspace")?.value ?? null;
const activeWorkspaceId = resolveActiveOfficeWorkspaceId(
officeWorkspaceItems,
cookieWorkspaceId,
settingsWorkspaceId,
);
// Fetch agents + projects + inbox for the active workspace so the
// sidebar renders them — including the inbox count badge — on first
// paint without a client refetch.
const [agentsResponse, projectsResponse, inboxResponse] = activeWorkspaceId
? await Promise.all([
listAgentProfiles(activeWorkspaceId, { cache: "no-store" }).catch(() => ({
agents: [],
})),
listProjects(activeWorkspaceId, { cache: "no-store" }).catch(() => ({
projects: [],
})),
getInbox(activeWorkspaceId, { cache: "no-store" }).catch(() => ({
items: [],
total_count: 0,
})),
])
: [{ agents: [] }, { projects: [] }, { items: [], total_count: 0 }];
const initialState: Partial<AppState> = {
workspaces: {
items: workspaceItems,
activeId: activeWorkspaceId,
},
userSettings: {
...mapUserSettingsResponse(userSettingsResponse),
workspaceId: activeWorkspaceId,
},
office: {
...officeHydrationState({
activeWorkspaceId,
agents: agentsResponse.agents as AppState["office"]["agentProfilesByWorkspaceId"][string],
projects: projectsResponse.projects as AppState["office"]["projectsByWorkspaceId"][string],
inboxItems: inboxResponse.items as AppState["office"]["inboxItemsByWorkspaceId"][string],
inboxCount: inboxResponse.total_count,
}),
meta: metaResponse,
},
};
return (
<TooltipProvider>
<StateHydrator initialState={initialState} />
<div className="flex h-full min-h-0 flex-col">
<OfficeShell>{children}</OfficeShell>
</div>
</TooltipProvider>
);
}
@@ -1,141 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
vi.mock("@/lib/server/cookies", () => ({
readCookies: vi.fn(),
}));
vi.mock("@/lib/api", () => ({
listWorkspaces: vi.fn(),
fetchUserSettings: vi.fn(),
}));
vi.mock("@/lib/api/domains/settings-api", () => ({
updateUserSettings: vi.fn(),
}));
import { readCookies } from "@/lib/server/cookies";
import { listWorkspaces, fetchUserSettings } from "@/lib/api";
import { updateUserSettings } from "@/lib/api/domains/settings-api";
import { getActiveWorkspaceId } from "./get-active-workspace";
const mockReadCookies = vi.mocked(readCookies);
const mockListWorkspaces = vi.mocked(listWorkspaces);
const mockFetchUserSettings = vi.mocked(fetchUserSettings);
const mockUpdateUserSettings = vi.mocked(updateUserSettings);
const OFFICE_WS_ID = "ws-office-1";
const OFFICE_WS_ID_2 = "ws-office-2";
const KANBAN_WS_ID = "ws-kanban-1";
const OFFICE_WS = { id: OFFICE_WS_ID, name: "Office", office_workflow_id: "wf-1" };
const OFFICE_WS_2 = { id: OFFICE_WS_ID_2, name: "Office 2", office_workflow_id: "wf-2" };
const KANBAN_WS = { id: KANBAN_WS_ID, name: "Kanban" }; // no office_workflow_id
function makeSettings(workspaceId: string) {
return { settings: { workspace_id: workspaceId } };
}
function makeCookieStore(workspaceId: string | null) {
return {
get: (name: string) =>
name === "office-active-workspace" && workspaceId ? { value: workspaceId } : undefined,
};
}
beforeEach(() => {
mockReadCookies.mockReset();
mockListWorkspaces.mockReset();
mockFetchUserSettings.mockReset();
mockUpdateUserSettings.mockReset();
mockUpdateUserSettings.mockResolvedValue({} as never);
// Default: no cookie set
mockReadCookies.mockResolvedValue(makeCookieStore(null) as never);
});
afterEach(() => {
vi.clearAllMocks();
});
describe("getActiveWorkspaceId", () => {
describe("URL workspaceId arg wins when it matches an office workspace", () => {
it("returns the URL workspace id and does NOT call updateUserSettings", async () => {
mockListWorkspaces.mockResolvedValue({ workspaces: [OFFICE_WS] } as never);
mockFetchUserSettings.mockResolvedValue(makeSettings("ws-other-1") as never);
const result = await getActiveWorkspaceId(OFFICE_WS_ID);
expect(result).toBe(OFFICE_WS_ID);
expect(mockUpdateUserSettings).not.toHaveBeenCalled();
});
it("ignores the URL param when it does not match any office workspace", async () => {
mockListWorkspaces.mockResolvedValue({ workspaces: [OFFICE_WS] } as never);
mockFetchUserSettings.mockResolvedValue(makeSettings(OFFICE_WS_ID) as never);
// "ws-unknown" not in office list - falls back to settings match
const result = await getActiveWorkspaceId("ws-unknown-1");
expect(result).toBe(OFFICE_WS_ID);
expect(mockUpdateUserSettings).not.toHaveBeenCalled();
});
});
describe("cookie wins after URL param misses", () => {
it("returns the cookie workspace and does NOT call updateUserSettings", async () => {
mockReadCookies.mockResolvedValue(makeCookieStore(OFFICE_WS_ID_2) as never);
mockListWorkspaces.mockResolvedValue({ workspaces: [OFFICE_WS, OFFICE_WS_2] } as never);
mockFetchUserSettings.mockResolvedValue(makeSettings(KANBAN_WS_ID) as never);
const result = await getActiveWorkspaceId();
expect(result).toBe(OFFICE_WS_ID_2);
expect(mockUpdateUserSettings).not.toHaveBeenCalled();
});
it("ignores cookie when it does not match any office workspace", async () => {
mockReadCookies.mockResolvedValue(makeCookieStore("ws-stale") as never);
mockListWorkspaces.mockResolvedValue({ workspaces: [OFFICE_WS] } as never);
mockFetchUserSettings.mockResolvedValue(makeSettings(OFFICE_WS_ID) as never);
const result = await getActiveWorkspaceId();
expect(result).toBe(OFFICE_WS_ID);
expect(mockUpdateUserSettings).not.toHaveBeenCalled();
});
});
describe("regression: kanban workspace in settings must not trigger updateUserSettings", () => {
it("falls back to first office workspace and does NOT call updateUserSettings", async () => {
mockListWorkspaces.mockResolvedValue({ workspaces: [KANBAN_WS, OFFICE_WS] } as never);
mockFetchUserSettings.mockResolvedValue(makeSettings(KANBAN_WS_ID) as never);
const result = await getActiveWorkspaceId();
expect(result).toBe(OFFICE_WS_ID);
expect(mockUpdateUserSettings).not.toHaveBeenCalled();
});
});
describe("settings.workspace_id points to a valid office workspace", () => {
it("returns the settings workspace id and does NOT call updateUserSettings", async () => {
mockListWorkspaces.mockResolvedValue({ workspaces: [OFFICE_WS] } as never);
mockFetchUserSettings.mockResolvedValue(makeSettings(OFFICE_WS_ID) as never);
const result = await getActiveWorkspaceId();
expect(result).toBe(OFFICE_WS_ID);
expect(mockUpdateUserSettings).not.toHaveBeenCalled();
});
});
describe("no office workspaces exist", () => {
it("returns null and does not call updateUserSettings", async () => {
mockListWorkspaces.mockResolvedValue({ workspaces: [] } as never);
mockFetchUserSettings.mockResolvedValue(makeSettings(OFFICE_WS_ID) as never);
const result = await getActiveWorkspaceId();
expect(result).toBeNull();
expect(mockUpdateUserSettings).not.toHaveBeenCalled();
});
});
});
@@ -1,52 +0,0 @@
import { listWorkspaces, fetchUserSettings } from "@/lib/api";
import { readCookies } from "@/lib/server/cookies";
/**
* Server-side helper to resolve the active workspace ID.
* Re-fetches workspaces and user settings (Next.js will deduplicate
* these calls within the same request when the layout also fetches them).
*
* Priority order:
* 1. urlWorkspaceId when it matches a valid office workspace.
* 2. office-active-workspace cookie when it matches a valid office workspace.
* 3. userSettings.workspace_id when it matches a valid office workspace.
* 4. First available office workspace as fallback.
*
* Does NOT write to user settings - the caller must not pollute the shared
* workspace_id that kanban uses.
*/
export async function getActiveWorkspaceId(urlWorkspaceId?: string): Promise<string | null> {
const [workspacesRes, settingsRes, cookieStore] = await Promise.all([
listWorkspaces({ cache: "no-store" }).catch(() => ({ workspaces: [] })),
fetchUserSettings({ cache: "no-store" }).catch(() => null),
readCookies().catch(() => null),
]);
// Only consider office workspaces (those with office_workflow_id set).
const workspaces = workspacesRes.workspaces.filter((w) => w.office_workflow_id);
// 1. URL param wins when it matches a valid office workspace.
if (urlWorkspaceId) {
const urlMatch = workspaces.find((w) => w.id === urlWorkspaceId);
if (urlMatch) return urlMatch.id;
}
// 2. Cookie set by the setup wizard and workspace rail - keeps page and
// layout in sync since layouts cannot read URL search params.
const cookieWorkspaceId = cookieStore?.get("office-active-workspace")?.value;
if (cookieWorkspaceId) {
const cookieMatch = workspaces.find((w) => w.id === cookieWorkspaceId);
if (cookieMatch) return cookieMatch.id;
}
// 3. Check if the settings workspace_id points to a valid office workspace.
const settingsWorkspaceId = settingsRes?.settings?.workspace_id || null;
const matched = workspaces.find((w) => w.id === settingsWorkspaceId);
if (matched) {
return matched.id;
}
// 4. Fall back to the first available office workspace.
// Do NOT persist this - userSettings.workspace_id belongs to kanban.
return workspaces[0]?.id ?? null;
}
-51
View File
@@ -1,51 +0,0 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
redirect: vi.fn((path: string) => {
throw new Error(`redirect:${path}`);
}),
getOnboardingState: vi.fn(),
getDashboard: vi.fn(),
getActiveWorkspaceId: vi.fn(),
}));
vi.mock("@/lib/routing/server-navigation", () => ({
redirect: mocks.redirect,
}));
vi.mock("@/lib/api/domains/office-api", () => ({
getOnboardingState: mocks.getOnboardingState,
getDashboard: mocks.getDashboard,
}));
vi.mock("./lib/get-active-workspace", () => ({
getActiveWorkspaceId: mocks.getActiveWorkspaceId,
}));
vi.mock("./page-client", () => ({
OfficePageClient: ({ initialDashboard }: { initialDashboard: unknown }) => (
<div data-testid="office-page-client">{JSON.stringify(initialDashboard)}</div>
),
}));
import OfficePage from "./page";
describe("OfficePage", () => {
beforeEach(() => {
mocks.redirect.mockClear();
mocks.getOnboardingState.mockReset();
mocks.getDashboard.mockReset();
mocks.getActiveWorkspaceId.mockReset();
});
it("redirects to setup-new when no office workspace exists", async () => {
mocks.getOnboardingState.mockResolvedValue({ completed: true });
mocks.getActiveWorkspaceId.mockResolvedValue(null);
await expect(OfficePage({ searchParams: Promise.resolve({}) })).rejects.toThrow(
"redirect:/office/setup?mode=new",
);
expect(mocks.redirect).toHaveBeenCalledWith("/office/setup?mode=new");
expect(mocks.getDashboard).not.toHaveBeenCalled();
});
});
-25
View File
@@ -1,25 +0,0 @@
import { redirect } from "@/lib/routing/server-navigation";
import { getDashboard, getOnboardingState } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "./lib/get-active-workspace";
import { OfficePageClient } from "./page-client";
type SearchParams = Promise<{ workspaceId?: string }>;
export default async function OfficePage({ searchParams }: { searchParams?: SearchParams }) {
const onboarding = await getOnboardingState({ cache: "no-store" }).catch(() => ({
completed: true,
}));
if (!onboarding.completed) {
redirect("/office/setup");
}
const params = searchParams ? await searchParams : {};
const workspaceId = await getActiveWorkspaceId(params.workspaceId);
if (!workspaceId) {
redirect("/office/setup?mode=new");
}
const dashboard = await getDashboard(workspaceId, { cache: "no-store" }).catch(() => null);
return <OfficePageClient initialDashboard={dashboard} initialWorkspaceId={workspaceId} />;
}
-18
View File
@@ -1,18 +0,0 @@
import { listProjects } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../lib/get-active-workspace";
import { ProjectsPageClient } from "./projects-page-client";
import type { Project } from "@/lib/state/slices/office/types";
export default async function ProjectsPage() {
const workspaceId = await getActiveWorkspaceId();
let projects: Project[] = [];
if (workspaceId) {
const res = await listProjects(workspaceId, { cache: "no-store" }).catch(() => ({
projects: [],
}));
projects = res.projects ?? [];
}
return <ProjectsPageClient initialProjects={projects} initialWorkspaceId={workspaceId} />;
}
-18
View File
@@ -1,18 +0,0 @@
import { listRoutines } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../lib/get-active-workspace";
import { RoutinesPageClient } from "./routines-page-client";
import type { Routine } from "@/lib/state/slices/office/types";
export default async function RoutinesPage() {
const workspaceId = await getActiveWorkspaceId();
let routines: Routine[] = [];
if (workspaceId) {
const res = await listRoutines(workspaceId, { cache: "no-store" }).catch(() => ({
routines: [],
}));
routines = res.routines ?? [];
}
return <RoutinesPageClient initialRoutines={routines} />;
}
-18
View File
@@ -1,18 +0,0 @@
import { listTasks } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../lib/get-active-workspace";
import { TasksPageClient } from "./tasks-page-client";
import type { OfficeTask } from "@/lib/state/slices/office/types";
export default async function TasksPage() {
const workspaceId = await getActiveWorkspaceId();
let tasks: OfficeTask[] = [];
if (workspaceId) {
const res = await listTasks(workspaceId, { cache: "no-store" }).catch(() => ({
tasks: [],
}));
tasks = res.tasks ?? [];
}
return <TasksPageClient initialIssues={tasks} />;
}
@@ -1,18 +0,0 @@
import { listActivity } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../../lib/get-active-workspace";
import { ActivityPageClient } from "./activity-page-client";
import type { ActivityEntry } from "@/lib/state/slices/office/types";
export default async function ActivityPage() {
const workspaceId = await getActiveWorkspaceId();
let activity: ActivityEntry[] = [];
if (workspaceId) {
const res = await listActivity(workspaceId, undefined, { cache: "no-store" }).catch(() => ({
activity: [],
}));
activity = res.activity ?? [];
}
return <ActivityPageClient initialActivity={activity} />;
}
@@ -1,15 +0,0 @@
import { getCosts } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../../lib/get-active-workspace";
import { CostsPageClient } from "./costs-page-client";
import type { CostSummary } from "@/lib/state/slices/office/types";
export default async function CostsPage() {
const workspaceId = await getActiveWorkspaceId();
let costSummary: CostSummary | null = null;
if (workspaceId) {
costSummary = await getCosts(workspaceId, { cache: "no-store" }).catch(() => null);
}
return <CostsPageClient initialCostSummary={costSummary} />;
}
@@ -1,18 +0,0 @@
import { listSkills } from "@/lib/api/domains/office-api";
import { getActiveWorkspaceId } from "../../lib/get-active-workspace";
import { SkillsPageClient } from "./skills-page-client";
import type { Skill } from "@/lib/state/slices/office/types";
export default async function SkillsPage() {
const workspaceId = await getActiveWorkspaceId();
let skills: Skill[] = [];
if (workspaceId) {
const res = await listSkills(workspaceId, { cache: "no-store" }).catch(() => ({
skills: [],
}));
skills = res.skills ?? [];
}
return <SkillsPageClient initialSkills={skills} />;
}
-42
View File
@@ -1,42 +0,0 @@
import { describe, expect, it } from "vitest";
import { workspaceId, workflowId } from "@/lib/types/ids";
import type { ListWorkspacesResponse } from "@/lib/types/http";
import { resolveActiveKanbanWorkspaceId } from "./page";
type WorkspaceRow = ListWorkspacesResponse["workspaces"][number];
describe("resolveActiveKanbanWorkspaceId", () => {
it("ignores office workspaces when resolving cookie and settings IDs", () => {
const activeId = resolveActiveKanbanWorkspaceId(
[workspaceRow("ws-office", "office-flow"), workspaceRow("ws-kanban", null)],
undefined,
"ws-office",
"ws-kanban",
);
expect(activeId).toBe("ws-kanban");
});
it("falls back when explicit URL workspace ID is an office workspace", () => {
const activeId = resolveActiveKanbanWorkspaceId(
[workspaceRow("ws-office", "office-flow"), workspaceRow("ws-kanban", null)],
"ws-office",
null,
"ws-kanban",
);
expect(activeId).toBe("ws-kanban");
});
});
function workspaceRow(id: string, officeWorkflowId: string | null): WorkspaceRow {
return {
id: workspaceId(id),
name: id,
owner_id: "owner-1",
office_workflow_id: officeWorkflowId ? workflowId(officeWorkflowId) : undefined,
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
} as WorkspaceRow;
}
-277
View File
@@ -1,277 +0,0 @@
import { PageClient } from "@/app/page-client";
import { StateHydrator } from "@/components/state-hydrator";
import {
fetchWorkflowSnapshot,
fetchUserSettings,
listWorkflows,
listRepositories,
listWorkspaces,
listTaskSessionMessages,
listQuickChatSessions,
listQuickTerminalTabs,
} from "@/lib/api";
import { listWorkspaceTaskPRs } from "@/lib/api/domains/github-api";
import { toQuickChatSessions } from "@/lib/quick-chat/map-sessions";
import { toQuickTerminalTab } from "@/lib/api/domains/quick-terminal-api";
import { snapshotToState } from "@/lib/ssr/mapper";
import { mapUserSettingsResponse } from "@/lib/ssr/user-settings";
import { resolveDesiredWorkflowId } from "@/lib/kanban/resolve-workflow";
import { ACTIVE_WORKSPACE_COOKIE } from "@/lib/routing/route-bootstrap";
import { resolveActiveId } from "@/lib/ssr/resolve-active-id";
import { readCookies } from "@/lib/server/cookies";
import type { AppState } from "@/lib/state/store";
import type { ListWorkspacesResponse, UserSettingsResponse } from "@/lib/types/http";
// Root page loader: keeps the old route shape while SPA boot data owns hydration.
type PageProps = {
searchParams?: Promise<Record<string, string | string[] | undefined>>;
};
function resolveParam(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
type WorkspaceItem = ListWorkspacesResponse["workspaces"][number];
function mapWorkspaceItem(ws: WorkspaceItem) {
return {
id: ws.id,
name: ws.name,
description: ws.description ?? null,
owner_id: ws.owner_id,
default_executor_id: ws.default_executor_id ?? null,
default_environment_id: ws.default_environment_id ?? null,
default_agent_profile_id: ws.default_agent_profile_id ?? null,
default_config_agent_profile_id: ws.default_config_agent_profile_id ?? null,
office_workflow_id: ws.office_workflow_id ?? null,
created_at: ws.created_at,
updated_at: ws.updated_at,
};
}
function buildUserSettingsState(
resp: UserSettingsResponse | null,
workspaceId: string | null,
): AppState["userSettings"] {
return { ...mapUserSettingsResponse(resp), workspaceId };
}
function buildBaseState(
workspaces: ListWorkspacesResponse,
userSettingsResponse: UserSettingsResponse | null,
activeWorkspaceId: string | null,
): Partial<AppState> {
return {
workspaces: {
items: workspaces.workspaces.map(mapWorkspaceItem),
activeId: activeWorkspaceId,
},
userSettings: buildUserSettingsState(userSettingsResponse, activeWorkspaceId),
};
}
export function resolveActiveKanbanWorkspaceId(
workspaces: WorkspaceItem[],
workspaceId: string | undefined,
cookieWorkspaceId: string | null,
settingsWorkspaceId: string | null,
): string | null {
const kanbanWorkspaces = workspaces.filter((workspace) => !workspace.office_workflow_id);
return resolveActiveId(kanbanWorkspaces, workspaceId, cookieWorkspaceId, settingsWorkspaceId);
}
async function loadSnapshotState(
workflowId: string,
taskId: string | undefined,
sessionId: string | undefined,
): Promise<Partial<AppState>> {
const [snapshot, messagesResponse] = await Promise.all([
fetchWorkflowSnapshot(workflowId, { cache: "no-store" }),
taskId && sessionId
? listTaskSessionMessages(
sessionId,
{ limit: 50, sort: "desc" },
{ cache: "no-store" },
).catch(() => null)
: Promise.resolve(null),
]);
const state: Partial<AppState> = { ...snapshotToState(snapshot) };
if (sessionId && messagesResponse) {
const messages = [...(messagesResponse.messages ?? [])].reverse();
state.messages = {
bySession: { [sessionId]: messages },
metaBySession: {
[sessionId]: {
isLoading: false,
isLoadingMore: false,
hasMore: messagesResponse.has_more ?? false,
oldestCursor: messages[0]?.id ?? null,
},
},
};
}
return state;
}
async function loadWorkspaceState({
activeWorkspaceId,
initialState,
settingsWorkflowId,
workflowIdParam,
}: {
activeWorkspaceId: string;
initialState: Partial<AppState>;
settingsWorkflowId: string | null;
workflowIdParam: string | undefined;
}) {
// Fire-and-forget: warm the backend PR cache for this workspace.
// The client will fetch the data after mount via useWorkspacePRs.
listWorkspaceTaskPRs(activeWorkspaceId, { cache: "no-store" }).catch(() => {});
const [workflowList, repositoriesResponse, quickChatResponse, quickTerminalResponse] =
await Promise.all([
listWorkflows(activeWorkspaceId, { cache: "no-store", includeHidden: true }),
listRepositories(activeWorkspaceId, undefined, { cache: "no-store" })
.then((response) => ({ ...response, loaded: true }))
.catch(() => ({ repositories: [], loaded: false })),
listQuickChatSessions(activeWorkspaceId, { cache: "no-store" }).catch(() => ({
sessions: [],
task_sessions: [],
})),
listQuickTerminalTabs(activeWorkspaceId, { cache: "no-store" }).catch(() => ({ tabs: [] })),
]);
// null preserves the user's explicit "All Workflows" choice.
const workflowId = resolveDesiredWorkflowId({
activeWorkflowId: workflowIdParam ?? null,
settingsWorkflowId,
workspaceWorkflows: workflowList.workflows,
});
const quickChatSessions = toQuickChatSessions(quickChatResponse.sessions);
const quickTerminalTabs = quickTerminalResponse.tabs.map(toQuickTerminalTab);
return {
workflowId,
initialState: {
...initialState,
userSettings: {
...(initialState.userSettings as AppState["userSettings"]),
workflowId,
},
workflows: {
items: workflowList.workflows.map((workflow) => ({
id: workflow.id,
workspaceId: workflow.workspace_id,
name: workflow.name,
hidden: workflow.hidden,
})),
activeId: workflowId,
},
repositories: {
itemsByWorkspaceId: { [activeWorkspaceId]: repositoriesResponse.repositories },
loadingByWorkspaceId: { [activeWorkspaceId]: false },
// A failed SSR fetch must remain retryable on the client. Marking an
// empty fallback as loaded leaves task creation permanently disabled
// because the dialog never gets a repository selection.
loadedByWorkspaceId: { [activeWorkspaceId]: repositoriesResponse.loaded },
},
quickChat: {
isOpen: false,
sessions: quickChatSessions,
activeSessionId: null,
terminalTabs: quickTerminalTabs,
activeKind: "conversation" as const,
activeTerminalTabId: null,
lastTerminalTabIdByWorkspace: {},
unseenIdleByWorkspace: {},
lastSettledAtBySession: {},
sessionOwnership: {},
syncRevisionByWorkspace: {},
tombstonedSessions: {},
},
},
};
}
function renderPageClient(
initialState: Partial<AppState>,
workspaceId: string,
taskId?: string,
sessionId?: string,
) {
return (
<>
<StateHydrator initialState={initialState} />
<PageClient workspaceId={workspaceId} initialTaskId={taskId} initialSessionId={sessionId} />
</>
);
}
function renderUnresolvedPage(initialState: Partial<AppState>) {
return (
<>
<StateHydrator initialState={initialState} />
<PageClient />
</>
);
}
export default async function Page({ searchParams }: PageProps) {
try {
const resolvedParams = searchParams ? await searchParams : {};
const workspaceId = resolveParam(resolvedParams.workspaceId);
const workflowIdParam = resolveParam(resolvedParams.workflowId);
const taskId = resolveParam(resolvedParams.taskId);
const sessionId = resolveParam(resolvedParams.sessionId);
const [workspaces, userSettingsResponse, cookieStore] = await Promise.all([
listWorkspaces({ cache: "no-store" }),
fetchUserSettings({ cache: "no-store" }).catch(() => null),
readCookies().catch((error) => {
console.error("Failed to read cookies on Kanban page:", error);
return null;
}),
]);
const settingsWorkspaceId = userSettingsResponse?.settings?.workspace_id || null;
const settingsWorkflowId = userSettingsResponse?.settings?.workflow_filter_id || null;
// The sidebar picker writes the selected workspace to this cookie so the
// choice survives a refresh even when userSettings is not updated on select.
// Kanban home only resolves against kanban workspaces; office workspaces
// belong under /office.
const cookieWorkspaceId = cookieStore?.get(ACTIVE_WORKSPACE_COOKIE)?.value ?? null;
// `readCookies()` is client-only in this code path; during SSR this is empty.
// Workspace selection still works because spa-routes.tsx re-hydrates from
// `readActiveWorkspaceCookie()` and the generic resolver on first client render.
const activeWorkspaceId = resolveActiveKanbanWorkspaceId(
workspaces.workspaces,
workspaceId,
cookieWorkspaceId,
settingsWorkspaceId,
);
const initialState = buildBaseState(workspaces, userSettingsResponse, activeWorkspaceId);
if (!activeWorkspaceId) {
return renderUnresolvedPage(initialState);
}
const workspaceState = await loadWorkspaceState({
activeWorkspaceId,
initialState,
settingsWorkflowId,
workflowIdParam,
});
if (!workspaceState.workflowId)
return renderPageClient(workspaceState.initialState, activeWorkspaceId);
const snapshotState = await loadSnapshotState(workspaceState.workflowId, taskId, sessionId);
return renderPageClient(
{ ...workspaceState.initialState, ...snapshotState },
activeWorkspaceId,
taskId,
sessionId,
);
} catch {
return <PageClient />;
}
}
-108
View File
@@ -1,108 +0,0 @@
import { SettingsLayoutClient } from "@/components/settings/settings-layout-client";
import { StateHydrator } from "@/components/state-hydrator";
import {
fetchUserSettings,
listAgentDiscovery,
listAgents,
listAvailableAgents,
listExecutors,
listWorkspaces,
} from "@/lib/api";
import {
ACTIVE_WORKSPACE_COOKIE,
mapWorkspaceItem,
resolveSettingsActiveWorkspaceId,
} from "@/lib/routing/route-bootstrap";
import { mapUserSettingsResponse } from "@/lib/ssr/user-settings";
import { readCookies } from "@/lib/server/cookies";
import { toAgentProfileOption } from "@/lib/state/slices/settings/types";
export default function SettingsLayout({ children }: { children: React.ReactNode }) {
return <SettingsLayoutServer>{children}</SettingsLayoutServer>;
}
async function SettingsLayoutServer({ children }: { children: React.ReactNode }) {
let initialState = {};
try {
// Fetch discovery + available agents alongside the DB-backed list so a
// hard refresh of /settings/agents/[name] (where no profile exists yet)
// can still render the agent from the discovered set.
const [workspaces, executors, agents, discovery, available, userSettingsResponse, cookieStore] =
await Promise.all([
listWorkspaces({ cache: "no-store" }),
listExecutors({ cache: "no-store" }),
listAgents({ cache: "no-store" }),
listAgentDiscovery({ cache: "no-store" }),
listAvailableAgents({ cache: "no-store" }),
fetchUserSettings({ cache: "no-store" }).catch(() => null),
readCookies().catch(() => null),
]);
// Hydrate userSettings into the ROOT store so app-global, override-driven
// shortcuts (TOGGLE_SIDEBAR, Quick Chat) work on settings routes too. The
// settings/general page mounts its own nested store for editing; that store
// is invisible to the root-mounted GlobalCommands/useAppShortcuts.
const mappedUserSettings = mapUserSettingsResponse(userSettingsResponse);
const workspaceItems = workspaces.workspaces.map(mapWorkspaceItem);
const activeWorkspaceId = resolveSettingsActiveWorkspaceId(
workspaceItems,
// `readCookies()` is client-only in this path; during SSR this is empty.
// Settings active workspace selection is completed on first client render by
// spa-routes via `readActiveWorkspaceCookie()`.
cookieStore?.get(ACTIVE_WORKSPACE_COOKIE)?.value ?? null,
userSettingsResponse?.settings?.workspace_id ?? null,
);
initialState = {
workspaces: {
items: workspaceItems,
activeId: activeWorkspaceId,
},
executors: {
items: executors.executors,
},
agentProfiles: {
items: agents.agents.flatMap((agent) =>
agent.profiles.map((profile) => toAgentProfileOption(agent, profile)),
),
},
settingsAgents: {
items: agents.agents,
},
agentDiscovery: {
items: discovery.agents,
loading: false,
loaded: true,
},
availableAgents: {
items: available.agents,
tools: available.tools ?? [],
loading: false,
loaded: true,
},
settingsData: {
executorsLoaded: true,
agentsLoaded: true,
},
...(mappedUserSettings.loaded
? {
userSettings: {
...mappedUserSettings,
workspaceId: activeWorkspaceId,
},
}
: {}),
};
} catch {
// If any non-settings fetch (workspaces, executors, agents, …) throws, we
// render with empty initial state — losing the userSettings overrides too.
// That's acceptable: the page is already degraded (no executors/agents), so
// override-driven shortcuts being inactive until client hydration is fine.
initialState = {};
}
return (
<>
<StateHydrator initialState={initialState} />
<SettingsLayoutClient>{children}</SettingsLayoutClient>
</>
);
}
@@ -1,5 +1,12 @@
import { beforeEach, describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE } from "@/lib/routing/route-bootstrap";
// The write path scopes names with the API-origin port; pin it so the
// assertions are deterministic.
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://localhost:8443" }),
}));
import {
rememberWorkspaceSelection,
rememberWorkspaceSelectionById,
@@ -14,10 +21,26 @@ const officeWithReservedChars = {
office_workflow_id: "wf-office-reserved",
};
// Reads a cookie's value, treating an empty entry (lingering `name=` after an
// expired write) as absent — the same semantics as the production reader
// (readCookie: "an empty cookie value is treated as absent").
function cookieValue(name: string): string | null {
const prefix = `${name}=`;
const entry = document.cookie
.split(";")
.map((part) => part.trim())
.find((part) => part.startsWith(prefix));
if (!entry) return null;
const value = decodeURIComponent(entry.slice(prefix.length));
return value || null;
}
describe("app sidebar workspace navigation", () => {
beforeEach(() => {
document.cookie = "kandev-active-workspace=; path=/; max-age=0";
document.cookie = "office-active-workspace=; path=/; max-age=0";
document.cookie = "kandev-active-workspace_8443=; path=/; max-age=0";
document.cookie = "office-active-workspace_8443=; path=/; max-age=0";
});
it("routes workspace home by active workspace type", () => {
@@ -26,12 +49,18 @@ describe("app sidebar workspace navigation", () => {
expect(workspaceHomeHref(undefined)).toBe("/?home=overview");
});
it("records the active workspace in one write", () => {
it("records the active workspace in one write under the port-scoped names", () => {
rememberWorkspaceSelection(kanban);
rememberWorkspaceSelection(office);
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}=office-1`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}=office-1`);
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}_8443=office-1`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}_8443=office-1`);
// The legacy unprefixed names are read-only fallback — never written.
// Assert on VALUES, not presence: some environments keep an empty
// `name=` entry after a max-age=0 cleanup, and an empty value is
// equivalent to absent (readCookie treats it as such).
expect(cookieValue(ACTIVE_WORKSPACE_COOKIE)).toBeNull();
expect(cookieValue(LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE)).toBeNull();
});
it("does not write the legacy office cookie for a kanban selection", () => {
@@ -41,18 +70,18 @@ describe("app sidebar workspace navigation", () => {
// The office boot paths read the legacy cookie to pick an office workspace
// when the unified cookie names a kanban board, so a kanban selection must
// leave it pointing at the office workspace last used.
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}=kanban-1`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}=office-1`);
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}_8443=kanban-1`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}_8443=office-1`);
});
it("writes active and legacy office workspace cookies with an encoded id", () => {
it("writes scoped active and office workspace cookies with an encoded id", () => {
rememberWorkspaceSelection(officeWithReservedChars);
expect(document.cookie).toContain(
`${ACTIVE_WORKSPACE_COOKIE}=${encodeURIComponent(officeWithReservedChars.id)}`,
`${ACTIVE_WORKSPACE_COOKIE}_8443=${encodeURIComponent(officeWithReservedChars.id)}`,
);
expect(document.cookie).toContain(
`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}=${encodeURIComponent(officeWithReservedChars.id)}`,
`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}_8443=${encodeURIComponent(officeWithReservedChars.id)}`,
);
});
@@ -61,7 +90,26 @@ describe("app sidebar workspace navigation", () => {
// else, so there is no record to pass.
rememberWorkspaceSelectionById("office-new", "office");
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}=office-new`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}=office-new`);
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}_8443=office-new`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}_8443=office-new`);
expect(cookieValue(ACTIVE_WORKSPACE_COOKIE)).toBeNull();
expect(cookieValue(LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE)).toBeNull();
});
it("leaves a pre-existing legacy cookie untouched when the scoped twin is written", () => {
// Pre-upgrade jar (or a default-port instance sharing the host): the
// unprefixed names hold a value that must survive — it is either the
// migration fallback for other instances or another instance's live
// selection. The write path must not scrub it (spec: no proactive legacy
// cookie deletion).
document.cookie = `${ACTIVE_WORKSPACE_COOKIE}=pre-upgrade; path=/`;
document.cookie = `${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}=pre-upgrade; path=/`;
rememberWorkspaceSelection(office);
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}_8443=office-1`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}_8443=office-1`);
expect(document.cookie).toContain(`${ACTIVE_WORKSPACE_COOKIE}=pre-upgrade`);
expect(document.cookie).toContain(`${LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE}=pre-upgrade`);
});
});
@@ -1,6 +1,7 @@
import {
ACTIVE_WORKSPACE_COOKIE,
LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE,
scopedCookieName,
} from "@/lib/routing/route-bootstrap";
import { isOfficeWorkspace, type ModeWorkspace } from "@/lib/state/slices/workspace/selectors";
@@ -27,15 +28,26 @@ export function rememberWorkspaceSelection(workspace: ModeWorkspace | undefined)
export function rememberWorkspaceSelectionById(id: string, kind: "office" | "kanban"): void {
if (!id || typeof document === "undefined") return;
writeWorkspaceCookie(ACTIVE_WORKSPACE_COOKIE, id);
// The office boot paths (`app/office/layout.tsx` and the office route
// bootstrap) still read the legacy cookie to pick an office workspace when
// the unified one names a kanban board, so it is kept in step here.
// The office boot path (`src/office-routes.tsx`) reads the office-family
// cookie (scoped name first, legacy unprefixed name as read-only fallback)
// to pick an office workspace when the unified one names a kanban board, so
// it is kept in step here. Only the port-scoped names are ever written.
if (kind === "office") {
writeWorkspaceCookie(LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE, id);
}
}
/**
* Writes one workspace-selection cookie under its port-scoped name (API-origin
* port; the plain name on a no-port instance). The legacy unprefixed name is
* deliberately left untouched: on a host serving a default-port instance it is
* that instance's LIVE selection cookie, and for upgraded ported instances it
* is the validated migration fallback until each writes its own scoped value.
* Scrubbing it from one instance would change the other instances' next boot
* (see docs/specs/fix-multi-instance-cookie-isolation/spec.md: the upgraded
* instance does not proactively delete the legacy cookie).
*/
function writeWorkspaceCookie(name: string, value: string): void {
if (typeof document === "undefined") return;
document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${ACTIVE_WORKSPACE_COOKIE_MAX_AGE}; samesite=strict`;
document.cookie = `${scopedCookieName(name)}=${encodeURIComponent(value)}; path=/; max-age=${ACTIVE_WORKSPACE_COOKIE_MAX_AGE}; samesite=strict`;
}
@@ -1,6 +1,12 @@
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
// The sidebar write path scopes names with the API-origin port; pin it so the
// captured write assertions are deterministic.
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://localhost:8443" }),
}));
const navigationMock = vi.hoisted(() => ({ push: vi.fn() }));
vi.mock("@/lib/routing/client-router", () => ({
@@ -159,7 +165,7 @@ describe("AppSidebarWorkspacePicker — workspace select", () => {
fireEvent.click(screen.getByTestId(OFFICE_WORKSPACE_ITEM));
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace=w2"))).toBe(true);
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace_8443=w2"))).toBe(true);
expect(storeState.setActiveWorkspace).toHaveBeenCalledWith("w2");
expect(navigationMock.push).not.toHaveBeenCalled();
});
@@ -191,13 +197,13 @@ describe("AppSidebarWorkspacePicker — workspace select", () => {
it("does not overwrite the office workspace cookie when selecting a kanban workspace", () => {
storeState.features.office = true;
storeState.workspaces.activeId = "w2";
cookieWrites = ["office-active-workspace=w2; path=/"];
cookieWrites = ["office-active-workspace_8443=w2; path=/"];
render(<AppSidebarWorkspacePicker />);
fireEvent.click(screen.getByTestId(KANBAN_WORKSPACE_ITEM));
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace=w1"))).toBe(false);
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace=w2"))).toBe(true);
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace_8443=w1"))).toBe(false);
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace_8443=w2"))).toBe(true);
expect(storeState.setActiveWorkspace).toHaveBeenCalledWith("w1");
expect(navigationMock.push).toHaveBeenCalledWith("/?home=overview&workspaceId=w1");
});
@@ -217,13 +223,13 @@ describe("AppSidebarWorkspacePicker — workspace select", () => {
storeState.workspaces.activeId = "w2";
// Written when w2 was selected. A workspace is recorded on the way in, not
// on the way out, so leaving it must simply not disturb this.
cookieWrites = ["office-active-workspace=w2; path=/"];
cookieWrites = ["office-active-workspace_8443=w2; path=/"];
render(<AppSidebarWorkspacePicker />);
fireEvent.click(screen.getByTestId(KANBAN_WORKSPACE_ITEM));
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace=w1"))).toBe(false);
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace=w2"))).toBe(true);
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace_8443=w1"))).toBe(false);
expect(cookieWrites.some((c) => c.startsWith("office-active-workspace_8443=w2"))).toBe(true);
expect(storeState.setActiveWorkspace).toHaveBeenCalledWith("w1");
expect(navigationMock.push).toHaveBeenCalledWith("/?home=overview&workspaceId=w1");
});
@@ -277,7 +283,7 @@ describe("AppSidebarWorkspacePicker — active workspace display and routing", (
fireEvent.click(screen.getByTestId(KANBAN_WORKSPACE_ITEM));
expect(cookieWrites.some((c) => c.startsWith("kandev-active-workspace=w1"))).toBe(true);
expect(cookieWrites.some((c) => c.startsWith("kandev-active-workspace_8443=w1"))).toBe(true);
// Re-selecting the workspace that is already active goes through the same
// one selection path as any other pick; the store action ignores a
// no-op change, so there is no reason for this branch to skip it.
+4 -3
View File
@@ -3,9 +3,10 @@ import { expect, type BrowserContext } from "@playwright/test";
/**
* Helpers for the opt-in authentication E2E suite.
*
* All calls go through a BrowserContext's request API so the kandev_session
* cookie set by login/setup/invite-accept is shared with pages opened from the
* same context (matching how the real SPA authenticates).
* All calls go through a BrowserContext's request API so the session cookie
* (port-scoped name, e.g. kandev_session_<port>) set by login/setup/invite
* accept is shared with pages opened from the same context (matching how the
* real SPA authenticates).
*/
export type Credentials = {
@@ -118,6 +118,29 @@ test.describe.serial("opt-in authentication", () => {
await context.close();
});
test("session cookie is port-scoped to the instance", async ({ browser, backend }) => {
// The session cookie is HttpOnly, so the name is asserted from the login
// response's Set-Cookie headers, not document.cookie. Two instances on one
// host (different ports) must not share a cookie name.
const context = await browser.newContext({ baseURL: backend.frontendUrl });
const res = await context.request.post(`${backend.baseUrl}/api/v1/auth/login`, {
data: { email: ADMIN.email, password: ADMIN.password },
});
expect(res.ok()).toBeTruthy();
const sessionNames = res
.headersArray()
.filter((h) => h.name.toLowerCase() === "set-cookie")
.map((h) => h.value.split(";")[0].split("=")[0])
.filter((name) => name.startsWith("kandev_session"));
expect(sessionNames).toEqual([`kandev_session_${backend.port}`]);
// The scoped session authenticates: the app renders authenticated content.
expect((await context.request.get(`${backend.baseUrl}/api/v1/workspaces`)).ok()).toBeTruthy();
await context.close();
});
test("two users are fully segregated over HTTP, boot payload, and WS", async ({
browser,
backend,
@@ -8,7 +8,7 @@ test.describe("Execution indicator", () => {
await testPage.goto("/office/tasks");
// Post-overhaul: the unified AppSidebar's Tasks section also lists tasks, so
// the title text appears in BOTH the global rail and the page table. Scope
// to `<main>` (the office layout's page content, which excludes the
// to `<main>` (the office shell's page content, which excludes the
// `<aside data-testid="app-sidebar">`) to avoid a strict-mode duplicate.
await expect(testPage.locator("main").getByText("Indicator Test Task")).toBeVisible({
timeout: 10_000,
@@ -33,11 +33,10 @@ test.describe("Office runtime agent creation", () => {
expect(createResponse.status).toBe(201);
const createdBody = (await createResponse.json()) as { agent: { id: string } };
// The office layout's SSR reads agentProfiles for the active
// workspace. Confirm the runtime-created agent is visible from
// the public list endpoint before we navigate — otherwise the
// layout would render "Agent not found." and never paint the
// topbar portal (no testid).
// The office boot payload gates agentProfiles on the active workspace.
// Confirm the runtime-created agent is visible from the public list
// endpoint before we navigate — otherwise the office route would render
// "Agent not found." and never paint the topbar portal (no testid).
await expect
.poll(
async () => {
@@ -63,9 +63,9 @@ test.describe("Sidebar navigation", () => {
// link asserted above; both are intentional entry points to /office/tasks.
await testPage.getByRole("link", { name: /Tasks In Progress/i }).click();
// Scope the heading assertion to the page content (`<main>` in the office
// layout). The unified AppSidebar's collapsible "Tasks" section header also
// exposes the accessible text "Tasks", so an unscoped role=heading/text
// match could be ambiguous against the global rail.
// shell's page content). The unified AppSidebar's collapsible "Tasks"
// section header also exposes the accessible text "Tasks", so an unscoped
// role=heading/text match could be ambiguous against the global rail.
await expect(
testPage.locator("main").getByRole("heading", { name: /Tasks/i }).first(),
).toBeVisible({
@@ -10,15 +10,24 @@ import { SessionPage } from "../../pages/session-page";
const ACTIVE_WORKSPACE_COOKIE = "kandev-active-workspace";
async function activeWorkspaceCookie(page: Page): Promise<string | null> {
return page.evaluate((name) => {
const prefix = `${name}=`;
const match = document.cookie
.split(";")
.map((part) => part.trim())
.find((part) => part.startsWith(prefix));
return match ? decodeURIComponent(match.slice(prefix.length)) : null;
}, ACTIVE_WORKSPACE_COOKIE);
// Reads the port-scoped active workspace cookie first, falling back to the
// legacy unprefixed name (read-only fallback for pre-upgrade selections).
async function activeWorkspaceCookie(page: Page, port: string): Promise<string | null> {
return page.evaluate(
({ baseName, port }) => {
const names = port ? [`${baseName}_${port}`, baseName] : [baseName];
for (const name of names) {
const prefix = `${name}=`;
const match = document.cookie
.split(";")
.map((part) => part.trim())
.find((part) => part.startsWith(prefix));
if (match) return decodeURIComponent(match.slice(prefix.length));
}
return null;
},
{ baseName: ACTIVE_WORKSPACE_COOKIE, port },
);
}
async function gotoTaskList(page: Page): Promise<void> {
@@ -101,7 +110,9 @@ test.describe("Sidebar — cross-workspace isolation", () => {
await expect(testPage.getByTestId("dockview-task-layout")).toHaveCount(0);
await expect(kanban.taskCard(taskB.id)).toBeVisible({ timeout: 10_000 });
await expect(kanban.taskCard(taskA.id)).not.toBeVisible();
await expect.poll(() => activeWorkspaceCookie(testPage)).toBe(workspaceB.id);
await expect
.poll(() => activeWorkspaceCookie(testPage, String(backend.port)))
.toBe(workspaceB.id);
// A hard reload and the task-list route must bootstrap the same cookie-backed
// workspace before client effects can fall back to the seed workspace.
@@ -130,6 +141,55 @@ test.describe("Sidebar — cross-workspace isolation", () => {
await expect(taskInList(testPage, "Workspace A Task")).not.toBeVisible();
});
test("writes the port-scoped workspace cookie and preserves the legacy name", async ({
testPage,
apiClient,
backend,
}) => {
const workspaceB = await apiClient.createWorkspace("Workspace B Cookie Scope");
// Simulate a pre-upgrade jar: the legacy unprefixed cookie exists before
// any selection is made post-upgrade.
await testPage.addInitScript(
({ baseName }) => {
document.cookie = `${baseName}=pre-upgrade; path=/`;
},
{ baseName: ACTIVE_WORKSPACE_COOKIE },
);
const kanban = new KanbanPage(testPage);
await kanban.goto();
await testPage.getByTestId("sidebar-workspace-trigger").click();
await testPage.getByTestId(`sidebar-workspace-item-${workspaceB.id}`).click();
await expect(testPage).toHaveURL(
(url) => url.pathname === "/" && url.searchParams.get("workspaceId") === workspaceB.id,
);
await expect(kanban.board).toBeVisible();
// The selection is recorded under the port-scoped name. The legacy
// unprefixed name must be left byte-for-byte untouched: on a host serving
// a default-port instance it is that instance's live selection cookie,
// and for upgraded ported instances it is the validated migration
// fallback (spec: no proactive legacy cookie scrubbing).
await expect
.poll(() => activeWorkspaceCookie(testPage, String(backend.port)))
.toBe(workspaceB.id);
const cookieState = await testPage.evaluate(
({ baseName, port }) => ({
unprefixedValue:
document.cookie
.split(";")
.map((part) => part.trim())
.find((part) => part.startsWith(`${baseName}=`))
?.slice(baseName.length + 1) ?? null,
scoped: document.cookie.includes(`${baseName}_${port}=`),
}),
{ baseName: ACTIVE_WORKSPACE_COOKIE, port: String(backend.port) },
);
expect(cookieState.scoped, "scoped cookie must be present").toBe(true);
expect(cookieState.unprefixedValue, "legacy cookie must be preserved").toBe("pre-upgrade");
});
test("creates only in the selected workspace after switching from an open task", async ({
testPage,
apiClient,
+329 -3
View File
@@ -1,18 +1,39 @@
import { beforeEach, describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import fs from "node:fs";
import path from "node:path";
// The default cookie port derives from the API base URL. Mock it to a fixed
// port so scoped-name assertions are deterministic and independent of the
// jsdom default origin (http://localhost:3000).
vi.mock("@/lib/config", () => ({
getBackendConfig: vi.fn(() => ({ apiBaseUrl: "http://localhost:8443" })),
}));
import { getBackendConfig } from "@/lib/config";
const GENERAL_COOKIE = "kandev-active-workspace";
const OFFICE_COOKIE = "office-active-workspace";
import {
apiOriginPort,
mapWorkspaceItem,
promoteLegacyWorkspaceSelection,
readActiveWorkspaceCookie,
readCookie,
readScopedCookie,
resolveOfficeWorkspaceId,
resolveSettingsActiveWorkspaceId,
scopedCookieName,
} from "./route-bootstrap";
import type { ListWorkspacesResponse } from "@/lib/types/http";
type WorkspaceItem = ListWorkspacesResponse["workspaces"][number];
beforeEach(() => {
document.cookie = "kandev-active-workspace=; path=/; max-age=0";
document.cookie = "office-active-workspace=; path=/; max-age=0";
document.cookie = `${GENERAL_COOKIE}=; path=/; max-age=0`;
document.cookie = `${OFFICE_COOKIE}=; path=/; max-age=0`;
document.cookie = `${GENERAL_COOKIE}_8443=; path=/; max-age=0`;
document.cookie = `${OFFICE_COOKIE}_8443=; path=/; max-age=0`;
});
describe("mapWorkspaceItem", () => {
@@ -93,3 +114,308 @@ describe("resolveSettingsActiveWorkspaceId", () => {
expect(resolveSettingsActiveWorkspaceId([], "k-1", "k-2")).toBeNull();
});
});
describe("scopedCookieName", () => {
it("appends the port suffix when a port is given", () => {
expect(scopedCookieName(GENERAL_COOKIE, "8443")).toBe("kandev-active-workspace_8443");
expect(scopedCookieName(OFFICE_COOKIE, "8443")).toBe("office-active-workspace_8443");
});
it("keeps the plain name when the port is empty", () => {
expect(scopedCookieName(GENERAL_COOKIE, "")).toBe("kandev-active-workspace");
});
it("derives the default port from the API base URL, not window.location.port", () => {
// Split-origin dev regression: the SPA runs on the web port and the API on
// the backend port (no Vite proxy). The cookie suffix must come from the
// API origin (here mocked to :8443), never from the browser location
// (jsdom default :3000), or the backend would read a different name.
expect(window.location.port).toBe("3000");
expect(scopedCookieName(GENERAL_COOKIE)).toBe("kandev-active-workspace_8443");
});
});
describe("promoteLegacyWorkspaceSelection", () => {
beforeEach(() => {
document.cookie = `${GENERAL_COOKIE}=; path=/; max-age=0`;
document.cookie = `${GENERAL_COOKIE}_8443=; path=/; max-age=0`;
document.cookie = `${OFFICE_COOKIE}=; path=/; max-age=0`;
document.cookie = `${OFFICE_COOKIE}_8443=; path=/; max-age=0`;
});
it("copies a validated legacy selection into the scoped cookie on first boot", () => {
document.cookie = `${GENERAL_COOKIE}=kanban-1; path=/`;
promoteLegacyWorkspaceSelection([{ id: "kanban-1" }, { id: "office-1" }]);
// The scoped cookie is now written and the legacy name is untouched (it
// is another instance's live cookie / the migration fallback for others).
expect(document.cookie).toContain(`${GENERAL_COOKIE}_8443=kanban-1`);
expect(document.cookie).toContain(`${GENERAL_COOKIE}=kanban-1`);
});
it("is a no-op when the scoped cookie already exists", () => {
document.cookie = `${GENERAL_COOKIE}=legacy-1; path=/`;
document.cookie = `${GENERAL_COOKIE}_8443=scoped-1; path=/`;
promoteLegacyWorkspaceSelection([{ id: "scoped-1" }, { id: "legacy-1" }]);
expect(readScopedCookie(GENERAL_COOKIE, "8443")).toBe("scoped-1");
expect(document.cookie).toContain(`${GENERAL_COOKIE}=legacy-1`);
});
it("is a no-op when the legacy value does not name a workspace", () => {
document.cookie = `${GENERAL_COOKIE}=stale-id; path=/`;
promoteLegacyWorkspaceSelection([{ id: "kanban-1" }]);
// No scoped twin was written (assert on VALUE: an empty lingering entry
// may exist after the cleanup, and readScopedCookie would return the
// legacy fallback anyway).
expect(document.cookie).not.toContain(`${GENERAL_COOKIE}_8443=stale-id`);
});
it("is a no-op on a no-port instance (scoped == legacy)", () => {
document.cookie = `${GENERAL_COOKIE}=kanban-1; path=/`;
vi.mocked(getBackendConfig).mockReturnValue({ apiBaseUrl: "http://localhost" });
try {
promoteLegacyWorkspaceSelection([{ id: "kanban-1" }]);
// No scoped twin exists to write; the plain name is the scoped name.
expect(readScopedCookie(GENERAL_COOKIE, "")).toBe("kanban-1");
expect(document.cookie).not.toContain(`${GENERAL_COOKIE}_=`);
} finally {
vi.mocked(getBackendConfig).mockReturnValue({ apiBaseUrl: "http://localhost:8443" });
}
});
it("promotes the office family under its own name", () => {
document.cookie = `${OFFICE_COOKIE}=office-1; path=/`;
promoteLegacyWorkspaceSelection([{ id: "office-1" }], OFFICE_COOKIE);
expect(document.cookie).toContain(`${OFFICE_COOKIE}_8443=office-1`);
expect(document.cookie).toContain(`${OFFICE_COOKIE}=office-1`);
// The general family is untouched.
expect(readScopedCookie(GENERAL_COOKIE, "8443")).toBeNull();
});
});
describe("readScopedCookie", () => {
it("reads the port-scoped cookie first", () => {
document.cookie = `${GENERAL_COOKIE}_8443=scoped-1; path=/`;
expect(readScopedCookie(GENERAL_COOKIE, "8443")).toBe("scoped-1");
});
it("falls back to the legacy unprefixed name when no scoped cookie exists", () => {
document.cookie = `${GENERAL_COOKIE}=legacy-1; path=/`;
expect(readScopedCookie(GENERAL_COOKIE, "8443")).toBe("legacy-1");
});
it("returns null when neither name exists", () => {
expect(readScopedCookie(GENERAL_COOKIE, "8443")).toBeNull();
});
it("keeps the plain-name read for a default-port (no suffix) instance", () => {
document.cookie = `${GENERAL_COOKIE}=legacy-1; path=/`;
expect(readScopedCookie(GENERAL_COOKIE, "")).toBe("legacy-1");
});
it("uses the API-origin default port for the active-workspace read", () => {
document.cookie = `${GENERAL_COOKIE}_8443=scoped-1; path=/`;
document.cookie = `${GENERAL_COOKIE}=legacy-1; path=/`;
expect(readActiveWorkspaceCookie()).toBe("scoped-1");
});
it("derives no port server-side without a configured API base URL", () => {
// Fail-closed: a server-side helper beside the backend has no browser
// origin, so the dev default port must not leak into cookie names.
const env = { ...process.env };
try {
delete process.env.KANDEV_API_BASE_URL;
const originalWindow = globalThis.window;
// happy-dom defines window; simulate a server context.
Object.defineProperty(globalThis, "window", { value: undefined, configurable: true });
try {
expect(apiOriginPort()).toBe("");
} finally {
Object.defineProperty(globalThis, "window", {
value: originalWindow,
configurable: true,
});
}
} finally {
process.env = env;
}
});
});
describe("resolveOfficeWorkspaceId", () => {
const OFFICE = { id: "office-1", office_workflow_id: "wf-1" };
const OFFICE_TWO = { id: "office-2", office_workflow_id: "wf-2" };
const KANBAN = { id: "kanban-1", office_workflow_id: null };
const items = [OFFICE, OFFICE_TWO];
it("prefers the route override over every cookie candidate", () => {
expect(
resolveOfficeWorkspaceId(items, {
routeWorkspaceId: OFFICE_TWO.id,
generalWorkspaceId: OFFICE.id,
officeWorkspaceId: OFFICE.id,
settingsWorkspaceId: OFFICE.id,
}),
).toBe(OFFICE_TWO.id);
});
it("prefers the general cookie over the office cookie when it names an office workspace", () => {
expect(
resolveOfficeWorkspaceId(items, {
routeWorkspaceId: null,
generalWorkspaceId: OFFICE.id,
officeWorkspaceId: OFFICE_TWO.id,
settingsWorkspaceId: null,
}),
).toBe(OFFICE.id);
});
it("falls through a kanban general cookie to the office cookie", () => {
expect(
resolveOfficeWorkspaceId(items, {
routeWorkspaceId: null,
generalWorkspaceId: KANBAN.id,
officeWorkspaceId: OFFICE_TWO.id,
settingsWorkspaceId: null,
}),
).toBe(OFFICE_TWO.id);
});
it("prefers the office cookie over settings", () => {
expect(
resolveOfficeWorkspaceId(items, {
routeWorkspaceId: null,
generalWorkspaceId: null,
officeWorkspaceId: OFFICE.id,
settingsWorkspaceId: OFFICE_TWO.id,
}),
).toBe(OFFICE.id);
});
it("falls back to settings, then the first workspace, then null", () => {
expect(
resolveOfficeWorkspaceId(items, {
routeWorkspaceId: null,
generalWorkspaceId: "ws-missing",
officeWorkspaceId: null,
settingsWorkspaceId: OFFICE_TWO.id,
}),
).toBe(OFFICE_TWO.id);
expect(
resolveOfficeWorkspaceId(items, {
routeWorkspaceId: null,
generalWorkspaceId: "ws-missing",
officeWorkspaceId: null,
settingsWorkspaceId: null,
}),
).toBe(OFFICE.id);
expect(resolveOfficeWorkspaceId([], { routeWorkspaceId: "office-1" })).toBeNull();
});
});
describe("structural guard: workspace-cookie lookups stay scoped", () => {
const here = path.dirname(new URL(import.meta.url).pathname);
const read = (file: string) => fs.readFileSync(path.resolve(here, "..", "..", file), "utf8");
// The live consumers of the workspace-cookie families. The Next-style
// server-component layer that previously held these lookups
// (app/office/layout.tsx, app/office/lib/get-active-workspace.ts,
// app/page.tsx, app/settings/layout.tsx) was unreachable in the Vite SPA
// and removed; every reader that remains runs in the browser.
const readers = [
"src/office-routes.tsx", // office boot: general then office family
"src/kanban-route.tsx", // kanban boot: general family
"src/settings-routes.tsx", // settings boot: general family
"src/spa-routes.tsx", // generic boot re-hydration: general family
];
const writer = "components/app-sidebar/app-sidebar-workspace-navigation.ts";
const allConsumers = [...readers, writer];
const workspaceCookieNames = `(ACTIVE_WORKSPACE_COOKIE|LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE|"${GENERAL_COOKIE}"|"${OFFICE_COOKIE}")`;
it("negative: no consumer performs a direct workspace-cookie lookup", () => {
for (const file of allConsumers) {
const source = read(file);
// Direct readCookie(...) with a workspace-cookie name (literal or
// exported constant) is forbidden — the scoped helpers are the only
// allowed read path.
const direct = new RegExp(`readCookie\\s*\\(\\s*${workspaceCookieNames}`);
expect(direct.test(source), `${file} must not read workspace cookies directly`).toBe(false);
}
});
it("positive: each reader reads via a scoped-first helper", () => {
for (const file of readers) {
const source = read(file);
expect(
source.includes("readActiveWorkspaceCookie") || source.includes("readScopedCookie"),
`${file} must read via a scoped-first helper`,
).toBe(true);
}
});
it("passes the correct cookie names per reader", () => {
// Whitespace- and trailing-comma-agnostic match: formatting must not
// break the contract check.
const compact = (file: string) => read(file).replace(/\s+/g, "").replace(/,/g, "");
// The office boot reads the office family (general first) to pick an
// office workspace when the unified cookie names a kanban board.
const officeSource = compact("src/office-routes.tsx");
const general = officeSource.indexOf("readActiveWorkspaceCookie()");
const office = officeSource.indexOf("readScopedCookie(LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE)");
expect(general, "office-routes must read the general family first").toBeGreaterThan(-1);
expect(office, "office-routes must read the office family").toBeGreaterThan(-1);
expect(
general,
"office-routes must read the general family before the office family",
).toBeLessThan(office);
// Kanban and settings boot read only the general family.
for (const file of ["src/kanban-route.tsx", "src/settings-routes.tsx", "src/spa-routes.tsx"]) {
const source = compact(file);
expect(
source.includes("readActiveWorkspaceCookie()"),
`${file} must read the general cookie via the scoped reader`,
).toBe(true);
expect(source.includes("LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE")).toBe(false);
}
});
it("promotes validated legacy selections in every live reader", () => {
const compact = (file: string) => read(file).replace(/\s+/g, "").replace(/,/g, "");
for (const file of readers) {
expect(
compact(file).includes("promoteLegacyWorkspaceSelection(workspaceItems)"),
`${file} must promote the general workspace cookie after validation`,
).toBe(true);
}
expect(
compact("src/office-routes.tsx").includes(
"promoteLegacyWorkspaceSelection(officeWorkspaceItemsLEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE)",
),
"office-routes must also promote the office workspace cookie",
).toBe(true);
});
it("the sidebar writer scopes names and leaves legacy cookies untouched", () => {
const source = read(writer);
expect(source.includes("scopedCookieName("), `${writer} must write scoped names`).toBe(true);
// The legacy unprefixed names are read-only fallback: never written and
// never expired (spec: no proactive legacy cookie scrubbing — on a host
// with a default-port instance the unprefixed name is that instance's
// live selection cookie).
expect(source.includes("max-age=0"), `${writer} must not expire cookies`).toBe(false);
});
});
+115 -1
View File
@@ -1,11 +1,63 @@
import { getBackendConfig } from "@/lib/config";
import type { WorkspaceState } from "@/lib/state/slices/workspace/types";
import type { ListWorkspacesResponse } from "@/lib/types/http";
export const ACTIVE_WORKSPACE_COOKIE = "kandev-active-workspace";
export const LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE = "office-active-workspace";
// One year; matches the sidebar writer's selection-cookie lifetime.
const WORKSPACE_COOKIE_MAX_AGE = 31536000;
type WorkspaceItem = ListWorkspacesResponse["workspaces"][number];
/**
* The API origin port. Browsers ignore port when matching cookies, so multiple
* kandev instances on one host (same IP, different ports) share one cookie
* jar; suffixing cookie names with this port isolates each instance's
* selection. Derived from the API base URL, NOT `window.location.port` — they
* only match in same-origin deployments (split-origin dev runs the SPA on the
* web port and the API on the backend port).
*/
export function apiOriginPort(): string {
if (typeof window === "undefined" && !process.env.KANDEV_API_BASE_URL) {
// Server-side helper beside the backend with no configured base URL: the
// dev default port means nothing on the real host, and scoping against it
// would produce a cookie name no browser ever writes. Unscoped is the
// fail-closed default; the browser (which has the real origin) is the
// only live cookie reader.
return "";
}
return new URL(getBackendConfig().apiBaseUrl).port;
}
/**
* Port-scopes a cookie name: `kandev-active-workspace` + port `8443` →
* `kandev-active-workspace_8443`. An empty/missing port keeps the plain name,
* so default-port (no port in the URL) deployments are unchanged.
*/
export function scopedCookieName(name: string, port?: string): string {
const suffix = port ?? apiOriginPort();
return suffix ? `${name}_${suffix}` : name;
}
/**
* Reads the port-scoped cookie first, falling back to the legacy unprefixed
* name so a pre-upgrade selection survives. The explicit `port` parameter
* keeps the helper pure and unit-testable without jsdom Location stubbing.
* An empty cookie value is treated as absent: expired/deleted cookies can
* linger as empty entries in document.cookie and must not shadow the
* fallback. On a default-port instance the scoped name IS the legacy name,
* so the fallback read is skipped (identical call, no-op).
*/
export function readScopedCookie(name: string, port?: string): string | null {
const scopedName = scopedCookieName(name, port);
const scoped = readCookie(scopedName);
if (scoped) return scoped;
if (scopedName === name) return null;
const legacy = readCookie(name);
return legacy || null;
}
export function mapWorkspaceItem(ws: WorkspaceItem): WorkspaceState["items"][number] {
return {
id: ws.id,
@@ -34,7 +86,69 @@ export function readCookie(name: string): string | null {
}
export function readActiveWorkspaceCookie(): string | null {
return readCookie(ACTIVE_WORKSPACE_COOKIE) || null;
return readScopedCookie(ACTIVE_WORKSPACE_COOKIE);
}
/**
* One-time promotion of a validated legacy selection into the scoped cookie.
*
* A ported instance whose scoped cookie was never written (fresh upgrade, or
* no explicit selection yet on this instance) falls back to the legacy
* unprefixed name on every boot, keeping it coupled to the shared jar. Once
* the boot resolves a legacy value that names one of the instance's own
* workspaces, copy it into the port-scoped name so later boots read the
* scoped cookie — without touching the legacy name, which is the live
* selection cookie of any default-port instance on the host and the
* migration fallback for other instances (spec: no proactive legacy
* scrubbing). No-op when the scoped cookie already exists, the legacy value
* is absent or invalid, or the instance has no port (scoped == legacy).
*/
export function promoteLegacyWorkspaceSelection(
workspaceItems: { id: string }[],
name: string = ACTIVE_WORKSPACE_COOKIE,
): void {
if (typeof document === "undefined") return;
const port = apiOriginPort();
if (!port) return;
const scoped = `${name}_${port}`;
if (readCookie(scoped)) return;
const legacy = readCookie(name);
if (!legacy || !workspaceItems.some((ws) => ws.id === legacy)) return;
document.cookie = `${scoped}=${encodeURIComponent(legacy)}; path=/; max-age=${WORKSPACE_COOKIE_MAX_AGE}; samesite=strict`;
}
export type OfficeWorkspaceItem = { id: string; office_workflow_id?: string | null };
export type OfficeWorkspaceCandidates = {
routeWorkspaceId?: string | null;
generalWorkspaceId?: string | null;
officeWorkspaceId?: string | null;
settingsWorkspaceId?: string | null;
};
/**
* Canonical office active-workspace resolver (frontend half of the
* fix-multi-instance-cookie-isolation task-03 contract). Precedence:
* explicit route override → general cookie when it names an office workspace
* → office cookie → user settings → first office workspace. Every candidate is
* validated against the office workspace set passed in. `routeWorkspaceId` is
* a client/page-only candidate: server layouts and the backend boot payload
* are cookie-first by design and pass null.
*/
export function resolveOfficeWorkspaceId(
workspaceItems: OfficeWorkspaceItem[],
candidates: OfficeWorkspaceCandidates,
): string | null {
const { routeWorkspaceId, generalWorkspaceId, officeWorkspaceId, settingsWorkspaceId } =
candidates;
return (
workspaceItems.find((workspace) => workspace.id === routeWorkspaceId)?.id ??
workspaceItems.find((workspace) => workspace.id === generalWorkspaceId)?.id ??
workspaceItems.find((workspace) => workspace.id === officeWorkspaceId)?.id ??
workspaceItems.find((workspace) => workspace.id === settingsWorkspaceId)?.id ??
workspaceItems[0]?.id ??
null
);
}
type SettingsWorkspaceItem = {
@@ -7,9 +7,9 @@ export type WorkspaceItem = WorkspaceState["items"][number];
* The fields an Office-vs-kanban decision needs, and nothing more.
*
* Structural rather than `WorkspaceItem` because callers hold workspace-shaped
* records from several sources — store items, API list responses, server-side
* helpers under `app/office/lib/`, test fixtures — and every one of them can
* answer this question without first being widened to the full record.
* records from several sources — store items, API list responses, test
* fixtures — and every one of them can answer this question without first
* being widened to the full record.
*/
export type ModeWorkspace = { id: string; office_workflow_id?: string | null };
+7 -1
View File
@@ -11,7 +11,11 @@ import { listWorkflows } from "@/lib/api/domains/kanban-api";
import { listRepositories, listWorkspaces } from "@/lib/api/domains/workspace-api";
import { resolveDesiredWorkflowId } from "@/lib/kanban/resolve-workflow";
import { hasHydratedKanbanRouteState } from "@/lib/routing/kanban-route-hydration";
import { mapWorkspaceItem, readActiveWorkspaceCookie } from "@/lib/routing/route-bootstrap";
import {
mapWorkspaceItem,
promoteLegacyWorkspaceSelection,
readActiveWorkspaceCookie,
} from "@/lib/routing/route-bootstrap";
import { useRouter } from "@/lib/routing/client-router";
import { mapUserSettingsResponse } from "@/lib/ssr/user-settings";
import { isOfficeWorkspace } from "@/lib/state/slices/workspace/selectors";
@@ -82,6 +86,7 @@ function useKanbanRouteBootstrap(route: KanbanRouteSelection, skip: boolean) {
const store = useAppStoreApi();
useEffect(() => {
promoteLegacyWorkspaceSelection(store.getState().workspaces.items);
if (skip) return;
if (hasHydratedKanbanRouteState(store.getState(), route)) return;
@@ -97,6 +102,7 @@ function useKanbanRouteBootstrap(route: KanbanRouteSelection, skip: boolean) {
const settingsWorkspaceId = settingsResponse?.settings?.workspace_id || null;
const settingsWorkflowId = settingsResponse?.settings?.workflow_filter_id || null;
const workspaceItems = workspacesResponse.workspaces.map(mapWorkspaceItem);
promoteLegacyWorkspaceSelection(workspaceItems);
const activeWorkspaceId = resolveKanbanRouteWorkspaceId(
workspaceItems,
route.workspaceId,
+47 -54
View File
@@ -1,75 +1,68 @@
import { beforeEach, describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
// The scoped cookie helpers derive the default port from the API base URL;
// pin it so scoped-name fixtures are deterministic.
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://localhost:8443" }),
}));
import {
__resetIdParamsPromiseCacheForTests,
idParamsPromise,
resolveActiveOfficeWorkspaceId,
resolveOfficeBootstrapWorkspaceId,
} from "./office-routes";
describe("resolveActiveOfficeWorkspaceId", () => {
describe("resolveOfficeBootstrapWorkspaceId (OfficeRoutes cookie reads)", () => {
const wsOffice1 = "ws-office-1";
const wsOffice2 = "ws-office-2";
const officeFlow1 = "office-flow-1";
const officeFlow2 = "office-flow-2";
const wsKanban = "ws-kanban-1";
const items = [
{ id: wsOffice1, office_workflow_id: "office-flow-1" },
{ id: wsOffice2, office_workflow_id: "office-flow-2" },
];
it("prefers explicit route workspace ID", () => {
const activeId = resolveActiveOfficeWorkspaceId(
[
{ id: wsOffice1, office_workflow_id: officeFlow1 },
{ id: wsOffice2, office_workflow_id: officeFlow2 },
],
wsOffice2,
"ws-office-1",
null,
null,
);
expect(activeId).toBe(wsOffice2);
beforeEach(() => {
document.cookie = "kandev-active-workspace=; path=/; max-age=0";
document.cookie = "office-active-workspace=; path=/; max-age=0";
document.cookie = "kandev-active-workspace_8443=; path=/; max-age=0";
document.cookie = "office-active-workspace_8443=; path=/; max-age=0";
});
it("falls back to the generic office workspace cookie when active cookie misses", () => {
const activeId = resolveActiveOfficeWorkspaceId(
[
{ id: wsOffice1, office_workflow_id: officeFlow1 },
{ id: wsOffice2, office_workflow_id: officeFlow2 },
],
null,
"ws-missing",
wsOffice1,
wsOffice2,
);
it("route override beats cookies naming a different workspace (invariant)", () => {
document.cookie = "kandev-active-workspace_8443=ws-office-1; path=/";
document.cookie = "office-active-workspace_8443=ws-office-1; path=/";
expect(activeId).toBe(wsOffice1);
expect(resolveOfficeBootstrapWorkspaceId(items, wsOffice2, null)).toBe(wsOffice2);
});
it("falls back to settings workspace when no cookie matches", () => {
const activeId = resolveActiveOfficeWorkspaceId(
[
{ id: wsOffice1, office_workflow_id: officeFlow1 },
{ id: wsOffice2, office_workflow_id: officeFlow2 },
],
null,
"ws-missing",
null,
wsOffice2,
);
it("hydrates the scoped general cookie with no route or unprefixed cookie (failing-before)", () => {
// Non-first fixture: pre-change the reader only sees unprefixed names, so
// this resolves to the first office workspace instead of ws-office-2.
document.cookie = "kandev-active-workspace_8443=ws-office-2; path=/";
expect(activeId).toBe(wsOffice2);
expect(resolveOfficeBootstrapWorkspaceId(items, null, null)).toBe(wsOffice2);
});
it("uses kandev-active-workspace when it holds an office workspace ID", () => {
const activeId = resolveActiveOfficeWorkspaceId(
[
{ id: wsOffice1, office_workflow_id: officeFlow1 },
{ id: wsOffice2, office_workflow_id: officeFlow2 },
],
null,
wsOffice1,
wsOffice2,
null,
);
it("prefers the scoped office cookie when the general cookie names a kanban workspace (failing-before)", () => {
// Pre-change the effect reads only the unprefixed office cookie (absent),
// so this falls to settings/first instead of ws-office-2.
document.cookie = `kandev-active-workspace_8443=${wsKanban}; path=/`;
document.cookie = "office-active-workspace_8443=ws-office-2; path=/";
expect(activeId).toBe(wsOffice1);
expect(resolveOfficeBootstrapWorkspaceId(items, null, null)).toBe(wsOffice2);
});
it("falls back to the legacy unprefixed office cookie when no scoped one exists", () => {
document.cookie = "office-active-workspace=ws-office-2; path=/";
expect(resolveOfficeBootstrapWorkspaceId(items, null, null)).toBe(wsOffice2);
});
it("resolves settings, then first, when no cookie names an office workspace", () => {
document.cookie = `kandev-active-workspace_8443=${wsKanban}; path=/`;
expect(resolveOfficeBootstrapWorkspaceId(items, null, wsOffice2)).toBe(wsOffice2);
expect(resolveOfficeBootstrapWorkspaceId(items, null, null)).toBe(wsOffice1);
});
});
+26 -16
View File
@@ -32,8 +32,11 @@ import { useRouter, useSearchParams } from "@/lib/routing/client-router";
import {
LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE,
mapWorkspaceItem,
promoteLegacyWorkspaceSelection,
readActiveWorkspaceCookie,
readCookie,
readScopedCookie,
resolveOfficeWorkspaceId,
type OfficeWorkspaceItem,
} from "@/lib/routing/route-bootstrap";
import type { WorkspaceState } from "@/lib/state/slices/workspace/types";
import { mapUserSettingsResponse } from "@/lib/ssr/user-settings";
@@ -218,14 +221,18 @@ function useOfficeRouteBootstrap(
}
const workspaceItems = workspacesResponse.workspaces.map(mapWorkspaceItem);
promoteLegacyWorkspaceSelection(workspaceItems);
const officeWorkspaceItems = workspaceItems.filter(
(workspace) => workspace.office_workflow_id,
);
const activeWorkspaceId = resolveActiveOfficeWorkspaceId(
// Same one-time promotion as the generic boot, for the office family:
// a validated legacy office selection is copied into its scoped name so
// a ported instance stops falling back to the shared jar on every boot
// (legacy name stays untouched — default-port instances' live cookie).
promoteLegacyWorkspaceSelection(officeWorkspaceItems, LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE);
const activeWorkspaceId = resolveOfficeBootstrapWorkspaceId(
officeWorkspaceItems,
routeWorkspaceId,
readActiveWorkspaceCookie(),
readCookie(LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE),
userSettingsResponse?.settings?.workspace_id ?? null,
);
@@ -254,21 +261,24 @@ function useOfficeRouteBootstrap(
return bootstrap;
}
export function resolveActiveOfficeWorkspaceId(
workspaceItems: { id: string; office_workflow_id?: string | null }[],
/**
* Resolves the office active workspace for the client bootstrap effect from
* the live cookie jar: general family (scoped, then legacy) and office family
* (scoped, then legacy), with the route override and settings as the other
* candidates. Kept as one exported function so the effect's cookie reads are
* unit-testable without rendering the hook.
*/
export function resolveOfficeBootstrapWorkspaceId(
officeWorkspaceItems: OfficeWorkspaceItem[],
routeWorkspaceId: string | null,
activeCookieWorkspaceId: string | null,
officeCookieWorkspaceId: string | null,
settingsWorkspaceId: string | null,
): string | null {
return (
workspaceItems.find((workspace) => workspace.id === routeWorkspaceId)?.id ??
workspaceItems.find((workspace) => workspace.id === activeCookieWorkspaceId)?.id ??
workspaceItems.find((workspace) => workspace.id === officeCookieWorkspaceId)?.id ??
workspaceItems.find((workspace) => workspace.id === settingsWorkspaceId)?.id ??
workspaceItems[0]?.id ??
null
);
return resolveOfficeWorkspaceId(officeWorkspaceItems, {
routeWorkspaceId,
generalWorkspaceId: readActiveWorkspaceCookie(),
officeWorkspaceId: readScopedCookie(LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE),
settingsWorkspaceId,
});
}
type AgentRouteMatch = {
+2
View File
@@ -23,6 +23,7 @@ import { SETTINGS_DISCOVERY_ROUTE_EXCLUSIONS } from "@/lib/settings-discovery/ca
import { workspaceId, workflowId } from "@/lib/types/ids";
import type { ListWorkspacesResponse, UserSettingsResponse } from "@/lib/types/http";
import { DEFAULT_SETTINGS_PATH } from "@/lib/settings/last-settings-page";
import { scopedCookieName } from "@/lib/routing/route-bootstrap";
import {
buildSettingsInitialStateForRoute,
renderSettingsRoute,
@@ -40,6 +41,7 @@ const TASK_BEHAVIOR_PATH = "/settings/preferences/task-behavior";
describe("buildSettingsInitialStateForRoute", () => {
beforeEach(() => {
document.cookie = `${ACTIVE_WORKSPACE_COOKIE}=; path=/; max-age=0`;
document.cookie = `${scopedCookieName(ACTIVE_WORKSPACE_COOKIE)}=; path=/; max-age=0`;
});
describe("workspace selection", () => {
+2
View File
@@ -91,6 +91,7 @@ import {
} from "@/lib/routing/path";
import {
mapWorkspaceItem,
promoteLegacyWorkspaceSelection,
readActiveWorkspaceCookie,
resolveSettingsActiveWorkspaceId,
} from "@/lib/routing/route-bootstrap";
@@ -573,6 +574,7 @@ export function buildSettingsInitialStateForRoute({
userSettingsResponse,
}: SettingsInitialStateData): HydrationState {
const workspaceItems = workspaces.map(mapWorkspaceItem);
promoteLegacyWorkspaceSelection(workspaceItems);
const activeWorkspaceId = resolveSettingsActiveWorkspaceId(
workspaceItems,
readActiveWorkspaceCookie(),
+11 -1
View File
@@ -37,7 +37,11 @@ import {
} from "@/components/plugins/plugin-error-boundary";
import { PluginPageFrame } from "@/components/plugins/plugin-page";
import { safeDecodePathSegment } from "@/lib/routing/path";
import { mapWorkspaceItem, readActiveWorkspaceCookie } from "@/lib/routing/route-bootstrap";
import {
mapWorkspaceItem,
promoteLegacyWorkspaceSelection,
readActiveWorkspaceCookie,
} from "@/lib/routing/route-bootstrap";
import { resolveActiveId } from "@/lib/ssr/resolve-active-id";
import { KanbanRoute } from "./kanban-route";
import { mapUserSettingsResponse } from "@/lib/ssr/user-settings";
@@ -485,6 +489,7 @@ function useRouteData({
useEffect(() => {
if (bootstrappedRef.current) return;
promoteLegacyWorkspaceSelection(store.getState().workspaces.items);
if (skipBootstrap) return;
bootstrappedRef.current = true;
let cancelled = false;
@@ -502,6 +507,11 @@ function useRouteData({
const cookieWorkspaceId = readActiveWorkspaceCookie();
const workspaceItems =
workspacesResponse?.workspaces.map(mapWorkspaceItem) ?? store.getState().workspaces.items;
// One-time migration: a ported instance that has no scoped cookie yet
// (fresh upgrade) falls back to the legacy name on every boot; once the
// boot validates a legacy value, copy it into the scoped cookie so
// later boots are decoupled (legacy name itself stays untouched).
promoteLegacyWorkspaceSelection(workspaceItems);
const workspaceId =
workspaceItems.length > 0
? resolveActiveId(
+2 -2
View File
@@ -91,7 +91,7 @@ A self-hoster setting `KANDEV_FEATURES_OFFICE=true` in their k8s manifest beats
- A `features` slice in the Zustand store mirrors the response.
- The root layout (`apps/web/app/layout.tsx`) SSR-fetches the flags once per request and seeds `StateProvider` initialState, so the first paint reflects the deployment's flags. No flash of feature UI.
- `useFeature(name)` reads a single flag.
- Page-level gating uses Next.js `notFound()` from a server-side layout (e.g. `apps/web/app/office/layout.tsx`); nav entries use `useFeature` and render `null` when off.
- Page-level gating reads the flag from the store and renders an unavailable screen (e.g. `OfficeRoutes` in `apps/web/src/office-routes.tsx` renders `OfficeUnavailable` when `features.office` is off); nav entries use `useFeature` and render `null` when off.
### Launchers
@@ -174,6 +174,6 @@ Same pattern — pick the section that matches the knob's purpose (`mocks`, `deb
- `apps/web/app/layout.tsx` — SSR-fetch + StateProvider seeding
- `apps/web/lib/state/slices/features/` — Zustand slice
- `apps/web/hooks/domains/features/use-feature.ts` — client hook
- `apps/web/app/office/layout.tsx` — page-level `notFound()` gating
- `apps/web/src/office-routes.tsx` — office flag gating (renders `OfficeUnavailable` when off)
- `apps/backend/internal/launcher/dev.go` — sets only the `KANDEV_DEBUG_DEV_MODE` selector
- `apps/web/e2e/fixtures/backend.ts` — sets only the `KANDEV_E2E_MOCK` selector + per-host paths
+25 -1
View File
@@ -10,7 +10,31 @@ The Vite migration moved first-paint data loading from Next server components to
## Decision
Kandev will use `kandev-active-workspace` as the general browser cookie for the current active workspace. The Go boot-state builders and SPA route bootstraps read it after explicit URL workspace params and before user settings. The legacy `office-active-workspace` cookie remains a read fallback and is still written for Office compatibility during migration.
Kandev will use `kandev-active-workspace` as the general browser cookie for the current active workspace. Generic boot paths **that accept an explicit workspace URL param** (Home, Tasks, integrations) read it after those params and before user settings; **Settings resolves cookie/settings-first** (no query-param candidate, matching both the backend `settingsWorkspaceID` and the frontend settings bootstrap). Office boot paths are intentionally **cookie-first**: `officeWorkspaces` (server) and the client `OfficeRoutes` in `src/office-routes.tsx` resolve from cookies/settings without a query-param candidate, while the `OfficeRoutes` bootstrap effect honors an explicit `?workspaceId=` (the ADR 2026-08-15 exception) and converge the store client-side. The legacy `office-active-workspace` cookie remains a read fallback **for the office boot paths only**; it is no longer written (see the 2026-08-17 amendments — new writes use only the port-scoped names).
**Amended 2026-08-17 (family separation):** cookie families are read
separately. Generic boot paths (Home, Settings, Tasks, integration) read
**only the general family** — `kandev-active-workspace` / the scoped
`kandev-active-workspace_<port>` — and resolve settings/first when only an
office cookie exists. Only office boot paths (`officeWorkspaces` and the
client `OfficeRoutes` in `src/office-routes.tsx`) read the **office family**
(`office-active-workspace` / the scoped
`office-active-workspace_<port>`), as one candidate among general, office,
and settings. The backend generic reader previously consulted the legacy
office name; that candidate is removed to match the frontend generic reader.
See `docs/specs/fix-multi-instance-cookie-isolation/spec.md`.
**Amended 2026-08-17:** the cookie names are port-scoped when the instance is
served on a non-default port (`kandev-active-workspace_<port>` /
`office-active-workspace_<port>`). Both sides derive the suffix from the API
origin port: the request host server-side (`X-Forwarded-Host` precedence)
and the API base URL (`getBackendConfig().apiBaseUrl`) client-side —
`window.location.port` only equals it in same-origin deployments. Cookies
ignore port in their scope, so multiple instances on one host (same IP,
different ports) otherwise overwrite each other's active-workspace selection.
The legacy unprefixed names remain readable as a validated fallback; new
writes use only the scoped names. See
`docs/specs/fix-multi-instance-cookie-isolation/spec.md`.
The cookie stores only the workspace ID. Broader preferences and filters should not move into cookies by default: durable user settings stay in backend user/workspace settings, shareable route state stays in URL params, and purely local view state may stay in localStorage. Add another cookie only when Go must know that value before serving the SPA shell.
@@ -22,12 +22,13 @@ RPCs the plugin *calls*, plus host→plugin events and a proxied inbound webhook
(`/api/plugins/{id}/webhooks/{key}`, already on the auth public allowlist).
None of these can establish an authenticated browser session.
The architectural constraint that shaped this decision: the `kandev_session`
cookie must be set on the **HTTP response to the browser**. A `Host` gRPC RPC
runs on the go-plugin broker channel, not the browser's HTTP connection, so it
*cannot* set that cookie. The only plugin→browser HTTP path is the webhook
response. Therefore session establishment must happen on the webhook response
path, regardless of whether a new RPC exists.
The architectural constraint that shaped this decision: the session cookie
(name derived from the request host — base name `kandev_session`) must be set
on the **HTTP response to the browser**. A `Host` gRPC RPC runs on the
go-plugin broker channel, not the browser's HTTP connection, so it *cannot*
set that cookie. The only plugin→browser HTTP path is the webhook response.
Therefore session establishment must happen on the webhook response path,
regardless of whether a new RPC exists.
## Decision
@@ -44,7 +45,7 @@ a reserved header `X-Kandev-Auth-Login` whose value is a JSON assertion
not silently ignored.
3. Calls `auth.Service.AuthenticateExternal`, which maps the assertion to a
user (existing identity → link-by-email → JIT-provision a **member**),
mints a session, and the host sets the `kandev_session` cookie itself. The
mints a session, and the host sets the session cookie itself. The
email-linking step is trust-sensitive: the plugin **MUST** only assert an
email the IdP verified as owned by the subject, otherwise a spoofed email
claim is an account takeover. As defense-in-depth the host **refuses to
@@ -38,8 +38,10 @@ a login screen or any behavioral change.
— deleted task/workspace row, or an account since deleted or disabled —
denies the dispatch. Disabling a user revokes their sessions and PATs, so
their still-running agent session must lose this surface too.
3. **Opaque DB-backed credentials, not JWTs.** Sessions (`kandev_session`
HttpOnly SameSite=Lax cookie) and personal access tokens (`kandev_pat_*`)
3. **Opaque DB-backed credentials, not JWTs.** Sessions (HttpOnly SameSite=Lax
cookie, base name `kandev_session`, effective name derived from the request
host — port-scoped on a ported host so instances on one host stay isolated)
and personal access tokens (`kandev_pat_*`)
are 256-bit random values stored as SHA-256 digests. Instant revocation
(user disable, logout-all) outweighs stateless verification at kandev
scale. The office agent HMAC-JWT remains a separate machine credential.
@@ -23,10 +23,15 @@ route-owned loading.
## Decision
The active workspace decides the mode. The URL never does. When a route and
the active workspace disagree, the workspace wins and the URL follows: the
The active workspace decides the mode. The URL never does — **with one
explicit exception (amended 2026-08-17): an explicit `?workspaceId=` query
param on the office page is honored at page bootstrap** (route-first
resolution, matching ADR 0023's URL-params precedence), because the office
page resolves its data workspace from the URL. Navigation without an
explicit param cannot change the active workspace; when a route and the
active workspace disagree, the workspace wins and the URL follows (the
kanban board route redirects to the workspace's Office home instead of
reassigning the workspace.
reassigning the workspace).
Mode resolves through a `WorkspaceScopeProvider` context rather than direct
store reads, with one provider at the app root. Mode is tri-state:
@@ -61,8 +66,10 @@ dashboards) render under the active workspace's chrome; they do not redirect.
settings fallback, so a workspace activated only by visiting a URL (never
explicitly selected) can snap back. Unchanged from before, minus the kanban
bias.
- The legacy `office-active-workspace` cookie keeps its ADR-0023 role: written
on office selections, read by the office boot paths.
- The legacy `office-active-workspace` cookie keeps its ADR-0023 role as a
read-only fallback for the office boot paths; office selections now write
the port-scoped name (amended 2026-08-17, see
`docs/specs/fix-multi-instance-cookie-isolation/spec.md`).
## Alternatives Considered
@@ -0,0 +1,298 @@
---
spec: docs/specs/fix-multi-instance-cookie-isolation/spec.md
created: 2026-08-17
status: pending
---
# Implementation Plan: Isolate Kandev Cookies Between Instances on One Host
## Root cause (confirmed)
Cookies are scoped by scheme + host only; the browser ignores port when
deciding which cookies to send. Multiple kandev instances on one IP (different
ports) therefore share one cookie jar, and kandev stores per-instance identity
in host-scoped cookies:
- `kandev_session` (auth token): last login wins; every other auth-enabled
instance rejects the foreign token (per-instance session store) and 401s,
and the SPA's `onUnauthorized` handler clears auth state and redirects to
`/login`. Reproduced live: two auth-enabled instances on :48429/:48529 each
return `{"authenticated":false}` for the other's token, and logging into
one yanks the other's open UI to the Sign in page. Maintainer-documented in
#2689.
- `kandev-active-workspace` / `office-active-workspace`: foreign workspace ids
are read at boot by every other instance. Both sides validate and fall
back today, so this path is graceful, but it churns cross-instance
workspace/mode selection and is the same unsegregated-storage class.
Fix: port-scope the cookie **names** (suffix `_<port>`), derived from the
API origin port on both sides — request Host / `X-Forwarded-Host` (backend)
and `getBackendConfig().apiBaseUrl` (frontend; `window.location.port` only
equals it in same-origin deployments). Legacy unprefixed workspace cookies
stay readable (validated fallback); the session cookie has no fallback (one
re-login, bug stays dead during migration).
## Changes
### Backend
- **New package `apps/backend/internal/common/httpcookie`**: `PortSuffix(r)`
and `ScopedName(r, base)`; honors `X-Forwarded-Host` (first value) before
`Host`; no suffix when the host has no port; IPv6 bracketed hosts handled.
Unit tests. Shared by the auth service and the boot-state builder.
- **Session cookie scoping** (`apps/backend/internal/auth`): login/setup/
logout handlers (`httpapi/cookie.go`, `handlers.go`), invite accept
(`handlers_admin.go` — there is no separate admin-login handler), the
auth middleware
(`httpmw/middleware.go`), and the plugin SSO bridge (`backendapp/auth.go`)
resolve the cookie name from the request via a new request-aware service
method `CookieNameForRequest(r)`. The config default for `auth.cookieName`
becomes **empty** (the service keeps the `kandev_session` base fallback, so
the effective name is unchanged for default deployments); a non-empty
configured value is returned verbatim, an empty one is port-suffixed. The
gateway production code does **not** read the session cookie (it only
handles the path-scoped `kandev_port_proxy` capability); its
`svc.CookieName()` uses are test request headers in
`gateway/websocket/port_proxy_auth_test.go` and must be updated to the
scoped name for their request Host.
- **Workspace cookie scoping** (`backendapp/boot_state_routes.go`):
`readActiveWorkspaceCookie` reads the scoped names first, then the legacy
unprefixed names. All downstream `firstValidID` validation is unchanged.
The suffix comes from the request Host (XFH precedence) — the same port
the SPA derives from the API base URL.
### Frontend
- `apps/web/lib/routing/route-bootstrap.ts`: add `scopedCookieName(name,
port?)` / `readScopedCookie(name, port?)` — the port defaults to the API
origin port from `getBackendConfig().apiBaseUrl` (not
`window.location.port`, which mismatches in split-origin dev), and the
explicit parameter makes the helpers pure and unit-testable without
stubbing; legacy fallback. `readActiveWorkspaceCookie` and the office read
path use it.
- `apps/web/components/app-sidebar/app-sidebar-workspace-navigation.ts`:
`writeWorkspaceCookie` writes the scoped name (same API-origin port).
- Server-component reads that go through `readCookies()`/`cookieStore`:
`apps/web/app/page.tsx`, `apps/web/app/office/layout.tsx`,
`apps/web/app/settings/layout.tsx`,
`apps/web/app/office/lib/get-active-workspace.ts` (not
`lib/get-active-workspace.ts`), and the separate legacy read in
`apps/web/src/office-routes.tsx` read the scoped name first, legacy
fallback.
### Docs
- **Deployment note** (`docs/public/authentication.md`): multiple
auth-enabled instances on one host are isolated per port; the proxy MUST
preserve the browser **hostname** — either preserve the full `Host`
(host:port) or rewrite only the port and forward a correct
`X-Forwarded-Host` (the CORS/WS origin gate compares `Origin` to `Host`
and ignores XFH, so rewriting a non-loopback hostname 403s before auth). A custom
`auth.cookieName` does not solve or alter the origin gate (it compares
hostnames, independent of cookie names) — such deployments must still use
a compliant Host/Origin setup, and the custom name disables automatic port
isolation (must be unique per cookie host). **Session-cookie
migration**: old auth-enabled builds conflict with other old builds; an
upgraded instance ignores the legacy session token and requires one
re-login; workspace selections keep their validated legacy read fallback.
- **Stale references** (ADR 0050, ADR
2026-07-24-opt-in-authentication, `apps/backend/AGENTS.md`,
`apps/backend/internal/auth/service_sso.go`,
`apps/backend/internal/plugins/auth_login.go`,
`apps/backend/internal/auth/store/models.go`): wording that pins the
literal `kandev_session` cookie name becomes "the session cookie (name
derived from the request host)".
- Already amended with this package: `docs/specs/auth/spec.md`,
`docs/decisions/0023-active-workspace-cookie.md`,
`docs/public/plugins-authoring.md`.
## Tests
Regression tests that must fail before the change:
- **Backend, session cookie** (`auth/httpapi/handlers_test.go` +
`httpmw/middleware_test.go`): login via a request with Host
`127.0.0.1:8443` sets `kandev_session_8443`; a request carrying only the
unprefixed `kandev_session` cookie is unauthenticated; a request carrying
the scoped cookie authenticates. Pre-fix: only `kandev_session` exists, so
the scoped assertions fail.
- **Backend, session set/clear coverage**: setup, login, logout, invite
accept (there is no separate admin-login handler — the first admin's
setup/login flows through `handlers.go`), and plugin SSO all set/clear the
scoped name; a
configured custom `auth.cookieName` stays verbatim (no suffix) on the same
ported host. Gateway `port_proxy_auth_test.go` request headers use the
scoped name for their Host.
- **Backend, config-default regression**: with the **loaded** default config
(empty `auth.cookieName`), login on a ported Host still sets
`kandev_session_<port>`; a seeded non-empty default must not suppress
suffixing. Custom-name tests must exercise both an empty config and an
explicitly configured name.
- **Backend, env contract**: `auth.cookieName` gets an explicit
`BindEnv("auth.cookieName", "KANDEV_AUTH_COOKIE_NAME")` (the automatic
camelCase mapping would otherwise expose the undocumented
`KANDEV_AUTH_COOKIENAME`). Precedence tests: loaded default (empty),
config.yaml custom value, env custom value, env-over-file.
- **Backend, conflicting Host/XFH**: resolver regression — Host
`public.example:8443` + `X-Forwarded-Host: public.example:9443` yields
`_9443` (XFH wins; pinned as the proxy-misconfiguration contract).
- **Backend, custom-name negative**: two routers on one cookie host with the
**same** configured custom name still conflict (documented exception —
custom names disable automatic port isolation); the test pins the
documented behavior.
- **Backend, mixed-version coverage**: tier 1 failing-before — ported Host
with a valid token under the unprefixed name 401s (old→new rejection);
re-upgrade — login writes the scoped name and a scoped request
authenticates. Tier 1b invariant back-compat guards — rollback (no scoped
cookie, scoped request 401s, 401 both sides) and no-port unprefixed
authentication (identical both sides) protect against post-change
regressions. Tier 2 — old-old conflict and the old side's unprefixed
success are old-build wire behaviors, documented in the spec and
explicitly NOT faked by a synthetic legacy adapter.
- **Backend, legacy-absence**: every session set/clear path (setup, login,
logout, invite accept, plugin SSO) asserts the exact
Set-Cookie name set contains only the scoped name — no unprefixed
`kandev_session` emitted; positive-only assertions would miss an
implementation emitting both names.
- **Frontend, boot-reader coverage**: the four CookieStore readers
(`app/page.tsx`, `app/office/layout.tsx`, `app/settings/layout.tsx`,
`app/office/lib/get-active-workspace.ts`) must use
`readScopedCookieStoreValue`; the sync office effect (`office-routes.tsx`)
uses the document-cookie `readScopedCookie` (both share `scopedCookieName`).
A structural guard test asserts both the absence of direct lookups —
literal names **or** the exported constants — (negative) and the presence
of each file's mandated helper reference (positive), so a boot path cannot
silently stay unscoped (task 04).
- **Backend, plugin SSO bridge**: the real bridge (`backendapp/auth.go`)
sets the scoped name for a ported Host; the existing fake-bridge test
(`plugins/auth_login_test.go`, which hardcodes `kandev_session`) is not
the only coverage.
- **Backend, two-instance isolation** (integration, `auth` package or
`backendapp`): two routers with different request Hosts and independent
stores; logging into A authenticates only `kandev_session_<portA>`; B
rejects A's cookie and authenticates only its own; workspace cookie reads
in `boot_state_routes.go` resolve per-Host with both scoped cookies in the
jar (non-first fixtures, failing-before).
- **Backend, proxy contract**: full-router tests — the CORS/WS origin gate
(`httpmw.AllowedOrigin`) compares `Origin` to `r.Host` hostnames and
ignores ports and `X-Forwarded-Host`. Three cases: preserved `Host`
(`public.example:8443`) reaches login — **reachability is invariant**
(current code authenticates under a preserved Host), so the failing-before
assertion is the paired `Set-Cookie: kandev_session_8443`; **same-hostname
port rewrite** (`Host: public.example:38429` + `XFH: public.example:8443`)
passes the gate — the failing-before assertion is the cookie resolver
deriving `_8443` from XFH; **non-loopback hostname rewrite**
(`Host: internal:38429`, a different non-loopback hostname) is rejected
403 before auth — invariant branch. The 403 fixture uses a different
non-loopback hostname, never a different port; loopback-alias rewrites
pass the existing gate and are unchanged.
- **Backend, workspace cookie** (`backendapp/boot_state_workspace_test.go`):
`readActiveWorkspaceCookie` with Host `127.0.0.1:8443` prefers
`kandev-active-workspace_8443` over the unprefixed name, and falls back to
the legacy name when no scoped one exists. Pre-fix: the scoped name is
never read. **Family separation**: the general reader ignores the
office-family cookies (pre-change the backend generic reader consults the
legacy office name — fails pre-change); `readOfficeWorkspaceCookie` reads
the office family only; backend/frontend parity tests.
**Downstream regression** (scenario 3): through
`bootPayload`/resolver — invariant/back-compat (valid unprefixed legacy id
selected when no scoped cookie exists; foreign/invalid legacy id falls
through to the instance-owned fallback) and failing-before
(scoped-over-legacy precedence when both exist).
**Office precedence**: canonical frontend resolver (route → general-if-office-valid → office → settings → first, with `getActiveWorkspaceId` passing its URL override; wrappers pass null only when none exists; convergence is client-eventual via the OfficeRoutes bootstrap effect; route is a client/page-only candidate — backend boot payload and server layout are cookie-first by design). The backend Go resolver maps the general/office/settings vectors (settings wired from `b.userSettings`), regression-tested through `officeWorkspaces`/`addOfficeRouteState` with distinct valid O1/O2, office-vs-settings, and office-absent cases; a downstream generic-route regression (every generic `RouteName` that resolves an active workspace id — Unknown, Home, Tasks, Settings, integrations, Stats — plus the quick-chat fallback, with only office cookies → settings/first; TaskDetail asserted separately via routeData/task-workspace, not the settings/first matrix) pins the family separation (tasks 03/04).
- **Frontend, cookie helpers** (`apps/web/lib/routing/route-bootstrap.test.ts`,
`apps/web/components/app-sidebar/app-sidebar-workspace-navigation.test.ts`):
`scopedCookieName(name, port)` is pure — tests pass `"8443"` explicitly and
assert the `kandev-active-workspace_8443` read/write plus legacy fallback
(no jsdom Location stubbing required). A split-origin regression asserts
the default port comes from the API base URL (`:38429`) and not from
`window.location.port` (`:37429`). **Legacy-absence**: the sidebar write
tests (`app-sidebar-workspace-navigation.test.ts` and
`app-sidebar-workspace-picker.test.tsx` — the picker drives the same
`rememberWorkspaceSelection` path and today asserts unprefixed writes)
assert `rememberWorkspaceSelection` does NOT write the unprefixed names
(legacy read fallback stays; no new legacy writes).
- **E2E** (`apps/web/e2e/tests/...`): auth project asserts the login
response sets `kandev_session_<port>`; the workspace-switch spec asserts
`kandev-active-workspace_<port>` is written on selection. The Playwright
fixture runs one backend per worker (no second backend), so the
two-instance behavioral regression is proven by the Go integration test
above; a two-backend Playwright fixture is explicitly out of scope.
## Implementation Waves And Parallel Candidates
Execution stays sequential in the primary conversation. Waves are a human
decision aid; only disjoint tasks are labelled parallel-safe.
Wave 1:
- [x] [task-01-shared-port-cookie-helper](task-01-shared-port-cookie-helper.md)
- [x] [task-04-workspace-cookie-port-scope-frontend](task-04-workspace-cookie-port-scope-frontend.md)
`task-01` (Go helper) and `task-04` (frontend) touch disjoint trees and
contracts; parallel-safe.
Wave 2:
- [x] [task-02-session-cookie-port-scope-backend](task-02-session-cookie-port-scope-backend.md)
- [x] [task-03-workspace-cookie-port-scope-backend](task-03-workspace-cookie-port-scope-backend.md)
Both consume `httpcookie` from `task-01`; disjoint files (auth vs
boot-state), parallel-safe after Wave 1.
Wave 3:
- [x] [task-05-e2e-cookie-scope-assertions](task-05-e2e-cookie-scope-assertions.md)
- [x] [task-06-docs-and-stale-references](task-06-docs-and-stale-references.md)
Task 05 depends on the shipped behavior of tasks 02 and 04. Task 06 (docs
only) is parallel-safe with 05.
## Validation commands
```bash
make fmt
cd apps/backend && go test ./internal/common/config/... ./internal/common/httpmw/... ./internal/auth/... ./internal/backendapp/... && make lint
cd apps && pnpm --filter @kandev/web test -- lib/routing/route-bootstrap.test.ts components/app-sidebar/app-sidebar-workspace-navigation.test.ts
cd apps/web && pnpm run typecheck && pnpm run lint
cd apps/web && pnpm e2e:raw --project=auth # or the auth project's exact command
```
## Invariant-negative pairing
The non-loopback-hostname-rewrite 403 and same-custom-name-conflict tests are invariant
branches that pass before the fix too; pair each with a change-specific
assertion (the XFH suffix derivation, the scoped Set-Cookie name) so the
suite still fails pre-change where a scenario demands it.
## Risks
- The proxy contract is the trap: the CORS/WS origin gate compares `Origin`
to `r.Host` hostnames and ignores ports and XFH, so the deployment rule is
"the proxy MUST preserve the browser Origin **hostname**". Compliant:
preserved `Host` (full host:port), or a same-hostname port rewrite with a
`X-Forwarded-Host` carrying the browser host:port (the resolver takes
the public port from XFH). Only a **non-loopback hostname** rewrite 403s
before auth (loopback-alias rewrites like `localhost` → `127.0.0.1` pass
the gate by existing `AllowedOrigin` design and stay unchanged); neither
XFH nor `auth.cookieName` can pass the gate, and
`AllowedOrigin` must not be weakened to trust XFH (CSRF boundary). When
Host and XFH conflict on port, XFH wins for cookie naming (pinned by a
resolver regression test).
- One-time re-login after upgrade for every auth-enabled instance. Accepted
tradeoff; the alternative (legacy fallback) resurrects the cross-instance
bleed during mixed-version periods.
- The `kandev_session` cookie name is referenced by gateway **tests**
(`port_proxy_auth_test.go`); every read/set site must use the scoped name
or WS/port-proxy auth tests break. Production gateway code only handles
the path-scoped `kandev_port_proxy` capability cookie and needs no change.
- Changing the `auth.cookieName` config default to empty must not change the
effective name for default deployments (the service keeps the base
fallback); any fixture or docs that assert the config value itself needs a
review (task 06 covers docs).
- Split-origin dev is the trap: any frontend port derivation not based on
the API origin silently degrades to the legacy fallback. The split-origin
regression test is the guard.
- Custom `auth.cookieName` values disable automatic port isolation; the
documented exception and the negative test keep this from being
rediscovered as a "fix".
@@ -0,0 +1,76 @@
---
id: "01-shared-port-cookie-helper"
title: "Shared port-scoped cookie name helper"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/fix-multi-instance-cookie-isolation/spec.md"
---
# Task 01: Shared port-scoped cookie name helper
## Acceptance
- `apps/backend/internal/common/httpcookie` exposes
`PortSuffix(r *http.Request) string` and
`ScopedName(r *http.Request, base string) string`:
- `ScopedName(r, "kandev_session")` returns `kandev_session_8443` when the
request host carries port 8443, and `kandev_session` when it does not.
- `X-Forwarded-Host` (first value) wins over `Host`; a bracketed IPv6 host
(`[::1]:8080`) yields `_8080`; an empty/malformed host yields no suffix.
- Unit tests cover every branch: Host port, no port, X-Forwarded-Host
precedence, comma-separated and whitespace-padded `X-Forwarded-Host`
(first value only), IPv6 bracket and zone-id forms (`[fe80::1%25eth0]:8080`
style), malformed/default-port hosts, nil request (no suffix), empty base.
**Port validation**: the suffix requires a decimal port in 1..65535 —
nonnumeric service names (`example.com:http`) and out-of-range values
(`example.com:99999`) yield no suffix. **Empty base**: `ScopedName(r, "")`
returns the empty string (a suffix is meaningless without a base name) —
the empty-base test asserts exactly that. A **conflicting Host/XFH test**
pins the precedence contract: Host `public.example:8443` +
`X-Forwarded-Host: public.example:9443` yields `_9443` (XFH wins; a
misconfigured proxy is the deployment's responsibility, not the
resolver's).
- The helper is a pure suffixing function: it never knows about config, so a
caller must not feed it a configured custom cookie name.
- `gofmt` clean; `make lint` in `apps/backend` passes.
## Verification
```bash
cd apps/backend && go test ./internal/common/httpcookie/... && go vet ./internal/common/httpcookie/...
```
## Files likely touched
- `apps/backend/internal/common/httpcookie/httpcookie.go` (new)
- `apps/backend/internal/common/httpcookie/httpcookie_test.go` (new)
## Dependencies
None. This is the shared contract both backend scoping tasks import.
## Parallelism
Parallel-safe with `task-04` (frontend, disjoint tree).
## Inputs
- Spec: `What` (port-scoped names, X-Forwarded-Host precedence) and
`Failure modes` (proxy, IPv6).
- Existing pattern: `apps/backend/internal/auth/httpapi/cookie.go`
`requestIsTLS` (X-Forwarded-Proto handling).
## Risks
- Keeping suffix derivation in one place is the point; do not inline it in
callers. The helper must not parse `X-Forwarded-Host` values that contain
multiple hosts (take the first, trimmed). The custom `auth.cookieName`
verbatim rule lives in the auth service (`CookieNameForRequest`), never in
this helper.
## Output contract
Report the helper API, changed files, exact commands and results,
blockers/risks, then mark this task `done` and update `plan.md`.
@@ -0,0 +1,194 @@
---
id: "02-session-cookie-port-scope-backend"
title: "Port-scope the session cookie (backend)"
status: done
wave: 2
depends_on: ["01-shared-port-cookie-helper"]
plan: "plan.md"
spec: "../../specs/fix-multi-instance-cookie-isolation/spec.md"
---
# Task 02: Port-scope the session cookie (backend)
## Acceptance
- The auth service gains a request-aware name resolver,
`CookieNameForRequest(r *http.Request) string`. The config default for
`auth.cookieName` becomes **empty** (currently seeded to
`kandev_session` in `common/config/config.go`); the service keeps the
`kandev_session` base fallback internally so the effective name for
default deployments is unchanged. A non-empty configured value is returned
verbatim (never suffixed); an empty one is returned via
`httpcookie.ScopedName(r, baseName)`. The request-less `CookieName()`
stays for contexts without a request (tests).
- Every production set/clear/read site resolves the name from the request:
setup, login, logout, **invite accept**, and the plugin SSO bridge
(`auth/httpapi/handlers.go`, `handlers_admin.go` — invite accept; there is
no separate admin-login handler — the first admin's setup/login flows
through `handlers.go`), the auth middleware read
(`auth/httpmw/middleware.go`), and the plugin SSO bridge
(`backendapp/auth.go`). Gateway production code does **not** read
the session cookie (only the path-scoped `kandev_port_proxy` capability);
the `svc.CookieName()` uses in `gateway/websocket/port_proxy_auth_test.go`
are test request headers and must use the scoped name for their Host.
- A request carrying only the legacy unprefixed `kandev_session` cookie is
**not** authenticated (no fallback).
- Regression tests, failing pre-change:
- `auth/httpapi/handlers_test.go`: login with Host `127.0.0.1:8443` sets
`kandev_session_8443`; logout clears the scoped name; invite accept and
setup (the first admin's login) set it; a subsequent authenticated call
must carry the scoped cookie; the unprefixed cookie alone yields 401.
- **Config-default regression**: with the **loaded** default config (empty
`auth.cookieName`), login on the same ported Host still sets
`kandev_session_8443`; a seeded non-empty default must not suppress
suffixing. Custom-name tests cover both an empty config and an
explicitly configured `auth.cookieName = "my_session"` (verbatim, no
suffix).
- Custom-name tests: parameterize the `apiClient` fixture's session-cookie
capture (currently filters `strings.Contains(name, "kandev_session")`,
which discards `my_session`); give the fixture a configurable expected
prefix (default `kandev_session`) or capture the exact `Set-Cookie` name
from the response, so a custom-name login authenticates its subsequent
request and asserts verbatim behavior through the same middleware path.
- **Env contract**: add `_ = v.BindEnv("auth.cookieName",
"KANDEV_AUTH_COOKIE_NAME")` in `common/config/config.go` (AutomaticEnv's
camelCase mapping would expose the undocumented `KANDEV_AUTH_COOKIENAME`);
precedence tests: loaded default (empty), config.yaml custom, env custom,
env-over-file.
- Proxy contract: full-router tests, distinguishing hostname rewrite from
port-only rewrite (the CORS gate compares hostnames and ignores ports):
**(a) preserved Host** `public.example:8443` + `Origin:
https://public.example:8443` reaches login and authenticates —
**reachability is invariant** (current code authenticates under a
preserved Host), so the failing-before assertion is the paired
`Set-Cookie: kandev_session_8443` on the response; **(b)
same-hostname port rewrite** — `Host: public.example:38429` +
`X-Forwarded-Host: public.example:8443` + `Origin:
https://public.example:8443` — passes the origin gate (hostname match),
and the **failing-before assertion is the cookie resolver deriving
`_8443` from XFH**; **(c) non-loopback
hostname rewrite** — `Host: internal:38429` (a different non-loopback
hostname) + `X-Forwarded-Host: public.example:8443` + `Origin:
https://public.example:8443` — rejected 403 by the origin gate before
auth (invariant branch). The 403 fixture must use a DIFFERENT
non-loopback hostname, not a
different port; loopback-alias rewrites (`localhost` → `127.0.0.1`) pass
the gate by existing `AllowedOrigin` design and are kept unchanged (not
regression-tested as a change).
- Custom-name negative: two routers on one cookie host with the **same**
configured custom name still conflict (documented exception: custom
names disable automatic port isolation); the test pins the documented
behavior.
- Mixed-version coverage, split into a failing-before regression tier, an
invariant back-compat tier, and a documented-limitation tier (a
synthetic legacy adapter would test nothing real, so old-build wire
behavior is not faked):
- **Tier 1 — failing-before regressions** (must fail before / pass
after): on a ported Host, a **valid** token carried under the
unprefixed `kandev_session` name is rejected 401 (old→new rejection —
pre-change the middleware reads the unprefixed name and authenticates);
re-upgrade — login on a ported Host writes `kandev_session_<port>` and
a scoped request authenticates (pre-change the scoped name is never
read → 401). All exercised through the real handlers/middleware/stores.
- **Tier 1b — invariant back-compat guards** (pass both sides; protect
against post-change regressions, not proof of the change): rollback —
no scoped cookie exists, so a scoped request 401s (401 both sides);
no-port Host — the unprefixed token still authenticates (pre-change and
post-change identical).
- **Tier 2 — documented limitations (spec only, not regression tests)**:
old-old conflict and the old side's unprefixed-session success are
wire behaviors of old binaries that current code cannot exhibit; the
spec documents them and this suite explicitly does not fake them.
- **Legacy-absence assertions** (negative, fail-before): every session
set/clear path — setup, login, logout, invite accept, plugin SSO —
asserts the **exact Set-Cookie name set** contains only the
scoped name (no unprefixed `kandev_session` emitted); a positive-only
assertion would let an implementation emit both names and retain the
cross-instance bleed.
- Two-instance isolation integration test (two routers, independent
stores, Hosts `127.0.0.1:8443` / `127.0.0.1:9443`): login on A
authenticates only A; B rejects A's scoped cookie; login on B keeps A's
session intact; each request authenticates only with its own port's
cookie name.
- `httpmw/middleware_test.go`: middleware resolves the scoped name; a
foreign-port token (`kandev_session_9443`) is rejected.
- **Plugin SSO bridge**: a **real bridge regression** — drive
`LoginExternal` (or the plugin webhook relay path) through
`backendapp/auth.go` with a Gin request Host `127.0.0.1:8443` and assert
the response sets `kandev_session_8443`; plus a custom-name verbatim
case. A resolver-output test alone is insufficient: a stale bridge call
to `b.auth.CookieName()` would pass resolver tests while emitting the
plain name for ported SSO. The existing fake-bridge test
(`plugins/auth_login_test.go`, which hardcodes `kandev_session`) must
not be the only coverage.
- Default-port request path: Host `example.com` (no port) — login sets
the plain `kandev_session`, the middleware authenticates with it, and
logout clears it (the no-port branch exercised through real handlers,
not just the helper).
- `gateway/websocket/port_proxy_auth_test.go`: request headers carry
`kandev_session_<port>` for the fixture Host.
## Verification
```bash
cd apps/backend && go test ./internal/common/config/... ./internal/common/httpmw/... ./internal/auth/... ./internal/backendapp/... ./internal/gateway/websocket/... && make lint
```
## Files likely touched
- `apps/backend/internal/common/config/config.go` (auth.cookieName default → empty; BindEnv `KANDEV_AUTH_COOKIE_NAME`)
- `apps/backend/internal/auth/service.go` (new `CookieNameForRequest`)
- `apps/backend/internal/auth/httpapi/cookie.go`
- `apps/backend/internal/auth/httpapi/handlers.go`
- `apps/backend/internal/auth/httpapi/handlers_admin.go`
- `apps/backend/internal/auth/httpapi/handlers_test.go`
- `apps/backend/internal/auth/httpmw/middleware.go`
- `apps/backend/internal/auth/httpmw/middleware_test.go`
- `apps/backend/internal/backendapp/auth.go` (plugin SSO bridge)
- `apps/backend/internal/gateway/websocket/port_proxy_auth_test.go`
- `apps/backend/internal/common/config/config_test.go` (default + env precedence)
- `apps/backend/internal/common/httpmw/origin_test.go` (proxy boundary, if it lives with the origin policy)
## Dependencies
`httpcookie` from task 01.
## Parallelism
Disjoint files from `task-03`; parallel-safe after Wave 1.
## Inputs
- Spec: `What` (session cookie scoping, `CookieNameForRequest`, no legacy
fallback), `Scenarios` (first, fourth, fifth, proxy), `Failure modes`
(proxy, mixed-version).
- Plan: `Backend > Session cookie scoping`, `Tests`.
## Risks
- Missing a set/clear site (invite accept and the plugin bridge were the
gaps found in review) leaves that flow writing the unprefixed name; the
acceptance list is exhaustive — grep `CookieName()`, `setSessionCookie(`,
and `b.auth.CookieName` to prove no stragglers.
- The seeded non-empty config default is the trap: `CookieNameForRequest`
must distinguish "empty config" (suffix the base name) from "explicitly
configured" (verbatim). The loaded-config regression test guards this.
- The CORS/WS origin gate compares `Origin` hostnames to `r.Host` and
ignores ports and XFH; do not weaken `AllowedOrigin` to trust XFH in this
fix (CSRF boundary). The deployment contract is "proxy preserves the
hostname": preserved Host passes, same-hostname port rewrite + correct
XFH passes (resolver takes the public port from XFH), non-loopback
hostname rewrite 403s (loopback aliases pass by existing design); the
full-router test proves all three.
- Custom-name negative test pins the documented exception: same custom name
on one cookie host = conflict by design.
- The custom-name rule must live in `CookieNameForRequest`, not the generic
helper, or configured deployments silently get suffixed names.
- The logout/clear path must use the same scoped name as login.
## Output contract
Report the scoped-name coverage (every set/read site), the custom-name and
proxy tests, the two-instance integration test, changed files, exact
commands and results, blockers/risks, then mark this task `done` and update
`plan.md`.
@@ -0,0 +1,161 @@
---
id: "03-workspace-cookie-port-scope-backend"
title: "Port-scope workspace cookie reads (backend)"
status: done
wave: 2
depends_on: ["01-shared-port-cookie-helper"]
plan: "plan.md"
spec: "../../specs/fix-multi-instance-cookie-isolation/spec.md"
---
# Task 03: Port-scope workspace cookie reads (backend)
## Acceptance
- `readActiveWorkspaceCookie(req)` in
`apps/backend/internal/backendapp/boot_state_routes.go` (not
`boot_state.go`) reads **only the general family**: scoped
`kandev-active-workspace_<port>` first, then the legacy unprefixed general
name — the office-family cookies are removed from this reader. This
aligns the backend generic boot with the frontend generic reader (which
never consults office cookies): with only an office cookie present, both
sides resolve settings/first instead of the backend picking an office
workspace. Value validation (`firstValidID` against the instance's
workspace set) is unchanged.
- New `readOfficeWorkspaceCookie(req)` reads **only the office family**:
scoped `office-active-workspace_<port>` first, then the legacy unprefixed
office name — never the general cookie. Parity tests: backend and
frontend generic readers ignore office-family cookies; the office reader
ignores the general family.
- **Office resolver-specific precedence** (fixes a pre-existing gap on the
touched surface): `officeWorkspaces` today passes ONE value
(`readActiveWorkspaceCookie(req)`) into `resolveActiveOfficeWorkspaceID`,
so when the general cookie names a kanban workspace the retained office
cookie is never consulted and office boot falls back to the first office
workspace. Add `readOfficeWorkspaceCookie(req)` (office-scoped first, then
legacy office name — never the general cookie) and pass THREE named
candidates into the office resolver — general, office, **settings** — each
validated against the office workspace set: general (when it names an
office workspace) → office cookie → settings → first office workspace. The
settings candidate is wired explicitly: `officeWorkspaces` loads
`b.userSettings(ctx)` (the same source `settingsWorkspaceID` uses, via
`b.p.userCtrl.GetUserSettings`) and passes `settings.Settings.WorkspaceID`.
The kanban/settings resolvers keep `readActiveWorkspaceCookie` as-is.
**Scope of the precedence contract**: `route` is a client/page-only
candidate — the backend boot payload and server layout are **cookie-first
by design** (no query-param candidate; `officeWorkspaces` does not read
query params today and that is unchanged). The route-first behavior
belongs to the frontend page bootstrap (`getActiveWorkspaceId`) and the
client `OfficeRoutes` effect, which converges the store after the
cookie-first server paint; the ADR 2026-08-15 query-param exception is
scoped to those page/bootstrap paths. Backend office resolution passes
exactly the three candidates (general, office, settings).
- Regression tests, failing pre-change
(`boot_state_workspace_test.go` / `helpers_test.go`): a request with Host
`127.0.0.1:8443` carrying `kandev-active-workspace_8443=<id>` returns that
id; carrying only the unprefixed `kandev-active-workspace=<other-id>`
falls back only when no scoped cookie exists. **Family separation**: the
general reader ignores `office-active-workspace_8443` and the legacy
office name (pre-change the backend generic reader consults the office
name — fails pre-change); the office reader ignores the general family.
- Per-Host isolation: **model the browser jar** — each request carries BOTH
scoped cookies (`kandev-active-workspace_8443` = distinct non-first
workspace A and `kandev-active-workspace_9443` = distinct non-first
workspace B), and Host `127.0.0.1:8443` resolves A while Host
`127.0.0.1:9443` resolves B. Failing-before: pre-change the reader ignores
all scoped names, so both requests resolve the first workspace — with
non-first A/B the assertion fails. (A request carrying only the other
port's cookie would pass pre-change too, so that shape is not the
regression.)
- **Downstream boot-state/resolver regression** (scenario 3, observable
behavior). Two classes: **(invariant/back-compat, pass both sides)** with
no scoped cookie present, a **valid** unprefixed legacy workspace id is
selected by the boot-state resolver (`firstValidID` picks it — current
behavior, guarded against regression) and a **foreign or invalid** legacy
id falls through to the instance-owned fallback (first workspace) — also
current behavior; **(failing-before)** when both a scoped and a legacy
cookie exist, the scoped value wins (pre-change the scoped name is never
read). A raw-reader-only test could pass while boot-state selection
mishandles fallback, so the assertions run through
`bootPayload`/`readActiveWorkspaceCookie` + resolution, not just the raw
reader.
- **Downstream generic-route regression** (family separation, observable):
table-driven full boot-state tests through `bootPayload`/`bootInitialState`
over the generic routes **that resolve an active workspace id** (`webapp.RouteName`: Unknown, Home, Tasks, Settings, GitHub, GitLab, Jira, Linear, Stats — Office and TaskDetail excluded) with only a scoped `office-active-workspace_<port>` cookie and with only a legacy office cookie: the resolved active id is settings/first, never the office id; assert `initialState` and `routeData` where applicable, and cover the quick-chat boot fallback (`boot_state.go` quick-chat path) separately. Classification: the **legacy-office row fails before the change** (the old generic reader consults the legacy office name); the **scoped-office row is an invariant guard** (the scoped name never existed pre-change — it already fell through) and is paired with the legacy row or another changed call-site assertion for the failing-before signal. A raw reader test alone does not prove the call sites in `boot_state_routes.go` and `boot_state.go` stopped selecting office ids.
- **TaskDetail is asserted separately, not in the settings/first matrix**:
`bootInitialState` has no task-detail workspace resolver — task detail state is emitted as `routeData` by `taskDetailRouteData` and quick-chat deliberately follows the task's workspace, so there is no activeId/settings-or-first value to assert for a normal TaskDetail request. The test asserts task-detail `routeData`/task workspace is task-derived (not cookie-derived) and the quick-chat boot follows the task's workspace with only office cookies present; the missing-task fallback path is covered as part of the Home case, not as TaskDetail coverage.
The office-route test (next bullet) separately asserts office cookies still select office workspaces there.
- **Office precedence regression** (through `officeWorkspaces` /
`addOfficeRouteState`, the full contract, with REAL user settings via
`b.userSettings`). Pre-change `readActiveWorkspaceCookie` reads only the
**unprefixed** names and never the scoped ones, so each row's behavior
depends on which cookie names it uses:
- **Rows with SCOPED names (`kandev-active-workspace_8443` /
`office-active-workspace_8443`) are all failing-before** — the scoped
names do not exist pre-change, so the reader returns empty and
`resolveActiveOfficeWorkspaceID` falls back to the first office
workspace. Assert the post-change winner and **require non-first
fixtures** (the winner must differ from the pre-change first-office
fallback): (a) scoped general = valid kanban id + scoped office = O2 →
O2; (b) scoped general = valid office O1 + scoped office = O2 (distinct)
→ O1; (c) scoped office = O1 + settings = different valid office O2 →
O1; (d) scoped office absent + scoped general = valid office O1 → O1.
- **Rows with LEGACY (unprefixed) names**: (a) legacy general = kanban +
legacy office = O2 → O2 (failing-before — pre-change the kanban id is
returned and the office cookie never consulted → first office); (b)
legacy general = valid office O1 + legacy office = O2 (distinct) → O1
(invariant — general-first both before and after); (c) legacy office =
O1 + settings = different valid office O2 → O1 (invariant — office beats
settings both before and after); (d) legacy office absent + legacy
general = valid office O1 → O1 (invariant).
- Settings must be the real `userSettings` value, not a fake.
## Verification
```bash
cd apps/backend && go test ./internal/backendapp/... && make lint
```
## Files likely touched
- `apps/backend/internal/backendapp/boot_state_routes.go`
- `apps/backend/internal/backendapp/boot_state_workspace_test.go`
- `apps/backend/internal/backendapp/helpers_test.go` (if a fixture needs the
scoped name)
## Dependencies
`httpcookie` from task 01.
## Parallelism
Disjoint files from `task-02`; parallel-safe after Wave 1.
## Inputs
- Spec: `What` (workspace cookie scoping + legacy fallback), `Scenarios`
(second and third).
- Plan: `Backend > Workspace cookie scoping`.
- Existing pattern: `readActiveWorkspaceCookie` currently iterates
`[]string{activeWorkspaceCookie, legacyOfficeWorkspaceCookie}`; the
amended design removes the office name from the generic reader (parity
with the frontend) and adds `readOfficeWorkspaceCookie` for the office
family.
## Risks
- Keep the legacy fallback read-only (never write unprefixed names); new
writes are the frontend task's job.
- The office boot-state path now resolves with named candidates —
`resolveActiveOfficeWorkspaceID(officeItems, generalCookieID,
officeCookieID, settingsID)` using `readActiveWorkspaceCookie` +
`readOfficeWorkspaceCookie` + `b.userSettings` — never
`resolveActiveOfficeWorkspaceID(officeItems, readActiveWorkspaceCookie(req))`
(which dropped the office cookie entirely). Preferring the scoped
`office-active-workspace_<port>` value inside the office resolver is
preserved.
## Output contract
Report the scoped read behavior, changed files, exact commands and results,
blockers/risks, then mark this task `done` and update `plan.md`.
@@ -0,0 +1,212 @@
---
id: "04-workspace-cookie-port-scope-frontend"
title: "Port-scope workspace cookies (frontend)"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/fix-multi-instance-cookie-isolation/spec.md"
---
# Task 04: Port-scope workspace cookies (frontend)
## Acceptance
- `apps/web/lib/routing/route-bootstrap.ts` gains:
- `scopedCookieName(name: string, port?: string): string` — appends
`_<port>` when non-empty; the port defaults to the API origin port from
`getBackendConfig().apiBaseUrl` (NOT `window.location.port`, which
mismatches in split-origin dev where the SPA runs on the web port and
the API on the backend port with no Vite proxy).
- `readScopedCookie(name: string, port?: string)` — reads the scoped name
first, falls back to the legacy name. The explicit `port` parameter
keeps both helpers pure and unit-testable without jsdom Location
stubbing (a same-module function cannot be `vi.spyOn`-stubbed for its
own callers — the ES-module lexical binding trap).
- `readActiveWorkspaceCookie` and the office legacy read
(`readCookie(LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE)`) use them with the
API-origin default.
- `apps/web/components/app-sidebar/app-sidebar-workspace-navigation.ts`
`writeWorkspaceCookie` writes the scoped name (same API-origin port) for
both `kandev-active-workspace` and `office-active-workspace`.
- Server-component and async client readers that hold a CookieStore read the
scoped name first, legacy fallback via
`readScopedCookieStoreValue(cookieStore, name, port?)`:
`apps/web/app/page.tsx`, `apps/web/app/office/layout.tsx`,
`apps/web/app/settings/layout.tsx`, and
`apps/web/app/office/lib/get-active-workspace.ts` (the actual helper
location; not `apps/web/lib/get-active-workspace.ts`).
- `apps/web/src/office-routes.tsx` is a **synchronous client effect** (lines
~224-229) and keeps the document-cookie-based `readScopedCookie(name,
port?)` helpers instead of an async `readCookies()` refactor; both helper
families share `scopedCookieName` so the derivation is identical. This
split is explicit: CookieStore readers use the store helper, the sync
office effect uses `readScopedCookie`.
- **Office precedence unification** (task-03 contract, frontend half):
`app/office/layout.tsx` and `app/office/lib/get-active-workspace.ts`
currently resolve the office cookie only, while `office-routes.tsx`
carries a 5-argument resolver with route precedence. Extract ONE canonical
frontend resolver with an explicit input contract:
`resolveOfficeWorkspaceId(items, { routeWorkspaceId, generalWorkspaceId,
officeWorkspaceId, settingsWorkspaceId })` and a single documented
precedence — **route → general (when it names an office workspace) →
office cookie → settings → first** — every candidate validated against the
office set. Wrappers pass their route override where one exists:
`getActiveWorkspaceId(urlWorkspaceId?)` passes it as `routeWorkspaceId`
(its URL-first behavior is already pinned by
`get-active-workspace.test.ts:58-78`; a valid `/office?workspaceId=O2`
must beat the cookies); only the no-argument caller
(`app/office/layout.tsx`) passes `null`. The server layout cannot read
query params and hydrates from cookies at first paint, so convergence with
a route override is **client-eventual**: the `office-routes.tsx` bootstrap
effect re-resolves route-first and hydrates the store. The convergence
regression asserts the OfficeRoutes bootstrap (route O2 + cookies naming
O1 → hydrated `activeId` = O2), not the server layout — the layout's
first-paint value is cookie-driven by design and converges client-side.
- **Structural guard test** (vitest, `fs`-based): (a) negative — no
workspace-cookie `cookieStore.get(...)` / `readCookie(...)` call exists in
the five files outside the helpers, with arguments rejected both as
literals (`"kandev-active-workspace"`, `"office-active-workspace"`) **and
as the exported constants** (`ACTIVE_WORKSPACE_COOKIE`,
`LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE` — `app/page.tsx` and
`app/settings/layout.tsx` read via the constant today); (b) **positive** —
each of the four CookieStore readers references `readScopedCookieStoreValue`
and `office-routes.tsx` references `readScopedCookie`, so a reader that
simply drops its lookup fails the guard. The helper unit tests cover
scoped-first + legacy fallback.
- Unit tests, failing pre-change:
- **Reader tests** (beyond the guard, which only proves symbol reference):
`app/office/lib/get-active-workspace.test.ts` is extended with
scoped-first (`office-active-workspace_8443`), legacy fallback,
route-override, and **general-vs-office precedence** cases;
**`src/office-routes.test.ts` is updated in place** (it currently tests
the 5-argument resolver including route precedence). **Classification**:
the resolver **precedence** cases (route > general-if-office > office >
settings > first, distinct-valid-O1/O2) are **invariant** — the current
`office-routes.tsx` resolver already implements this precedence and the
existing `office-routes.test.ts` already covers it; extraction must keep
them green pre-change. The **failing-before** coverage targets the
scoped/legacy cookie reads (`scopedCookieName`, `readScopedCookie`,
`readScopedCookieStoreValue`), the server-reader wrapper wiring
(`get-active-workspace` + the office layout reading both scoped cookie
families), and the client convergence path (route override hydrating
`activeId` — the old office-cookie-only reads are what is actually
wrong).
- `route-bootstrap.test.ts`: `scopedCookieName("kandev-active-workspace",
"8443")` = `kandev-active-workspace_8443`; `readScopedCookie` returns
the `_8443` value when present and falls back to the legacy name
otherwise. `readScopedCookieStoreValue` returns the scoped
`cookieStore` entry first, legacy fallback. A **split-origin
regression** asserts the default port comes from the API base URL
(`:38429`) and not from `window.location.port` (`:37429`) — stub
`getBackendConfig` (separate module, mockable) or pass the port
explicitly.
- **Structural guard test** (vitest, `fs`-based): fails on any
workspace-cookie lookup in the five files outside the helpers — literal
names **or** the exported constants (`ACTIVE_WORKSPACE_COOKIE`,
`LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE`) — (negative), and on a file
that does not reference its mandated helper — the four CookieStore
readers must import `readScopedCookieStoreValue`, `office-routes.tsx`
must import `readScopedCookie` (positive).
- **No-port frontend regression**: an API origin with no explicit port (or
`port=""`) yields no suffix — `scopedCookieName("kandev-active-workspace",
"")` stays unprefixed and the write path emits the plain name (the spec's
single-instance/default-port promise, frontend half; backend session
no-port is task 02).
- **Client convergence**: two classes. **(invariant)** OfficeRoutes
bootstrap with a route override naming O2 and cookies naming O1 hydrates
`activeId` = O2 — the current route-first resolver already wins, so this
guards the precedence, not the change. **(failing-before)** a
**no-route / invalid-route** case with distinct **non-first** scoped
fixtures: route override absent, scoped general cookie naming O1 (and no
valid unprefixed cookie) → the bootstrap hydrates O1 (pre-change the
reader never sees the scoped name → settings/first, so the assertion
fails pre-change).
- **OfficeRoutes scoped-office bootstrap regression** (failing-before,
the scoped **office-family** read — the convergence case above covers
the general family only): OfficeRoutes bootstrap with scoped general
`kandev-active-workspace_8443` naming a **kanban** workspace, scoped
office `office-active-workspace_8443` naming non-first O2, no legacy
office cookie, no route/settings candidate → hydrated `activeId` = O2.
Pre-change the effect's direct `readCookie(LEGACY_OFFICE_ACTIVE_
WORKSPACE_COOKIE)` reads only the unprefixed name (absent) → settings/
first; fails pre-change. Implement via a focused bootstrap test or a
narrow exported cookie-candidate reader used by the effect.
- **Per-file guard argument assertions**: the structural guard also checks
each CookieStore reader passes the correct cookie name — `app/page.tsx`
and `app/settings/layout.tsx` must reference `ACTIVE_WORKSPACE_COOKIE`
(not the legacy office constant) through the helper, and
`app/office/layout.tsx` + `get-active-workspace.ts` must pass BOTH
`ACTIVE_WORKSPACE_COOKIE` and `LEGACY_OFFICE_ACTIVE_WORKSPACE_COOKIE` in
the documented order (general first); **`office-routes.tsx` must
reference `readScopedCookie` with the legacy office constant** for its
office candidate (defense-in-depth against the wrong family/name).
Text/AST assertions in the guard test, or focused reader tests; a wrong
constant or a dropped candidate fails the suite.
- `app-sidebar-workspace-navigation.test.ts` **and
`app-sidebar-workspace-picker.test.tsx`** (the picker drives the same
`rememberWorkspaceSelection` path and today asserts unprefixed writes):
`rememberWorkspaceSelection` writes `kandev-active-workspace_8443=...`
(and `office-active-workspace_8443=...` for office workspaces) **and
does not write the unprefixed names** (negative assertion — the legacy
read fallback stays, but no new legacy writes); the picker fixtures and
captured cookie-name assertions are updated to the API-port suffix.
## Verification
```bash
cd apps && pnpm --filter @kandev/web test -- lib/routing/route-bootstrap.test.ts components/app-sidebar/app-sidebar-workspace-navigation.test.ts components/app-sidebar/app-sidebar-workspace-picker.test.tsx app/office/lib/get-active-workspace.test.ts src/office-routes.test.ts
cd apps/web && pnpm run typecheck
```
## Files likely touched
- `apps/web/lib/routing/route-bootstrap.ts`
- `apps/web/lib/routing/route-bootstrap.test.ts`
- `apps/web/components/app-sidebar/app-sidebar-workspace-navigation.ts`
- `apps/web/components/app-sidebar/app-sidebar-workspace-navigation.test.ts`
- `apps/web/components/app-sidebar/app-sidebar-workspace-picker.test.tsx`
- `apps/web/app/page.tsx`
- `apps/web/app/office/layout.tsx`
- `apps/web/app/settings/layout.tsx`
- `apps/web/app/office/lib/get-active-workspace.ts`
- `apps/web/app/office/lib/get-active-workspace.test.ts`
- `apps/web/src/office-routes.tsx` (office bootstrap cookie reads)
- `apps/web/src/office-routes.test.ts` (resolver tests updated/moved in place)
- `apps/web/lib/config.ts` (only if the API-origin port needs a small accessor)
## Dependencies
None (independent of the Go helper).
## Parallelism
Parallel-safe with `task-01` (disjoint tree/contract).
## Inputs
- Spec: `What` (workspace cookie scoping — API-origin port on both sides,
legacy fallback), `Scenarios` (second, third, split-origin).
- Plan: `Frontend`.
- Existing pattern: `writeWorkspaceCookie` is the single client write
choke point; `readCookie` is the single client read choke point;
`getBackendConfig()` in `apps/web/lib/config.ts` already resolves the
API base URL (split-origin dev vs same-origin prod).
## Risks
- Split-origin dev is the trap: any default not derived from the API base
URL silently degrades to the legacy fallback. The split-origin regression
test is the guard.
- Do not stub a same-module helper with `vi.spyOn` — the ES-module lexical
binding is not replaced for its own callers; tests pass the `port`
parameter explicitly instead.
- Do not scope `kandev_locale` or `layout:*` reads (out of scope); keep the
change limited to the workspace cookies.
- `office-routes.tsx` reads both cookies through `readActiveWorkspaceCookie`
/ `readCookie`; verify the office bootstrap uses the scoped variants.
## Output contract
Report the scoped read/write behavior, changed files, exact commands and
results, blockers/risks, then mark this task `done` and update `plan.md`.
@@ -0,0 +1,77 @@
---
id: "05-e2e-cookie-scope-assertions"
title: "E2E cookie-name assertions"
status: done
wave: 3
depends_on: ["02-session-cookie-port-scope-backend", "04-workspace-cookie-port-scope-frontend"]
plan: "plan.md"
spec: "../../specs/fix-multi-instance-cookie-isolation/spec.md"
---
# Task 05: E2E cookie-name assertions
## Acceptance
- The auth e2e project asserts that the login response's `Set-Cookie` names
the session cookie `kandev_session_<port>` (port = the fixture's backend
port), and that after login the app renders authenticated content.
- The workspace-switch e2e spec (or a new focused spec) asserts that
selecting a workspace in the sidebar writes `kandev-active-workspace_<port>`
rather than the unprefixed name. **E2E covers the Kanban cookie only**: the
existing `workspace-switch-sidebar-isolation.spec.ts` runs with Office
disabled, so the `office-active-workspace_<port>` write is asserted at the
unit level (task 04 sidebar test), not in E2E. An Office-enabled
workspace-switch E2E setup is recorded as a follow-up, not a blocker.
- Both assertions fail pre-change (the cookies are unprefixed today).
- Scope limitation (from review round 1): the Playwright fixture runs one
backend per worker (`apps/web/e2e/fixtures/backend.ts`, `restart()`
replaces that same process), so e2e here proves the browser-observable
cookie **naming** contract only. The two-instance behavioral regression
(independent sessions and workspace state per port) is proven by the Go
integration tests in tasks 02 and 03. A two-backend Playwright fixture is
explicitly out of scope; note it as a follow-up in the task output.
- The e2e files live in `apps/web/e2e/tests/` following the existing auth
and workspace-switch spec conventions; no new infrastructure.
## Verification
```bash
cd apps/web && pnpm e2e:raw --project=auth
# plus the workspace-switch spec's exact command from apps/web/e2e/README.md
```
## Files likely touched
- `apps/web/e2e/tests/auth/login.spec.ts` (or the auth project's login spec)
- `apps/web/e2e/tests/task/workspace-switch-sidebar-isolation.spec.ts` (or a
sibling spec asserting cookie names)
## Dependencies
Shipped behavior of tasks 02 and 04.
## Parallelism
Sequential with task 06? No — both are Wave 3 and disjoint (e2e specs vs
docs); parallel-safe.
## Inputs
- Spec: `API surface` (cookie names observable via Set-Cookie / document
cookie), `Scenarios` (first, second, fourth).
- Existing helpers: `apps/web/e2e/helpers/api-client.ts`,
`apps/web/e2e/helpers/causal-waits.ts`.
## Risks
- The session cookie is HttpOnly, so assertions must read the response
`Set-Cookie` header, not `document.cookie`.
- The auth project gates on `KANDEV_FEATURES_AUTH=true` per-spec via
`backend.restart(env)`; the workspace-switch spec runs auth-off and only
asserts the workspace cookie names.
## Output contract
Report the asserted cookie names, spec files, exact commands and results,
the noted two-backend-e2e follow-up, blockers/risks, then mark this task
`done` and update `plan.md`.
@@ -0,0 +1,124 @@
---
id: "06-docs-and-stale-references"
title: "Deployment note and stale cookie-name references"
status: done
wave: 3
depends_on: ["02-session-cookie-port-scope-backend", "04-workspace-cookie-port-scope-frontend"]
plan: "plan.md"
spec: "../../specs/fix-multi-instance-cookie-isolation/spec.md"
---
# Task 06: Deployment note and stale cookie-name references
## Acceptance
- `docs/public/authentication.md` gains an operator note: multiple
auth-enabled instances on one host (same IP, different ports) are isolated
per port via port-scoped cookie names. Reverse proxies: the CORS/WS origin
gate compares the browser `Origin` hostname with the request `Host` and
ignores `X-Forwarded-Host`, so the proxy MUST preserve the browser
**hostname**; it may either preserve the full `Host` (host:port) or rewrite
only the port and forward a correct `X-Forwarded-Host` (the resolver takes
the public port from XFH) — rewriting a non-loopback hostname 403s before
auth (loopback-alias rewrites such as `localhost` → `127.0.0.1` pass the
existing origin gate and are unchanged).
**Session-cookie migration** (scoped to auth sessions; workspace cookies
are separate): old auth-enabled builds conflict with other old builds via
the shared unprefixed `kandev_session`; an upgraded instance ignores the
legacy session token and requires one re-login (guaranteed on rollback and
re-upgrade because the new build never reads the unprefixed session
cookie); workspace selections keep their validated legacy read fallback, so
a pre-upgrade selection survives. Custom `auth.cookieName` values disable
automatic port isolation and must be unique per cookie host. Instances on
the same host at default ports over different schemes (HTTP :80 + HTTPS
:443) keep the plain names and are not isolated.
- `docs/public/configuration.md` documents `auth.cookieName` with its
canonical environment override `KANDEV_AUTH_COOKIE_NAME` (explicit
`BindEnv`; the automatic camelCase mapping would expose the undocumented
`KANDEV_AUTH_COOKIENAME`), plus config.yaml and precedence
(env over file over default).
- Stale references that pin the literal `kandev_session` cookie name are
updated to describe "the session cookie (name derived from the request
host)" or "base name `kandev_session`; effective name request-host-derived":
- `apps/web/e2e/helpers/auth.ts` (doc comment, ~lines 6-8)
- `apps/web/components/app-sidebar/app-sidebar-workspace-navigation.ts`
(comment ~lines 30-34: "office paths read the legacy cookie... kept in
step" — legacy names are now read-only fallback, writes are scoped)
- `apps/web/app/office/layout.tsx` (comment ~lines 154-157: the office
cookie "is set by the setup wizard and workspace rail" — now writes the
port-scoped name)
- `docs/specs/plugins/spec.md` (~lines 223-234, external-login section)
- `docs/decisions/0050-plugin-external-auth-capability.md`
- `docs/decisions/2026-07-24-opt-in-authentication.md`
- `apps/backend/AGENTS.md`
- `apps/backend/internal/backendapp/auth.go` (plugin SSO bridge doc
comment, ~lines 21-24)
- `apps/backend/internal/auth/service_sso.go` (comment)
- `apps/backend/internal/plugins/auth_login.go` (comment)
- `apps/backend/internal/auth/store/models.go` (comment)
- **No-op verification targets** (already amended by this package; keep in
the audit grep, do NOT edit): `docs/specs/auth/spec.md` (already states
base name + request-host-derived effective names) and
`docs/decisions/2026-08-15-office-mode-follows-active-workspace.md`
(already states the legacy office cookie is read-only fallback and writes
are port-scoped).
- No behavioral code change in this task; `gofmt`/lint still clean (comments
only).
## Verification
```bash
rg -n "kandev_session" docs/specs/auth/spec.md docs/specs/plugins/spec.md docs/decisions/0050-plugin-external-auth-capability.md docs/decisions/2026-07-24-opt-in-authentication.md apps/backend/AGENTS.md apps/backend/internal/auth apps/backend/internal/plugins apps/backend/internal/backendapp/auth.go apps/web/e2e/helpers/auth.ts apps/web/components/app-sidebar/app-sidebar-workspace-navigation.ts apps/web/app/office/layout.tsx
rg -n "office-active-workspace" docs/decisions/0023-active-workspace-cookie.md docs/decisions/2026-08-15-office-mode-follows-active-workspace.md docs/decisions/2026-07-24-opt-in-authentication.md
# every path listed in the stale-reference acceptance must appear above; remaining hits must be intentional (e.g. the legacy-cookie no-fallback note in the fix spec)
cd apps/backend && go build ./...
```
## Files likely touched
- `docs/public/authentication.md`
- `docs/public/configuration.md` (new `auth.cookieName` row + env name)
- `docs/specs/plugins/spec.md`
- `apps/web/e2e/helpers/auth.ts` (doc comment)
- `apps/web/components/app-sidebar/app-sidebar-workspace-navigation.ts`
- `apps/web/app/office/layout.tsx`
- `docs/decisions/0050-plugin-external-auth-capability.md`
- `docs/decisions/2026-07-24-opt-in-authentication.md`
- `apps/backend/AGENTS.md`
- `apps/backend/internal/backendapp/auth.go`
- `apps/backend/internal/auth/service_sso.go`
- `apps/backend/internal/plugins/auth_login.go`
- `apps/backend/internal/auth/store/models.go`
Audit-only (do NOT edit; already amended by this package, keep in the
verification grep): `docs/specs/auth/spec.md`,
`docs/decisions/2026-08-15-office-mode-follows-active-workspace.md`.
## Dependencies
The behavior contract from tasks 02 and 04 (docs describe shipped behavior).
## Parallelism
Wave 3, parallel-safe with `task-05` (docs vs e2e specs; disjoint).
## Inputs
- Spec: `Failure modes` (proxy, mixed-version), `Out of scope`.
- Plan: `Docs`.
- Existing pattern: `docs/public/plugins-authoring.md` already describes the
request-host-derived name; mirror that wording.
## Risks
- Some hits are intentional (the fix spec's legacy-fallback note, the auth
spec's port-scoped bullet); do not rewrite the fix package itself. Only
prose that implies a fixed literal name is in scope.
- Comments in `service_sso.go` / `auth_login.go` sit next to the SSO bridge
code changed in task 02; coordinate wording with that task's diff.
## Output contract
Report the deployment note placement, the updated references, the remaining
intentional `kandev_session` hits, changed files, exact commands and results,
blockers/risks, then mark this task `done` and update `plan.md`.
+10
View File
@@ -65,6 +65,16 @@ External MCP clients (Claude Code, Cursor connecting to `/mcp`) must be configur
`/health` (readiness probes), the login/setup/invite pages, `GET /api/v1/features`, and self-authenticating webhook receivers (automation webhooks with `X-Webhook-Secret`, office channel HMAC webhooks, plugin webhooks). Everything else requires a session or token.
## Multiple instances on one host
Browsers match cookies by host and ignore the port, so several auth-enabled kandev instances on the same host (same IP, different ports) would otherwise share one cookie jar. Kandev isolates them by port-scoping its instance-identity cookie **names**: `kandev_session_<port>`, `kandev-active-workspace_<port>`, and `office-active-workspace_<port>` on a ported host, plain names on a default-port host. Default-port normalization is scheme-aware and mirrors the SPA's `URL.port` behavior: `:80` on HTTP and `:443` on HTTPS yield no suffix (browsers omit them from `Host`), while the scheme-mismatched combinations (HTTP `:443`, HTTPS `:80`) keep their port suffix on both sides, so `example.com:80` and `example.com` resolve to the same plain names and two HTTP instances on ports 80 and 443 stay isolated. Logging into one instance no longer logs the others out, and selecting a workspace in one no longer changes what the others boot into.
**Reverse proxies must preserve the browser hostname.** The CORS/WS origin gate compares the browser `Origin` hostname with the request `Host` and ignores `X-Forwarded-Host` and ports. The proxy may either preserve the full `Host` (`public.example:8443`) or rewrite only the port and forward a correct `X-Forwarded-Host` (the cookie resolver takes the public port from it; the header is honored only from peers listed in `KANDEV_TRUSTED_PROXIES`, the same list that gates `X-Forwarded-For`). Rewriting a **non-loopback hostname** is rejected with 403 before authentication. Loopback-alias rewrites (e.g. `localhost` → `127.0.0.1`) pass the gate by design.
**Session-cookie migration.** Old auth-enabled builds conflict with each other via the shared unprefixed `kandev_session`; an upgraded instance ignores the legacy session token and requires one re-login (the new build never reads the unprefixed session cookie, so this holds on rollback and re-upgrade too). Workspace selections keep their validated legacy read fallback, so a pre-upgrade selection survives.
A custom `auth.cookieName` (see [configuration](configuration.md#authentication-office-plugins-and-feature-flags)) disables automatic port isolation and must be unique per cookie host. In particular, an explicit `auth.cookieName: kandev_session` (copied from the pre-isolation default) silently keeps the old shared-name behavior after upgrade: remove the setting (or any other value equal to the base name) to inherit port isolation. A custom name does not change the origin gate, which compares hostnames independently of cookie names. Instances served on the same host at default ports over different schemes (HTTP `:80` + HTTPS `:443`) carry no port in their Host and keep the plain names; they are not isolated by this mechanism.
## What is isolated
When authentication is on, everything in a workspace is private to its owner and returns "not found" to anyone else, even if they know the ID: workspaces, tasks, workflows, sessions, plans, walkthroughs, terminals, VS Code, port previews, git snapshots, Workspace secrets, repository bindings, **and the workspace's third-party integration settings (GitHub/GitLab/Jira/Linear/Sentry/Azure) and automations**. A user's Global secrets are also private to that user. Admins manage users but do not see other users' workspaces or secrets.
+1
View File
@@ -143,6 +143,7 @@ YAML, the database, or Settings.
|---|---|---|---|
| `auth.jwtSecret` | `KANDEV_AUTH_JWTSECRET` | generated value | Accepted and validated compatibility configuration; the current main HTTP product path does not use it as an authentication boundary. |
| `auth.tokenDuration` | `KANDEV_AUTH_TOKENDURATION` | `3600` | Must be positive, but is not consumed by the current main HTTP product path. |
| `auth.cookieName` | `KANDEV_AUTH_COOKIE_NAME` | empty | Session cookie base name. Empty (default) means the effective name is derived from the request host: `kandev_session` on a default-port host, `kandev_session_<port>` on a ported host. This isolates multiple instances on one host (see [authentication](authentication.md#multiple-instances-on-one-host)). A non-empty value is used verbatim (never port-suffixed) and disables automatic isolation, so it must be unique per cookie host. Precedence: environment over config file over default. |
| `office.jwtSigningKey` | `KANDEV_OFFICE_JWTSIGNINGKEY` | random per start | HMAC key for Office agent-runtime JWTs. Set a stable secret when Office tasks must survive restarts. |
| `features.office` | `KANDEV_FEATURES_OFFICE` | `false` in production | Experimental Office UI, routes, services, and automation. |
| `features.auth` | `KANDEV_FEATURES_AUTH` | `false` in production | Opt-in authentication and per-user workspaces. The first visitor after enabling completes setup and becomes the admin. |
+7 -3
View File
@@ -931,9 +931,13 @@ ACS in a `webhook`, validate the token yourself, then set the reserved
`X-Kandev-Auth-Login` response header to a JSON object
`{"provider","subject","email","display_name"}`. Kandev maps it to a user
(link-by-email or just-in-time member provisioning), mints the session, and sets
the `kandev_session` cookie itself; your plugin never handles the raw token,
and any `Set-Cookie` you return is dropped. Requires authentication enabled;
emitting the header without `capabilities.auth` returns 403.
the session cookie itself (the host derives the name from the request host:
`kandev_session` on default ports, `kandev_session_<port>` otherwise, unless
`auth.cookieName` is explicitly configured, in which case that name is used
verbatim and must be unique per cookie host); your
plugin never handles the raw token, and any `Set-Cookie` you return is
dropped. Requires authentication enabled; emitting the header without
`capabilities.auth` returns 403.
**You MUST only assert an `email` the IdP has verified as owned by `subject`.**
Kandev auto-links that email to (or provisions) an account, so an unverified or
+20 -5
View File
@@ -34,11 +34,22 @@ the local single-user install with a login screen it never asked for.
`admin` (user management, auth settings, destructive system operations,
feature toggles) and `member`. Users can be disabled (revokes all sessions
and tokens); the last active admin cannot be demoted or disabled.
- **Sessions & tokens.** Browser sessions are opaque cookies
(`kandev_session`, HttpOnly, SameSite=Lax, sliding 30-day expiry,
DB-backed and revocable from `Settings > Account`). Programmatic clients
(external MCP, scripts, CI) use personal access tokens
(`kandev_pat_…`, shown once, revocable).
- **Sessions & tokens.** Browser sessions are opaque cookies with the base
session-cookie name `kandev_session` (effective name is request-host
derived — see the port-scoping bullet below), HttpOnly, SameSite=Lax,
sliding 30-day expiry, DB-backed and revocable from `Settings > Account`.
Programmatic clients (external MCP, scripts, CI) use personal access
tokens (`kandev_pat_…`, shown once, revocable).
- **Cookie name is port-scoped when the instance is served on a non-default
port.** Cookies ignore port when deciding scope, so two auth-enabled
instances on one host (same IP, different ports) would otherwise overwrite
each other's `kandev_session` and yank every instance to `/login` on the
next request. The backend derives the session cookie name from the request
host: `kandev_session_<port>` on a ported host, plain `kandev_session` on a
default-port host (see `fix-multi-instance-cookie-isolation`). An explicit
`auth.cookieName` config value is used verbatim. The legacy unprefixed
cookie is deliberately not read (one re-login after upgrade keeps the
cross-instance conflict dead).
- **Invites.** Admins mint tokenized invite URLs (`/invite?token=…`,
optional pinned email, member/admin role, 7-day default expiry, single
use). No email server required. Admins can also create accounts directly.
@@ -124,6 +135,10 @@ the local single-user install with a login screen it never asked for.
- **GIVEN** an authenticated Kandev browser session, **WHEN** a protected API
request receives a Kandev session challenge, **THEN** the browser clears the
stale Kandev identity and navigates to `/login`.
- **GIVEN** two auth-enabled Kandev instances A (port 8080) and B (port
8081) on the same host, **WHEN** the user logs into B, **THEN** A's session
keeps working and A's next page load authenticates with A's own
`kandev_session_8080` cookie rather than showing the Sign in page.
- **GIVEN** an authenticated Kandev browser session and an expired or invalid
third-party integration credential, **WHEN** GitHub, GitLab, Jira, or Linear
data loading returns 401 without a Kandev session challenge, **THEN** the
@@ -0,0 +1,246 @@
---
status: pending
created: 2026-08-17
owner: Kandev
---
# Isolate Kandev cookies between instances on one host
## Why
Browsers match cookies by host, domain, and path; **port is not part of
cookie scope** (the `Secure` attribute controls transmission over TLS, not
scheme partitioning). Every kandev instance bound to the same host (same IP,
different ports) therefore shares one cookie jar: a cookie written by the
instance the user touched last is sent to every other instance on the next
request. `localStorage` and `sessionStorage` are origin-scoped (scheme +
host + port) and therefore port-segregated; cookies are the only browser
storage that leaks between instances (empirically verified: a cookie written
on port 18111 is readable on port 18222 of the same host, while
localStorage/sessionStorage are not). Known limit: instances served on the
same host at default ports over different schemes (`http://host` on :80 and
`https://host` on :443) both carry no port in their Host, so they keep the
plain cookie names and are not isolated by this fix; the reported scenario
(same scheme, different ports) is fully covered.
Three kandev cookies carry per-instance identity and are all written with
`Path=/` and no Domain/Port scoping:
- `kandev_session` — the auth session token (HttpOnly). Two auth-enabled
instances on one host overwrite each other's token. The losing instance
rejects the foreign token (per-instance session store), 401s every API
call, and the SPA's `onUnauthorized` handler clears auth state and
redirects to `/login`. With two or more instances this ping-pongs: every
instance keeps breaking (`"crashes / blanks"` in the report). Reproduced
live with two auth-enabled instances (A on :48429, B on :48529): logging
into B yanked A's open UI to the Sign in page; each instance rejects the
other's token with `{"mode":"enabled","authenticated":false}`. The
maintainers documented the same caveat in kdlbs/kandev#2689 ("Cookies do
not include ports in their scope. Two authenticated Kandev instances on the
same hostname can have a `kandev_session` cookie conflict").
- `kandev-active-workspace` and `office-active-workspace` — the remembered
active workspace. A foreign workspace id is read by every other instance at
boot. Today both backend (`firstValidID`) and frontend resolvers validate
the value against the instance's own workspace list and fall back to the
first workspace, so this path is graceful rather than fatal — but it
constantly churns which workspace (and, since ADR
2026-08-15-office-mode-follows-active-workspace, which mode) each instance
boots into, and any unvalidated read of these values would hard-fail.
Private-browsing the demo servers "fixes" the report because the browser
gives private contexts an isolated cookie partition — consistent with cookies
being the shared state.
## What
Port-scope the instance-identity cookie **names** so each instance reads and
writes only its own cookie. The browser already keeps all names in one jar;
each instance simply ignores the foreign-named ones.
- `kandev_session` becomes `kandev_session_<port>` where `<port>` is derived
from the request Host (backend-side set and read), honoring
`X-Forwarded-Host` when present (same pattern as the existing
`X-Forwarded-Proto` TLS detection). A request without a port in its host
keeps the plain name (`kandev_session`), so default-port deployments are
unchanged. The backend resolves the name through a request-aware service
method (`CookieNameForRequest(r)`). The config default for `auth.cookieName`
is **empty** (the service keeps the `kandev_session` base fallback
internally, so the effective name for default deployments is unchanged):
when the configured value is non-empty it is returned verbatim (never
suffixed); when empty the default base name is port-suffixed. This lets the
resolver distinguish explicit configuration from the default — a seeded
non-empty default would defeat suffixing in production. The generic
`httpcookie.ScopedName` helper only appends the suffix and is never fed a
configured name.
- `kandev-active-workspace` / `office-active-workspace` become
`kandev-active-workspace_<port>` / `office-active-workspace_<port>`.
**Both sides derive the suffix from the API origin port** (one canonical
port): the SPA takes it from `getBackendConfig().apiBaseUrl` — equal to
`window.location.port` in same-origin deployments (Go serves SPA + API on
one port) and equal to the backend port in split-origin dev (Vite SPA on
the web port, API on the backend port, no Vite proxy — the browser calls
the backend directly), which is the same port the backend sees on its
request Host; the backend derives it from the request Host
(`X-Forwarded-Host` precedence). Deriving from `window.location.port`
alone would mismatch the backend in split-origin dev. The unprefixed
legacy names remain readable as a fallback (their values are still
validated against the workspace list), so a pre-upgrade selection
survives; new writes only use the scoped names.
- The session cookie has **no** legacy fallback: after upgrade each instance
requires one re-login. A fallback would re-open the cross-instance bleed
for any mixed-version period.
- **Workspace isolation scope: all-new builds.** The validated legacy
fallback means an upgraded instance still reads the unprefixed workspace
cookie while **old builds keep writing it**, so during a mixed-version
deployment an old instance can overwrite the legacy value a new instance
reads (when the id validates against the new instance's workspace list).
Workspace-selection isolation therefore applies once **all** instances on
the host are upgraded; the legacy fallback exists so pre-upgrade
selections survive, and it is safe because resolution validates against
the instance's own workspace set (a foreign id falls back gracefully).
Sessions are isolated even during mixed versions (no legacy session
fallback).
Observable behavior: with two or more **upgraded** kandev instances on one
host (same IP, different ports), logging into one no longer logs the others
out, and selecting a workspace in one no longer changes what the others boot
into. Single-instance and default-port behavior is unchanged. No HTTP
endpoint, WebSocket protocol, or data contract changes.
## API surface
Cookie names are browser-observable (DevTools, response `Set-Cookie`
headers): `kandev_session_<port>`, `kandev-active-workspace_<port>`,
`office-active-workspace_<port>`. No API, route, or wire change.
## Failure modes
- **Proxy drops `X-Forwarded-Host` or rewrites a non-loopback hostname.**
Two distinct failures: (1) when the effective host the backend derives the
suffix from differs from the browser-visible origin (missing or incorrect
`X-Forwarded-Host` under a port rewrite), the cookie name mismatches and
every request 401s (login loop); (2) when the proxy rewrites a
**non-loopback** hostname, the CORS/WS origin gate rejects the request
with 403 before auth (loopback-alias rewrites such as `localhost` →
`127.0.0.1` pass the existing gate and are unchanged). **Primary
deployment contract: the proxy MUST preserve the browser Origin
hostname.** The CORS/WS origin gate (`httpmw.AllowedOrigin`) compares the
browser `Origin` hostname with `r.Host` and does not consult
`X-Forwarded-Host`, so a proxy that rewrites the **non-loopback hostname**
is rejected with 403 before auth regardless of cookie naming;
`X-Forwarded-Host` must
carry the browser host:port for cookie naming. Two compliant setups:
(a) preserve `Host` fully (XFH absent or identical); (b) rewrite only the
port (same hostname) and forward a correct `X-Forwarded-Host` — CORS
hostname (ports are not compared) while the cookie resolver takes
the public port from XFH. **When both Host and X-Forwarded-Host carry
conflicting ports, `X-Forwarded-Host` wins for cookie naming** (it
represents the original browser Host across the chain); that conflict is a
proxy misconfiguration and is pinned by a resolver regression test.
Rewritten-**hostname** deployments require an independently configured
CORS trust extension, which is out of scope here — **qualified to
non-loopback hostnames**: `AllowedOrigin` already permits any origin/request
pair whose normalized hosts are both loopback (e.g. `localhost` →
`127.0.0.1`), an existing exception for dev reverse proxies that this fix
keeps unchanged and does not regression-test as a change. A full-router
test drives the boundary: preserved `Host` + public `Origin` reaches
login; same-hostname port-rewrite + correct XFH passes and scopes to the
public port; rewritten **non-loopback hostname** + public
`X-Forwarded-Host` + public `Origin` is rejected 403.
- **Port in URL vs port in Host disagree** (rare; browsers normalize
default ports out of Host). Suffix only when the Host actually carries a
port, so `http://host` and `http://host:80` agree in practice.
- **IPv6 hosts.** `net.SplitHostPort` handles bracketed forms
(`[::1]:8080`); unbracketed `::1` has no port and gets no suffix.
- **Custom cookie names disable automatic port isolation.** A non-empty
`auth.cookieName` is used verbatim (never suffixed), so two auth-enabled
instances on one cookie host configured with the **same** custom name
overwrite each other exactly like the original bug — the isolation promise
applies to default-named instances. Deployments that set a custom name
must make it unique per cookie host (per instance), and should treat it as
single-instance-oriented. The canonical environment override is
`KANDEV_AUTH_COOKIE_NAME` (explicit `BindEnv`; the automatic camelCase
mapping would otherwise yield the undocumented `KANDEV_AUTH_COOKIENAME`).
- **Mixed-version migration.** Old builds keep writing the unprefixed names.
The upgraded instance ignores legacy session cookies (clean one-time
re-login) and reads legacy workspace cookies only as a validated fallback,
but an **old build still conflicts with other old builds, and a rollback
resurrects the original bleed** (old binaries read/write the shared
unprefixed `kandev_session`). Operational contract: all auth-enabled
instances on one host must upgrade together; after a rollback every
instance needs a fresh login. On re-upgrade the guarantee is mechanical:
the new build reads only scoped cookie names, which the old build never
wrote, so no valid scoped session exists until the user logs in again (old
session rows remain in the DB but are unreachable via the scoped name). The
upgraded instance does not proactively
delete the legacy cookie — scrubbing the shared jar from one instance would
just log other (old) instances out and they would re-write it.
## Scenarios
- **GIVEN** two auth-enabled kandev instances A (port 8080) and B (port
8081) on the same host, **WHEN** the user logs into B, **THEN** A's open
session keeps working, and A's next page load shows A's authenticated UI
rather than the Sign in page.
- **GIVEN** the same pair, **WHEN** the user selects a workspace in B,
**THEN** A's next boot resolves A's own workspace selection, not B's
workspace id.
- **GIVEN** an instance upgraded from a version that wrote the unprefixed
workspace cookie, **WHEN** the instance boots, **THEN** the legacy value is
honored when it names one of the instance's own workspaces.
- **GIVEN** an instance upgraded from a version that wrote the unprefixed
session cookie, **WHEN** the user loads the instance, **THEN** the user is
asked to sign in once (the legacy token is not accepted), and the new
scoped cookie is used afterwards.
- **GIVEN** a single instance on the default port (no port in the URL),
**WHEN** the user logs in, **THEN** the cookie keeps the plain
`kandev_session` name and the flow is unchanged.
- **GIVEN** two auth-enabled instances A and B on one host where B is still
an old build, **WHEN** both users are logged in, **THEN** the old build
still conflicts with other old builds (documented limitation — old-build
wire behavior, not regression-tested).
- **GIVEN** the same pair after B upgrades and all instances re-login,
**THEN** the conflict is gone — recovery is inferred from independently
tested invariants (the new build rejects the legacy session token; two new
builds keep isolated sessions per port).
- **GIVEN** an old instance A and an upgraded instance B on one host,
**WHEN** the user selects a workspace in A, **THEN** B may read A's legacy
unprefixed workspace value (validated fallback — resolved only when it
names one of B's own workspaces, else B falls back); workspace isolation
is a property of all-new-build deployments (documented limitation,
invariant-tested).
- **GIVEN** an auth-enabled instance behind a reverse proxy that preserves
the browser `Host` (`public.example:8443`), **WHEN** the user logs in,
**THEN** the session cookie is set under the public-origin port suffix
(`kandev_session_8443`) and subsequent requests authenticate.
- **GIVEN** an auth-enabled instance behind a reverse proxy that **rewrites
a non-loopback hostname** (even with correct `X-Forwarded-Host`), **WHEN**
the browser sends a request from the public origin, **THEN** the CORS/WS
origin gate rejects it with 403 before auth (the gate compares `Origin` to
`Host` and ignores `X-Forwarded-Host`); the cookie-name resolver would
derive the `X-Forwarded-Host` suffix in isolation, but the request never
reaches it. Rewritten-hostname deployments require an independently
configured CORS trust extension, which is out of scope for this fix.
Loopback-alias rewrites (e.g. `localhost` → `127.0.0.1`) pass the gate by
existing `AllowedOrigin` design (dev reverse proxies) and are unchanged. A
same-hostname port-rewrite with correct XFH remains compliant.
- **GIVEN** split-origin dev (SPA on the web port, API on the backend port,
no Vite proxy), **WHEN** the user selects a workspace in the SPA, **THEN**
the workspace cookie is written with the backend port suffix and the
backend's boot reads the same scoped name (no legacy fallback needed).
- **GIVEN** an unconfigured (default) deployment on a ported host, **WHEN**
the user logs in, **THEN** the session cookie is `kandev_session_<port>`
— the empty config default must not suppress suffixing.
- **GIVEN** two auth-enabled instances on one cookie host both configured
with the same custom `auth.cookieName`, **WHEN** both users are logged in,
**THEN** the instances still conflict (documented exception: custom names
disable automatic port isolation and must be unique per host).
## Out of scope
- `kandev_locale` (validated, benign) and the write-only `layout:*` cookies
keep their names.
- The path-scoped port-proxy capability cookie (`kandev_port_proxy`) is
unchanged.
- Personal access tokens and the WS `?token=` path are unaffected.
- No legacy fallback for the session cookie (deliberate; see What).
+3 -2
View File
@@ -225,8 +225,9 @@ against an external IdP (OIDC/SAML): its webhook (the callback / SAML ACS)
validates the token, then asserts the identity to kandev via the reserved
`X-Kandev-Auth-Login` response header (`{provider, subject, email,
display_name}`). The host maps it to a user (link-by-email or just-in-time
member provisioning), mints the session, and sets the `kandev_session` cookie
itself — the plugin never receives the raw token. Requires auth enabled; new
member provisioning), mints the session, and sets the session cookie (name
derived from the request host) itself — the plugin never receives the raw
token. Requires auth enabled; new
users are members, and the host never creates an admin nor auto-links to an
existing admin account. The plugin **must** only assert IdP-verified emails (an
unverified email claim is an account-takeover vector the host cannot detect).