Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: add rate limiting to webhooks and auth endpoints, and add caching to user session (#2591)
Kyle Mendellab6415dae80b
diff --git a/backend/api/api.go b/backend/api/api.goindex 83fd6b455..0d3d2143b 100644--- a/backend/api/api.go+++ b/backend/api/api.go@@ -394,7 +394,7 @@ func registerHandlers(api huma.API, svc *Services) {handlers.RegisterAppImages(api, appImagesSvc)handlers.RegisterFonts(api, fontSvc)handlers.RegisterProjects(api, projectSvc)- handlers.RegisterUsers(api, userSvc)+ handlers.RegisterUsers(api, userSvc, authSvc)handlers.RegisterVersion(api, versionSvc)handlers.RegisterEvents(api, eventSvc, apiKeySvc)handlers.RegisterOidc(api, authSvc, oidcSvc, cfg)diff --git a/backend/api/handlers/auth.go b/backend/api/handlers/auth.goindex b75c4cb8b..9993d7ec6 100644--- a/backend/api/handlers/auth.go+++ b/backend/api/handlers/auth.go@@ -284,7 +284,8 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordIreturn nil, huma.Error400BadRequest((&common.PasswordRequiredError{}).Error())}- err := h.authService.ChangePassword(ctx, userModel.ID, input.Body.CurrentPassword, input.Body.NewPassword)+ currentSessionID, _ := humamw.GetCurrentSessionIDFromContext(ctx)+ err := h.authService.ChangePassword(ctx, userModel.ID, input.Body.CurrentPassword, input.Body.NewPassword, currentSessionID)if err != nil {switch {case errors.Is(err, services.ErrInvalidCredentials):diff --git a/backend/api/handlers/users.go b/backend/api/handlers/users.goindex 14852f002..519d4acf9 100644--- a/backend/api/handlers/users.go+++ b/backend/api/handlers/users.go@@ -18,6 +18,7 @@ import (// UserHandler handles user management endpoints.type UserHandler struct {userService *services.UserService+ authService *services.AuthService}// ============================================================================@@ -81,8 +82,8 @@ type DeleteUserOutput struct {// ============================================================================// RegisterUsers registers all user management endpoints.-func RegisterUsers(api huma.API, userService *services.UserService) {- h := &UserHandler{userService: userService}+func RegisterUsers(api huma.API, userService *services.UserService, authService *services.AuthService) {+ h := &UserHandler{userService: userService, authService: authService}huma.Register(api, huma.Operation{OperationID: "listUsers",@@ -327,6 +328,10 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*return nil, huma.Error500InternalServerError((&common.UserUpdateError{Err: err}).Error())}+ if h.authService != nil {+ h.authService.InvalidateUserTokenCache(updatedUser.ID)+ }+out, err := h.userService.ToUserResponseDto(ctx, *updatedUser)if err != nil {return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())@@ -360,6 +365,10 @@ func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*return nil, huma.Error500InternalServerError((&common.UserDeletionError{Err: err}).Error())}+ if h.authService != nil {+ h.authService.InvalidateUserTokenCache(input.UserID)+ }+return &DeleteUserOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true,diff --git a/backend/api/middleware/auth.go b/backend/api/middleware/auth.goindex 4c4d093b3..ed86a6ab8 100644--- a/backend/api/middleware/auth.go+++ b/backend/api/middleware/auth.go@@ -211,46 +211,25 @@ func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyServicreturn}- // Check agent authentication first (if in agent mode)- if cfg != nil && cfg.AgentMode {- if user, ok := tryAgentAuthInternal(ctx, cfg); ok {- newCtx := setUserInContextInternal(ctx.Context(), user)- ctx = huma.WithContext(ctx, newCtx)- next(ctx)- return- }+ if newCtx, ok := tryAgentAuthCtxInternal(ctx, cfg); ok {+ next(newCtx)+ return}reqs := parseSecurityRequirementsInternal(api, ctx)if !reqs.isRequired {- next(ctx)+ next(opportunisticBearerAuthInternal(ctx, authService))return}- // If API key header is present and API key auth is allowed, prioritize it.- // If validation fails, do NOT fall back to Bearer auth.if reqs.apiKeyAuth && ctx.Header(pkgutils.HeaderApiKey) != "" {- if user, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {- newCtx := setUserInContextInternal(ctx.Context(), user)- ctx = huma.WithContext(ctx, newCtx)- next(ctx)- return- }- if user, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(pkgutils.HeaderApiKey)); ok {- newCtx := setUserInContextInternal(ctx.Context(), user)- ctx = huma.WithContext(ctx, newCtx)- next(ctx)- return- }- // API key was present but invalid. Fail immediately.- _ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized: invalid API key")+ handleApiKeyAuthInternal(api, ctx, apiKeyService, envTokenResolver, next)return}if user, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(pkgutils.HeaderAgentToken)); ok {newCtx := setUserInContextInternal(ctx.Context(), user)- ctx = huma.WithContext(ctx, newCtx)- next(ctx)+ next(huma.WithContext(ctx, newCtx))return}@@ -264,11 +243,53 @@ func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyServic}}- // Write unauthorized response directly_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized: valid authentication required")}}+func tryAgentAuthCtxInternal(ctx huma.Context, cfg *config.Config) (huma.Context, bool) {+ if cfg == nil || !cfg.AgentMode {+ return ctx, false+ }+ user, ok := tryAgentAuthInternal(ctx, cfg)+ if !ok {+ return ctx, false+ }+ return huma.WithContext(ctx, setUserInContextInternal(ctx.Context(), user)), true+}++// opportunisticBearerAuthInternal populates the user/session context if a valid+// bearer token is present, but never fails the request. Used for public routes+// (e.g. logout) that still need to know who the caller is when a token exists.+func opportunisticBearerAuthInternal(ctx huma.Context, authService *services.AuthService) huma.Context {+ if extractBearerTokenInternal(ctx) == "" {+ return ctx+ }+ user, sessionID, err := tryBearerAuthInternal(ctx, authService)+ if err != nil || user == nil {+ return ctx+ }+ newCtx := setUserInContextInternal(ctx.Context(), user)+ newCtx = context.WithValue(newCtx, ContextKeyCurrentSessionID, sessionID)+ return huma.WithContext(ctx, newCtx)+}++// handleApiKeyAuthInternal handles the API-key-present branch. If validation+// fails, it writes 401 directly — Bearer is not attempted as fallback.+func handleApiKeyAuthInternal(api huma.API, ctx huma.Context, apiKeyService *services.ApiKeyService, envTokenResolver environmentAccessTokenResolver, next func(huma.Context)) {+ if user, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {+ newCtx := setUserInContextInternal(ctx.Context(), user)+ next(huma.WithContext(ctx, newCtx))+ return+ }+ if user, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(pkgutils.HeaderApiKey)); ok {+ newCtx := setUserInContextInternal(ctx.Context(), user)+ next(huma.WithContext(ctx, newCtx))+ return+ }+ _ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized: invalid API key")+}+func handleBearerAuthInternal(api huma.API, ctx huma.Context, authService *services.AuthService) (huma.Context, bool) {user, sessionID, err := tryBearerAuthInternal(ctx, authService)if err == nil && user != nil {diff --git a/backend/api/middleware/auth_test.go b/backend/api/middleware/auth_test.goindex 7e4678d70..a83c1b216 100644--- a/backend/api/middleware/auth_test.go+++ b/backend/api/middleware/auth_test.go@@ -5,14 +5,20 @@ import ("net/http""net/http/httptest""testing"+ "time""github.com/danielgtaylor/huma/v2""github.com/danielgtaylor/huma/v2/adapters/humaecho""github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models""github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/types/auth"+ glsqlite "github.com/glebarez/sqlite"+ "github.com/golang-jwt/jwt/v5""github.com/labstack/echo/v4""github.com/stretchr/testify/require"+ "gorm.io/gorm")type secureInput struct{}@@ -152,3 +158,96 @@ func TestParseSecurityRequirements(t *testing.T) {})}}++func setupAuthMiddlewareTestDBInternal(t *testing.T) *database.DB {+ t.Helper()+ db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.AutoMigrate(&models.SettingVariable{}, &models.User{}, &models.UserSession{}))+ return &database.DB{DB: db}+}++func TestNewAuthBridge_OpportunisticAuthOnPublicRoute(t *testing.T) {+ db := setupAuthMiddlewareTestDBInternal(t)+ userSvc := services.NewUserService(db)+ sessionSvc := services.NewSessionService(db)++ jwtSecret := "test-secret-please-do-not-use-in-prod"+ cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}+ authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, jwtSecret, cfg)++ _, err := userSvc.CreateUser(context.Background(), &models.User{+ BaseModel: models.BaseModel{ID: "u-logout"},+ Username: "logouttest",+ Roles: models.StringSlice{"user"},+ })+ require.NoError(t, err)++ exp := time.Now().Add(5 * time.Minute)+ session, _, err := sessionSvc.CreateSession(context.Background(), "u-logout", exp, auth.SessionMeta{})+ require.NoError(t, err)++ claims := jwt.MapClaims{+ "jti": "u-logout",+ "sub": "access",+ "iat": time.Now().Unix(),+ "exp": exp.Unix(),+ "sid": session.ID,+ "user_id": "u-logout",+ "username": "logouttest",+ "roles": []string{"user"},+ }+ token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(jwtSecret))+ require.NoError(t, err)++ router := echo.New()+ apiGroup := router.Group("/api")+ humaConfig := huma.DefaultConfig("test", "1.0.0")+ humaConfig.Components.SecuritySchemes = map[string]*huma.SecurityScheme{+ "BearerAuth": {Type: "http", Scheme: "bearer"},+ }+ api := humaecho.NewWithGroup(router, apiGroup, humaConfig)+ api.UseMiddleware(NewAuthBridge(api, authSvc, nil, nil, &config.Config{}))++ var sawSessionID string+ huma.Register(api, huma.Operation{+ OperationID: "public-with-session",+ Method: http.MethodPost,+ Path: "/public",+ Security: []map[string][]string{},+ }, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {+ if sid, ok := GetCurrentSessionIDFromContext(ctx); ok {+ sawSessionID = sid+ }+ return &secureOutput{}, nil+ })++ t.Run("populates session ID when valid token presented", func(t *testing.T) {+ sawSessionID = ""+ req := httptest.NewRequest(http.MethodPost, "/api/public", nil)+ req.Header.Set("Authorization", "Bearer "+token)+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+ require.Equal(t, session.ID, sawSessionID)+ })++ t.Run("succeeds with no token", func(t *testing.T) {+ sawSessionID = ""+ req := httptest.NewRequest(http.MethodPost, "/api/public", nil)+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+ require.Equal(t, "", sawSessionID)+ })++ t.Run("succeeds with invalid token (does not block)", func(t *testing.T) {+ sawSessionID = ""+ req := httptest.NewRequest(http.MethodPost, "/api/public", nil)+ req.Header.Set("Authorization", "Bearer not-a-valid-token")+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+ require.Equal(t, "", sawSessionID)+ })+}diff --git a/backend/api/webhooks_trigger.go b/backend/api/webhooks_trigger.goindex eed0ecdbb..7cd72f693 100644--- a/backend/api/webhooks_trigger.go+++ b/backend/api/webhooks_trigger.go@@ -10,10 +10,7 @@ import (// RegisterWebhookTrigger registers the public (unauthenticated) trigger endpoint.// The token in the URL is the sole authentication mechanism.-//-// Security note: tokens appear in server access logs and browser history. Ensure access-// logs are appropriately protected, and consider rate-limiting this endpoint at the-// reverse-proxy level.+// Rate-limited via PerIPRateLimitForPaths in router_bootstrap.go.func RegisterWebhookTrigger(g *echo.Group, webhookService *services.WebhookService) {g.POST("/webhooks/trigger/:token", func(c echo.Context) error {if webhookService == nil {diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex 6298c5f95..cc513979d 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -3,6 +3,7 @@ package bootstrapimport ("context""log/slog"+ "net""path""strings"@@ -117,6 +118,30 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)e.HideBanner = truee.HidePort = true+ if cfg.TrustedProxies == "" {+ e.IPExtractor = echo.ExtractIPDirect()+ } else {+ var opts []echo.TrustOption+ for _, cidr := range strings.Split(cfg.TrustedProxies, ",") {+ cidr = strings.TrimSpace(cidr)+ if cidr == "" {+ continue+ }+ _, ipnet, err := net.ParseCIDR(cidr)+ if err != nil {+ slog.Warn("invalid TRUSTED_PROXIES CIDR, ignoring", "cidr", cidr, "error", err)+ continue+ }+ opts = append(opts, echo.TrustIPRange(ipnet))+ }+ if len(opts) == 0 {+ slog.Warn("TRUSTED_PROXIES set but no valid CIDRs found; falling back to direct IP extraction")+ e.IPExtractor = echo.ExtractIPDirect()+ } else {+ e.IPExtractor = echo.ExtractIPFromXFFHeader(opts...)+ }+ }+e.Use(echomiddleware.Recover())e.Use(requestLoggerMiddlewareInternal()) //nolint:contextcheck@@ -126,6 +151,18 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)e.Use(middleware.NewCORSMiddleware(cfg).Add())apiGroup := e.Group("/api")++ apiGroup.Use(middleware.PerIPRateLimitForPaths(+ []string{+ "/api/auth/login",+ "/api/auth/refresh",+ "/api/oidc/callback",+ }, 5, 5,+ ))+ apiGroup.Use(middleware.PerIPRateLimitForPaths(+ []string{"/api/webhooks/trigger/:token"}, 60, 10,+ ))+tunnelRegistry := edge.NewTunnelRegistry()edge.SetDefaultRegistry(tunnelRegistry)envResolver := func(ctx context.Context, id string) (string, *string, bool, error) {diff --git a/backend/internal/config/config.go b/backend/internal/config/config.goindex 9e4c859f8..0883fef8e 100644--- a/backend/internal/config/config.go+++ b/backend/internal/config/config.go@@ -82,6 +82,8 @@ type Config struct {EdgeMTLSServerName string `env:"EDGE_MTLS_SERVER_NAME" default:""`EdgeMTLSAssetsDir string `env:"EDGE_MTLS_ASSETS_DIR" default:""`+ TrustedProxies string `env:"TRUSTED_PROXIES" default:""`+FilePerm os.FileMode `env:"FILE_PERM" default:"0644"`DirPerm os.FileMode `env:"DIR_PERM" default:"0755"`GitWorkDir string `env:"GIT_WORK_DIR" default:"data/git"`diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.goindex 60ae6e174..0ec9ba31f 100644--- a/backend/internal/config/config_test.go+++ b/backend/internal/config/config_test.go@@ -503,6 +503,29 @@ func TestSetFieldValueInternal_DurationUsesFieldTagDefault(t *testing.T) {assert.Equal(t, 2*time.Hour, cfg.SessionTimeout)}+func TestConfig_TrustedProxies(t *testing.T) {+ orig := os.Getenv("TRUSTED_PROXIES")+ defer restoreEnv("TRUSTED_PROXIES", orig)++ t.Run("Default empty", func(t *testing.T) {+ unsetEnv(t, "TRUSTED_PROXIES")+ cfg := Load()+ assert.Equal(t, "", cfg.TrustedProxies)+ })++ t.Run("Single CIDR", func(t *testing.T) {+ setEnv(t, "TRUSTED_PROXIES", "10.0.0.0/8")+ cfg := Load()+ assert.Equal(t, "10.0.0.0/8", cfg.TrustedProxies)+ })++ t.Run("Multiple CIDRs", func(t *testing.T) {+ setEnv(t, "TRUSTED_PROXIES", "10.0.0.0/8,192.168.0.0/16,172.16.0.0/12")+ cfg := Load()+ assert.Equal(t, "10.0.0.0/8,192.168.0.0/16,172.16.0.0/12", cfg.TrustedProxies)+ })+}+func restoreEnv(key, value string) {if value == "" {_ = os.Unsetenv(key)diff --git a/backend/internal/configschema/schema_test.go b/backend/internal/configschema/schema_test.goindex 378835432..1c172552d 100644--- a/backend/internal/configschema/schema_test.go+++ b/backend/internal/configschema/schema_test.go@@ -261,6 +261,7 @@ var expectedEnvConfigVars = []string{"TLS_ENABLED","TLS_KEY_FILE","TRIVY_SCAN_TIMEOUT",+ "TRUSTED_PROXIES","TZ","UI_CONFIGURATION_DISABLED","UPDATE_CHECK_DISABLED",diff --git a/backend/internal/middleware/rate_limit_middleware.go b/backend/internal/middleware/rate_limit_middleware.goindex 464eb5270..20cba51a6 100644--- a/backend/internal/middleware/rate_limit_middleware.go+++ b/backend/internal/middleware/rate_limit_middleware.go@@ -165,6 +165,31 @@ func agentTokenRateLimitKeyInternal(token string) string {return hex.EncodeToString(sum[:])}+// PerIPRateLimitForPaths returns an Echo middleware that applies a per-IP+// rate limit only when c.Path() (the registered route pattern) is in paths.+// Each path gets its own independent token bucket, so traffic on one path+// does not deplete the budget for another (e.g. a login burst will not+// block a concurrent token refresh).+func PerIPRateLimitForPaths(paths []string, perMinute int, burst int) echo.MiddlewareFunc {+ limiters := make(map[string]echo.MiddlewareFunc, len(paths))+ for _, p := range paths {+ limiters[p] = PerIPRateLimit(perMinute, burst)+ }+ return func(next echo.HandlerFunc) echo.HandlerFunc {+ gatedByPath := make(map[string]echo.HandlerFunc, len(limiters))+ for p, rl := range limiters {+ gatedByPath[p] = rl(next)+ }+ return func(c echo.Context) error {+ gated, ok := gatedByPath[c.Path()]+ if !ok {+ return next(c)+ }+ return gated(c)+ }+ }+}+func clientIPForRateLimitInternal(c echo.Context) string {if ip := strings.TrimSpace(c.RealIP()); ip != "" {return ipdiff --git a/backend/internal/middleware/rate_limit_middleware_test.go b/backend/internal/middleware/rate_limit_middleware_test.goindex a4f80c3aa..0d3768d1a 100644--- a/backend/internal/middleware/rate_limit_middleware_test.go+++ b/backend/internal/middleware/rate_limit_middleware_test.go@@ -68,6 +68,100 @@ func TestStackedAgentEnrollmentRateLimits_KeepIPBackPressure(t *testing.T) {require.Equal(t, http.StatusTooManyRequests, doReq("token-b"))}+func TestPerIPRateLimitForPaths_AppliesOnlyToConfiguredPaths(t *testing.T) {+ router := echo.New()+ router.IPExtractor = echo.ExtractIPDirect()++ router.Use(PerIPRateLimitForPaths([]string{"/limited"}, 60, 1))+ router.POST("/limited", func(c echo.Context) error {+ return c.NoContent(http.StatusOK)+ })+ router.POST("/unlimited", func(c echo.Context) error {+ return c.NoContent(http.StatusOK)+ })++ doReq := func(path string) int {+ req := httptest.NewRequest(http.MethodPost, path, nil)+ req.RemoteAddr = "192.0.2.10:4000"+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ return rec.Code+ }++ require.Equal(t, http.StatusOK, doReq("/limited"))+ require.Equal(t, http.StatusTooManyRequests, doReq("/limited"))++ for i := 0; i < 10; i++ {+ require.Equal(t, http.StatusOK, doReq("/unlimited"))+ }+}++func TestPerIPRateLimitForPaths_TracksDistinctIPs(t *testing.T) {+ router := echo.New()+ router.IPExtractor = echo.ExtractIPDirect()++ router.Use(PerIPRateLimitForPaths([]string{"/limited"}, 60, 1))+ router.POST("/limited", func(c echo.Context) error {+ return c.NoContent(http.StatusOK)+ })++ doReqFrom := func(addr string) int {+ req := httptest.NewRequest(http.MethodPost, "/limited", nil)+ req.RemoteAddr = addr+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ return rec.Code+ }++ require.Equal(t, http.StatusOK, doReqFrom("192.0.2.10:1000"))+ require.Equal(t, http.StatusTooManyRequests, doReqFrom("192.0.2.10:1000"))+ require.Equal(t, http.StatusOK, doReqFrom("192.0.2.11:1000"))+}++func TestPerIPRateLimitForPaths_IndependentBucketPerPath(t *testing.T) {+ router := echo.New()+ router.IPExtractor = echo.ExtractIPDirect()++ router.Use(PerIPRateLimitForPaths([]string{"/a", "/b"}, 60, 1))+ router.POST("/a", func(c echo.Context) error { return c.NoContent(http.StatusOK) })+ router.POST("/b", func(c echo.Context) error { return c.NoContent(http.StatusOK) })++ doReq := func(path string) int {+ req := httptest.NewRequest(http.MethodPost, path, nil)+ req.RemoteAddr = "192.0.2.10:4000"+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ return rec.Code+ }++ require.Equal(t, http.StatusOK, doReq("/a"))+ require.Equal(t, http.StatusTooManyRequests, doReq("/a"))+ // /b has its own bucket and must not be affected by /a's burst exhaustion.+ require.Equal(t, http.StatusOK, doReq("/b"))+ require.Equal(t, http.StatusTooManyRequests, doReq("/b"))+}++func TestPerIPRateLimitForPaths_RouteParamsDoNotEscapeFilter(t *testing.T) {+ router := echo.New()+ router.IPExtractor = echo.ExtractIPDirect()++ router.Use(PerIPRateLimitForPaths([]string{"/webhooks/trigger/:token"}, 60, 1))+ router.POST("/webhooks/trigger/:token", func(c echo.Context) error {+ return c.NoContent(http.StatusOK)+ })++ doReq := func(token string) int {+ req := httptest.NewRequest(http.MethodPost, "/webhooks/trigger/"+token, nil)+ req.RemoteAddr = "192.0.2.10:4000"+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ return rec.Code+ }++ require.Equal(t, http.StatusOK, doReq("token-aaa"))+ require.Equal(t, http.StatusTooManyRequests, doReq("token-bbb"))+}+func TestIPRateLimiter_EnforcesMaxEntriesForRecentClients(t *testing.T) {limiter := newIPRateLimiterInternal(1, 1)limiter.maxEntries = 3diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex 6187a0d71..3205d1dc0 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -2,6 +2,8 @@ package servicesimport ("context"+ "crypto/sha256"+ "encoding/hex""errors""fmt""log/slog"@@ -11,6 +13,7 @@ import ("github.com/getarcaneapp/arcane/backend/internal/common""github.com/getarcaneapp/arcane/backend/internal/config""github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/pkg/utils/cache""github.com/getarcaneapp/arcane/backend/pkg/utils/jwtclaims""github.com/getarcaneapp/arcane/types/auth""github.com/golang-jwt/jwt/v5"@@ -58,6 +61,11 @@ type refreshClaims struct {AppVersion string `json:"app_version,omitempty"`}+type verifiedTokenEntry struct {+ User models.User+ SessionID string+}+type AuthService struct {userService *UserServicesettingsService *SettingsService@@ -66,6 +74,11 @@ type AuthService struct {jwtSecret []byterefreshExpiry time.Durationconfig *config.Config+ // tokenCache is a per-process in-memory cache. In horizontally-scaled+ // deployments, RevokeSession / ChangePassword / InvalidateUserTokenCache+ // only purge the local instance; peers continue to accept the token until+ // their own TTL expires. The TTL is kept short to bound this window.+ tokenCache *cache.TTL[verifiedTokenEntry]}func NewAuthService(userService *UserService, settingsService *SettingsService, eventService *EventService, sessionService *SessionService, jwtSecret string, cfg *config.Config) *AuthService {@@ -77,6 +90,7 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,jwtSecret: jwtclaims.CheckOrGenerateJwtSecret(jwtSecret),refreshExpiry: cfg.JWTRefreshExpiry,config: cfg,+ tokenCache: cache.NewTTL[verifiedTokenEntry](15 * time.Second),}}@@ -683,6 +697,12 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*modreturn nil, "", &common.SessionServiceUnavailableError{}}+ tokenHash := hashTokenInternal(accessToken)+ if cached, ok := s.tokenCache.Get(tokenHash); ok {+ u := cached.User+ return &u, cached.SessionID, nil+ }+// Verify user exists in DB// This ensures that if the database is wiped or user is deleted, the token becomes invalid// even if the JWT signature is still valid (e.g. same JWT_SECRET).@@ -705,10 +725,17 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*modreturn nil, "", err}+ s.tokenCache.Put(tokenHash, verifiedTokenEntry{User: *dbUser, SessionID: session.ID})+return dbUser, session.ID, nil}-func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassword, newPassword string) error {+func hashTokenInternal(token string) string {+ sum := sha256.Sum256([]byte(token))+ return hex.EncodeToString(sum[:])+}++func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassword, newPassword, currentSessionID string) error {if s.sessionService == nil {return &common.SessionServiceUnavailableError{}}@@ -734,13 +761,29 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassworif _, err = s.userService.UpdateUser(ctx, user); err != nil {return err}- return s.sessionService.RevokeAllUserSessions(ctx, userID)+ s.tokenCache.DeleteFunc(func(_ string, e verifiedTokenEntry) bool {+ return e.User.ID == userID && e.SessionID != currentSessionID+ })+ return s.sessionService.RevokeAllUserSessionsExcept(ctx, userID, currentSessionID)+}++// InvalidateUserTokenCache purges all cached token verifications for a user.+// Call this after admin-initiated role changes, account disable, or user+// deletion so stale verifications cannot grant access for the cache TTL.+func (s *AuthService) InvalidateUserTokenCache(userID string) {+ if s.tokenCache == nil || strings.TrimSpace(userID) == "" {+ return+ }+ s.tokenCache.DeleteFunc(func(_ string, e verifiedTokenEntry) bool {+ return e.User.ID == userID+ })}func (s *AuthService) RevokeSession(ctx context.Context, sessionID string) error {if s.sessionService == nil {return nil}+ s.tokenCache.DeleteFunc(func(_ string, e verifiedTokenEntry) bool { return e.SessionID == sessionID })return s.sessionService.RevokeSession(ctx, sessionID)}diff --git a/backend/internal/services/auth_service_test.go b/backend/internal/services/auth_service_test.goindex d8a646b40..97b3193a4 100644--- a/backend/internal/services/auth_service_test.go+++ b/backend/internal/services/auth_service_test.go@@ -15,6 +15,7 @@ import ("github.com/getarcaneapp/arcane/backend/internal/config""github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/pkg/utils/cache""github.com/getarcaneapp/arcane/types/auth""github.com/golang-jwt/jwt/v5")@@ -37,12 +38,14 @@ func newTestAuthService(secret string) *AuthService {jwtSecret: b,refreshExpiry: 24 * time.Hour,config: &config.Config{},+ tokenCache: cache.NewTTL[verifiedTokenEntry](15 * time.Second),}}return &AuthService{jwtSecret: []byte(secret),refreshExpiry: 24 * time.Hour,config: &config.Config{},+ tokenCache: cache.NewTTL[verifiedTokenEntry](15 * time.Second),}}@@ -485,7 +488,7 @@ func TestChangePassword_RevokesAllSessions(t *testing.T) {sessionA, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))sessionB, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))- require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "new-password"))+ require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "new-password", ""))sessionA, err = s.sessionService.GetSessionByID(context.Background(), sessionA.ID)require.NoError(t, err)@@ -495,6 +498,37 @@ func TestChangePassword_RevokesAllSessions(t *testing.T) {require.NotNil(t, sessionB.RevokedAt)}+func TestChangePassword_KeepsCurrentSessionAlive(t *testing.T) {+ db := setupAuthServiceTestDB(t)+ userSvc := NewUserService(db)+ s := newTestAuthService("")+ s.userService = userSvc+ s.sessionService = NewSessionService(db)++ passwordHash, err := userSvc.hashPassword("old-password")+ require.NoError(t, err)+ user := &models.User{+ BaseModel: models.BaseModel{ID: "u-keep"},+ Username: "keep-user",+ PasswordHash: passwordHash,+ Roles: models.StringSlice{"user"},+ }+ _, err = userSvc.CreateUser(context.Background(), user)+ require.NoError(t, err)++ current, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))+ other, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))++ require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "new-password", current.ID))++ current, err = s.sessionService.GetSessionByID(context.Background(), current.ID)+ require.NoError(t, err)+ other, err = s.sessionService.GetSessionByID(context.Background(), other.ID)+ require.NoError(t, err)+ require.Nil(t, current.RevokedAt, "current session should remain active")+ require.NotNil(t, other.RevokedAt, "other sessions should be revoked")+}+func TestRefreshToken_RejectsNonHMACAlg(t *testing.T) {s := newTestAuthService("")exp := time.Now().Add(5 * time.Minute)diff --git a/backend/internal/services/session_service.go b/backend/internal/services/session_service.goindex 8d7842a58..88ded2334 100644--- a/backend/internal/services/session_service.go+++ b/backend/internal/services/session_service.go@@ -152,15 +152,20 @@ func hashRefreshJTIInternal(jti string) string {return hex.EncodeToString(sum[:])}-func (s *SessionService) RevokeAllUserSessions(ctx context.Context, userID string) error {+// RevokeAllUserSessionsExcept revokes every active session for userID, leaving+// exceptSessionID active. Pass "" to revoke all sessions.+func (s *SessionService) RevokeAllUserSessionsExcept(ctx context.Context, userID, exceptSessionID string) error {if strings.TrimSpace(userID) == "" {return ErrInvalidToken}now := time.Now()- if err := s.db.WithContext(ctx).Model(&models.UserSession{}).- Where("user_id = ? AND revoked_at IS NULL", userID).- Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {+ query := s.db.WithContext(ctx).Model(&models.UserSession{}).+ Where("user_id = ? AND revoked_at IS NULL", userID)+ if strings.TrimSpace(exceptSessionID) != "" {+ query = query.Where("id <> ?", exceptSessionID)+ }+ if err := query.Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {return fmt.Errorf("failed to revoke user sessions: %w", err)}return nildiff --git a/backend/pkg/utils/cache/ttl.go b/backend/pkg/utils/cache/ttl.gonew file mode 100644index 000000000..1b5011422--- /dev/null+++ b/backend/pkg/utils/cache/ttl.go@@ -0,0 +1,66 @@+package cache++import (+ "sync"+ "time"+)++type entry[V any] struct {+ value V+ expiresAt time.Time+}++// TTL is a concurrency-safe in-memory cache with per-entry expiration.+type TTL[V any] struct {+ mu sync.RWMutex+ entries map[string]*entry[V]+ ttl time.Duration+ lastSweep time.Time+}++func NewTTL[V any](ttl time.Duration) *TTL[V] {+ return &TTL[V]{+ entries: make(map[string]*entry[V]),+ ttl: ttl,+ }+}++func (c *TTL[V]) Get(key string) (V, bool) {+ c.mu.RLock()+ defer c.mu.RUnlock()+ e, ok := c.entries[key]+ if !ok || time.Now().After(e.expiresAt) {+ var zero V+ return zero, false+ }+ return e.value, true+}++func (c *TTL[V]) Put(key string, value V) {+ c.mu.Lock()+ defer c.mu.Unlock()+ now := time.Now()+ if now.Sub(c.lastSweep) > c.ttl {+ for k, e := range c.entries {+ if now.After(e.expiresAt) {+ delete(c.entries, k)+ }+ }+ c.lastSweep = now+ }+ c.entries[key] = &entry[V]{+ value: value,+ expiresAt: now.Add(c.ttl),+ }+}++// DeleteFunc removes all entries where the predicate returns true.+func (c *TTL[V]) DeleteFunc(fn func(key string, value V) bool) {+ c.mu.Lock()+ defer c.mu.Unlock()+ for k, e := range c.entries {+ if fn(k, e.value) {+ delete(c.entries, k)+ }+ }+}