Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(release): stabilize backend rehearsal blockers

Richard Courtman8ed5e74912d5
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f0611eb940..4dd0bcd225 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -646,6 +646,11 @@ stay owned by the configured router data path: session, CSRF, and
recovery-token runtime state may not silently bind themselves to hidden
`/etc/pulse` fallback initialization or retain old-path state after a
reconfiguration.
+That same shared `internal/api/` dependency also assumes those auth stores
+tear down synchronously when lifecycle-adjacent routers or hosted runtimes are
+reconfigured: session and CSRF workers may not rely on best-effort background
+signals that can wedge teardown, block temp-path cleanup, or leave first-
+session and hosted handoff validation hanging behind a stale auth worker.
That same path-ownership rule also applies to bootstrap-token recovery and
adjacent hosted billing side effects that share the `internal/api/` boundary:
CLI/bootstrap retrieval, webhook dedupe state, and customer-index persistence
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index c4c5bcd420..d34573ce7e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -160,6 +160,7 @@ Own canonical runtime payload shapes between backend and frontend.
19. Keep mobile onboarding payload reads aligned with the server-owned relay-mobile credential: `internal/api/router_routes_ai_relay.go`, `internal/api/onboarding_handlers.go`, and `internal/api/contract_test.go` must allow the dedicated `relay:mobile:access` scope to reach the governed QR, deep-link, and connection-validation payloads without reintroducing a broader `settings:read` requirement for token-authenticated pairing clients.
20. Keep hosted billing-state quickstart payload fields on the shared API contract: `internal/api/hosted_entitlement_refresh.go`, `internal/api/subscription_state_handlers.go`, and `internal/api/contract_test.go` must preserve `quickstart_credits_granted`, `quickstart_credits_used`, and `quickstart_credits_granted_at` through hosted signup, hosted lease refresh, and billing-state reads instead of letting lease rewrites silently erase seeded quickstart inventory.
21. Keep hosted AI settings bootstrap on the shared API contract: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`, `internal/api/ai_handler.go`, and `internal/api/contract_test.go` must treat a missing `ai.enc` in hosted mode as a canonical bootstrap condition, persist one machine-owned quickstart-backed AI config when hosted entitlements grant AI capability, and preserve that configured settings payload as the same public contract that Chat, Patrol, and AI Settings consume.
+22. Keep shared auth-store and universal rate-limit behavior on canonical router ownership: `internal/api/router.go`, `internal/api/rate_limit_config.go`, `internal/api/session_store.go`, `internal/api/csrf_store.go`, `internal/api/cloud_handoff_handlers.go`, and `internal/api/contract_test.go` must keep session/CSRF persistence scoped to the configured runtime data path, shut those workers down synchronously during router teardown or reinitialization, preserve hosted browser-session precedence during handoff-adjacent auth checks, and ensure hosted rate-limit presentation plus in-memory limiter counters stay owned by the current router instance instead of leaking across fresh routers or test harnesses.
## Forbidden Paths
@@ -1593,6 +1594,11 @@ session, CSRF, and recovery-token stores may not silently self-initialize on
`sync.Once`; the configured router data path must remain the canonical owner of
those persistence stores, and reinitializing that data path must replace the
old runtime store rather than leaking prior-path state forward.
+That same auth-persistence boundary also owns teardown semantics: session and
+CSRF persistence workers must stop synchronously when the runtime shuts down or
+reinitializes, rather than depending on best-effort background signals that can
+leave hosted auth checks, handoff tests, or temp-dir cleanup blocked behind a
+worker that never observes shutdown.
That same configured-path rule also applies to runtime auth/config reloads:
`internal/config/watcher.go` may use `PULSE_AUTH_CONFIG_DIR` only as an
explicit override, but otherwise it must watch the resolved runtime
@@ -1732,6 +1738,12 @@ is considered, so hosted protected routes such as relay-mobile token minting,
onboarding reads, and billing-admin/API surfaces stay reachable after cloud
handoff instead of flattening the operator back to `anonymous` or demanding a
bearer token from the browser as soon as the tenant has minted one.
+That same hosted entry boundary also owns rate-limit presentation and state
+scoping for canonical router surfaces: hosted trial-signup verification and
+checkout routes must render the hosted rate-limit guidance instead of a bare
+generic `Too Many Requests`, and the universal API limiter must stay scoped to
+the owning router configuration so one router instance or test harness cannot
+poison a fresh router's contract state through leaked in-memory counters.
That same shared settings-scope contract must then preserve canonical
org-management privilege on the tenant side: when a hosted or multi-tenant
request is scoped to a non-default org, `internal/api/security_setup_fix.go`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index cbb3bd1243..90d8e41fcd 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -121,6 +121,12 @@ The recovery backend is a real product boundary, not just a helper package:
`internal/recovery/` owns per-tenant SQLite persistence, rollup derivation,
query filtering, and recovery-point indexing for the `/api/recovery/*`
surfaces.
+That same shared `internal/api/` dependency also assumes auth-persistence
+teardown is synchronous when recovery-adjacent runtimes reinitialize. Session,
+CSRF, and recovery-token workers may not leave stale background goroutines or
+half-shutdown path ownership behind, because hosted handoff, recovery
+inspection, and adjacent temp-path tests all depend on the same canonical
+runtime data-dir authority being replaceable without hangs or leaked state.
That shared `internal/api/` dependency now also assumes hosted tenant AI
bootstrap and chat-runtime reads resolve through one effective hosted billing
lease before storage- or recovery-adjacent runtime consumers inspect
diff --git a/internal/api/cloud_handoff_handlers.go b/internal/api/cloud_handoff_handlers.go
index d9e99bd5fe..36a52f2796 100644
--- a/internal/api/cloud_handoff_handlers.go
+++ b/internal/api/cloud_handoff_handlers.go
@@ -41,6 +41,10 @@ type jtiReplayStore struct {
initErr error
}
+const deleteExpiredHandoffJTIQuery = `
+DELETE FROM handoff_jti INDEXED BY idx_handoff_jti_expires_at
+WHERE expires_at <= ?`
+
func (s *jtiReplayStore) init() {
s.once.Do(func() {
dir := filepath.Clean(s.configDir)
@@ -132,7 +136,7 @@ func (s *jtiReplayStore) checkAndStore(jti string, expiresAt time.Time) (stored
defer s.mu.Unlock()
now := time.Now().UTC().Unix()
- if _, err := s.db.Exec(`DELETE FROM handoff_jti WHERE expires_at <= ?`, now); err != nil {
+ if _, err := s.db.Exec(deleteExpiredHandoffJTIQuery, now); err != nil {
return false, fmt.Errorf("cleanup handoff jti: %w", err)
}
diff --git a/internal/api/cloud_handoff_queryplan_test.go b/internal/api/cloud_handoff_queryplan_test.go
index 5aaea0b508..1217459827 100644
--- a/internal/api/cloud_handoff_queryplan_test.go
+++ b/internal/api/cloud_handoff_queryplan_test.go
@@ -13,7 +13,7 @@ func TestJTIReplayStoreQueryPlanUsesExpiryIndex(t *testing.T) {
store, now := newJTIReplayPlanTestStore(t)
- plan := explainHandoffQueryPlan(t, store.db, `DELETE FROM handoff_jti WHERE expires_at <= ?`, now.Unix())
+ plan := explainHandoffQueryPlan(t, store.db, deleteExpiredHandoffJTIQuery, now.Unix())
if containsHandoffFullTableScan(plan) {
t.Fatalf("cleanup query uses full table scan on handoff_jti\nPlan:\n%s", plan)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index a582b12ddd..f0beb4cceb 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -1446,6 +1446,38 @@ func TestContract_HostedSessionAuthPrecedesAnonymousFallback(t *testing.T) {
}
}
+func TestContract_UniversalRateLimitStateIsScopedPerRouterConfig(t *testing.T) {
+ handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ first := UniversalRateLimitMiddlewareWithConfig(newEndpointRateLimitConfig(), handler)
+ second := UniversalRateLimitMiddlewareWithConfig(newEndpointRateLimitConfig(), handler)
+
+ makeRequest := func(target http.Handler) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil)
+ req.RemoteAddr = "198.51.100.25:12345"
+ rec := httptest.NewRecorder()
+ target.ServeHTTP(rec, req)
+ return rec
+ }
+
+ for i := 0; i < 10; i++ {
+ if rec := makeRequest(first); rec.Code != http.StatusOK {
+ t.Fatalf("first router request %d status = %d, want %d", i+1, rec.Code, http.StatusOK)
+ }
+ }
+
+ if rec := makeRequest(first); rec.Code != http.StatusTooManyRequests {
+ t.Fatalf("first router overflow status = %d, want %d", rec.Code, http.StatusTooManyRequests)
+ }
+
+ if rec := makeRequest(second); rec.Code != http.StatusOK {
+ t.Fatalf("second router first request status = %d, want %d", rec.Code, http.StatusOK)
+ }
+}
+
func TestContract_HostedOrgManagerSessionCanMintRelayMobileToken(t *testing.T) {
defer SetMultiTenantEnabled(false)
SetMultiTenantEnabled(true)
diff --git a/internal/api/csrf_store.go b/internal/api/csrf_store.go
index 142673c7b1..af3c18c078 100644
--- a/internal/api/csrf_store.go
+++ b/internal/api/csrf_store.go
@@ -151,9 +151,8 @@ func (c *CSRFTokenStore) Shutdown() {
if c.saveTicker != nil {
c.saveTicker.Stop()
}
- select {
- case c.stopChan <- true:
- default:
+ if c.stopChan != nil {
+ close(c.stopChan)
}
})
if c.workerDone != nil {
diff --git a/internal/api/csrf_store_test.go b/internal/api/csrf_store_test.go
index 15b68cd6eb..f03ff97bf6 100644
--- a/internal/api/csrf_store_test.go
+++ b/internal/api/csrf_store_test.go
@@ -673,3 +673,22 @@ func TestCSRFTokenStore_InitReconfiguresDataPath(t *testing.T) {
t.Fatalf("expected reconfigured csrf tokens file to exist: %v", err)
}
}
+
+func TestCSRFTokenStore_ShutdownReturnsWithoutWaitingForWorkerReceive(t *testing.T) {
+ storeDir := t.TempDir()
+ InitCSRFStore(storeDir)
+ store := GetCSRFStore()
+ t.Cleanup(resetCSRFStoreForTests)
+
+ done := make(chan struct{})
+ go func() {
+ store.Shutdown()
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(500 * time.Millisecond):
+ t.Fatal("Shutdown should not block waiting for the background worker to receive a stop signal")
+ }
+}
diff --git a/internal/api/rate_limit_config.go b/internal/api/rate_limit_config.go
index b00caee34b..89e14735fa 100644
--- a/internal/api/rate_limit_config.go
+++ b/internal/api/rate_limit_config.go
@@ -21,9 +21,8 @@ type EndpointRateLimitConfig struct {
var globalRateLimitConfig *EndpointRateLimitConfig
-// InitializeRateLimiters sets up rate limiters for all endpoint categories
-func InitializeRateLimiters() {
- globalRateLimitConfig = &EndpointRateLimitConfig{
+func newEndpointRateLimitConfig() *EndpointRateLimitConfig {
+ return &EndpointRateLimitConfig{
// Authentication endpoints: strict limits to prevent brute force
AuthEndpoints: NewRateLimiter(10, 1*time.Minute), // 10 attempts per minute
@@ -50,12 +49,24 @@ func InitializeRateLimiters() {
}
}
-// GetRateLimiterForEndpoint returns the appropriate rate limiter for a given endpoint
-func GetRateLimiterForEndpoint(path string, method string) *RateLimiter {
+func ensureGlobalRateLimitConfig() *EndpointRateLimitConfig {
if globalRateLimitConfig == nil {
InitializeRateLimiters()
}
+ return globalRateLimitConfig
+}
+
+// InitializeRateLimiters sets up rate limiters for all endpoint categories
+func InitializeRateLimiters() {
+ globalRateLimitConfig = newEndpointRateLimitConfig()
+}
+// GetRateLimiterForEndpoint returns the appropriate rate limiter for a given endpoint
+func GetRateLimiterForEndpoint(path string, method string) *RateLimiter {
+ return getRateLimiterForEndpoint(ensureGlobalRateLimitConfig(), path, method)
+}
+
+func getRateLimiterForEndpoint(cfg *EndpointRateLimitConfig, path string, method string) *RateLimiter {
// Normalize path
path = strings.ToLower(path)
@@ -67,18 +78,18 @@ func GetRateLimiterForEndpoint(path string, method string) *RateLimiter {
strings.Contains(path, "/api/security/regenerate-token") ||
strings.Contains(path, "/api/security/validate-token") ||
strings.Contains(path, "/api/auth") {
- return globalRateLimitConfig.AuthEndpoints
+ return cfg.AuthEndpoints
}
// Recovery endpoints
if strings.Contains(path, "/api/security/recovery") {
- return globalRateLimitConfig.RecoveryEndpoints
+ return cfg.RecoveryEndpoints
}
// Export/Import endpoints
if strings.Contains(path, "/api/config/export") ||
strings.Contains(path, "/api/config/import") {
- return globalRateLimitConfig.ExportEndpoints
+ return cfg.ExportEndpoints
}
// Configuration endpoints (write operations only)
@@ -86,24 +97,24 @@ func GetRateLimiterForEndpoint(path string, method string) *RateLimiter {
strings.Contains(path, "/api/config/system") ||
strings.Contains(path, "/api/config/webhooks") ||
strings.Contains(path, "/api/config/alerts")) {
- return globalRateLimitConfig.ConfigEndpoints
+ return cfg.ConfigEndpoints
}
// Configuration read endpoints get higher limits to prevent UI issues
if method == "GET" && (strings.Contains(path, "/api/config/") ||
strings.Contains(path, "/api/discover") ||
strings.Contains(path, "/api/security/status")) {
- return globalRateLimitConfig.PublicEndpoints // Use higher limit for reads
+ return cfg.PublicEndpoints // Use higher limit for reads
}
// Update endpoints
if strings.Contains(path, "/api/updates") {
- return globalRateLimitConfig.UpdateEndpoints
+ return cfg.UpdateEndpoints
}
// WebSocket endpoints
if strings.Contains(path, "/ws") {
- return globalRateLimitConfig.WebSocketEndpoints
+ return cfg.WebSocketEndpoints
}
// Public endpoints (no auth required)
@@ -111,20 +122,22 @@ func GetRateLimiterForEndpoint(path string, method string) *RateLimiter {
strings.Contains(path, "/api/version") ||
strings.Contains(path, "/api/security/status") ||
strings.Contains(path, "/metrics") {
- return globalRateLimitConfig.PublicEndpoints
+ return cfg.PublicEndpoints
}
// Default to general API rate limiter
- return globalRateLimitConfig.GeneralAPI
+ return cfg.GeneralAPI
}
// UniversalRateLimitMiddleware applies appropriate rate limiting to all endpoints
func UniversalRateLimitMiddleware(next http.Handler) http.Handler {
- // Initialize rate limiters if not already done
- if globalRateLimitConfig == nil {
- InitializeRateLimiters()
- }
+ return UniversalRateLimitMiddlewareWithConfig(ensureGlobalRateLimitConfig(), next)
+}
+func UniversalRateLimitMiddlewareWithConfig(cfg *EndpointRateLimitConfig, next http.Handler) http.Handler {
+ if cfg == nil {
+ cfg = newEndpointRateLimitConfig()
+ }
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip rate limiting for static assets
if !strings.HasPrefix(r.URL.Path, "/api") && !strings.HasPrefix(r.URL.Path, "/ws") {
@@ -156,7 +169,7 @@ func UniversalRateLimitMiddleware(next http.Handler) http.Handler {
}
// Get appropriate rate limiter for this endpoint
- limiter := GetRateLimiterForEndpoint(r.URL.Path, r.Method)
+ limiter := getRateLimiterForEndpoint(cfg, r.URL.Path, r.Method)
// Check rate limit
if !limiter.Allow(ip) {
diff --git a/internal/api/rate_limit_config_test.go b/internal/api/rate_limit_config_test.go
index 7ed7d59328..525c9de172 100644
--- a/internal/api/rate_limit_config_test.go
+++ b/internal/api/rate_limit_config_test.go
@@ -443,6 +443,47 @@ func TestUniversalRateLimitMiddleware_InitializesIfNeeded(t *testing.T) {
}
}
+func TestUniversalRateLimitMiddlewareWithConfig_UsesIndependentState(t *testing.T) {
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ firstConfig := newEndpointRateLimitConfig()
+ secondConfig := newEndpointRateLimitConfig()
+
+ first := UniversalRateLimitMiddlewareWithConfig(firstConfig, handler)
+ second := UniversalRateLimitMiddlewareWithConfig(secondConfig, handler)
+
+ firstLimiter := getRateLimiterForEndpoint(firstConfig, "/api/login", http.MethodPost)
+ testIP := "203.0.113.199"
+
+ makeRequest := func() *http.Request {
+ req := httptest.NewRequest(http.MethodPost, "/api/login", nil)
+ req.RemoteAddr = testIP + ":12345"
+ return req
+ }
+
+ for i := 0; i < firstLimiter.limit; i++ {
+ rr := httptest.NewRecorder()
+ first.ServeHTTP(rr, makeRequest())
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected first middleware OK while under limit, got %d on request %d", rr.Code, i+1)
+ }
+ }
+
+ rr := httptest.NewRecorder()
+ first.ServeHTTP(rr, makeRequest())
+ if rr.Code != http.StatusTooManyRequests {
+ t.Fatalf("expected first middleware to hit rate limit, got %d", rr.Code)
+ }
+
+ rr = httptest.NewRecorder()
+ second.ServeHTTP(rr, makeRequest())
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected second middleware to start with fresh state, got %d", rr.Code)
+ }
+}
+
func TestUniversalRateLimitMiddleware_StaticAssetBypass(t *testing.T) {
InitializeRateLimiters()
diff --git a/internal/api/router.go b/internal/api/router.go
index 37fd6895b8..3c4bc24d98 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -294,7 +294,7 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit
// Auth context middleware extracts user/token info BEFORE tenant middleware
handler = AuthContextMiddleware(cfg, r.mtMonitor, handler)
- handler = UniversalRateLimitMiddleware(handler)
+ handler = UniversalRateLimitMiddlewareWithConfig(newEndpointRateLimitConfig(), handler)
r.wrapped = handler
return r
}
diff --git a/internal/api/router_routes_ai_execute_test.go b/internal/api/router_routes_ai_execute_test.go
index 20ea05763f..cd5dc97c86 100644
--- a/internal/api/router_routes_ai_execute_test.go
+++ b/internal/api/router_routes_ai_execute_test.go
@@ -18,6 +18,8 @@ import (
// ai:execute API token for route-level /api/ai/execute tests.
func setupExecuteRouter(t *testing.T, ollamaURL string) (*Router, string) {
t.Helper()
+ resetPersistentAuthStoresForTests()
+ t.Cleanup(resetPersistentAuthStoresForTests)
rawToken := "ai-execute-route-token-" + t.Name() + ".12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeAIExecute}, nil)
@@ -33,6 +35,7 @@ func setupExecuteRouter(t *testing.T, ollamaURL string) (*Router, string) {
}
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+ t.Cleanup(router.shutdownBackgroundWorkers)
router.aiSettingsHandler.defaultConfig = cfg
router.aiSettingsHandler.defaultPersistence = persistence
svc := ai.NewService(persistence, nil)
diff --git a/internal/api/router_routes_ai_test_provider_test.go b/internal/api/router_routes_ai_test_provider_test.go
index 64b3c8a046..fd41864426 100644
--- a/internal/api/router_routes_ai_test_provider_test.go
+++ b/internal/api/router_routes_ai_test_provider_test.go
@@ -17,6 +17,8 @@ import (
// settings:write API token for route-level /api/ai/test/{provider} tests.
func setupTestProviderRouter(t *testing.T, ollamaURL string) (*Router, string) {
t.Helper()
+ resetPersistentAuthStoresForTests()
+ t.Cleanup(resetPersistentAuthStoresForTests)
rawToken := "ai-test-provider-route-token-" + t.Name() + ".12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsWrite}, nil)
@@ -32,6 +34,7 @@ func setupTestProviderRouter(t *testing.T, ollamaURL string) (*Router, string) {
}
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+ t.Cleanup(router.shutdownBackgroundWorkers)
router.aiSettingsHandler.defaultConfig = cfg
router.aiSettingsHandler.defaultPersistence = persistence
svc := ai.NewService(persistence, nil)
diff --git a/internal/api/session_store.go b/internal/api/session_store.go
index 60ace815ca..e4770bc93b 100644
--- a/internal/api/session_store.go
+++ b/internal/api/session_store.go
@@ -176,9 +176,8 @@ func (s *SessionStore) Shutdown() {
if s.saveTicker != nil {
s.saveTicker.Stop()
}
- select {
- case s.stopChan <- true:
- default:
+ if s.stopChan != nil {
+ close(s.stopChan)
}
})
if s.workerDone != nil {
diff --git a/internal/api/session_store_test.go b/internal/api/session_store_test.go
index 12411be7d9..9128e835e1 100644
--- a/internal/api/session_store_test.go
+++ b/internal/api/session_store_test.go
@@ -833,3 +833,20 @@ func TestSessionStore_LoadHashedSessions_DropsRefreshTokenWithoutCrypto(t *testi
t.Fatalf("expected refresh token to be dropped without crypto, got %q", session.OIDCRefreshToken)
}
}
+
+func TestSessionStore_ShutdownReturnsWithoutWaitingForWorkerReceive(t *testing.T) {
+ dir := t.TempDir()
+ store := NewSessionStore(dir)
+
+ done := make(chan struct{})
+ go func() {
+ store.Shutdown()
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(500 * time.Millisecond):
+ t.Fatal("Shutdown should not block waiting for the background worker to receive a stop signal")
+ }
+}
diff --git a/internal/cloudcp/routes.go b/internal/cloudcp/routes.go
index ea5134a3b4..4ba0828a13 100644
--- a/internal/cloudcp/routes.go
+++ b/internal/cloudcp/routes.go
@@ -120,10 +120,13 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {
// Hosted Pulse Pro trial signup: public form + checkout + return completion.
trialSignupHandlers := NewTrialSignupHandlers(deps.Config, deps.EmailSender, deps.TrialSignupStore, hostedEntitlements)
hostedEntitlementHandlers := NewHostedEntitlementHandlers(hostedEntitlements)
+ trialSignupRejected := func(w http.ResponseWriter, r *http.Request, retryAfter int) {
+ trialSignupHandlers.HandleRateLimitedTrialSignup(w, r, retryAfter)
+ }
mux.Handle("/start-pro-trial", trialSignupPageLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleStartProTrial)))
- mux.Handle("/api/trial-signup/request-verification", trialSignupVerificationLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleRequestVerification)))
+ mux.Handle("/api/trial-signup/request-verification", trialSignupVerificationLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleRequestVerification), trialSignupRejected))
mux.Handle("/trial-signup/verify", trialSignupVerifyLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleVerifyEmail)))
- mux.Handle("/api/trial-signup/checkout", trialSignupCheckoutLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleCheckout)))
+ mux.Handle("/api/trial-signup/checkout", trialSignupCheckoutLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleCheckout), trialSignupRejected))
mux.Handle("/trial-signup/complete", trialSignupCompleteLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleTrialSignupComplete)))
mux.Handle("/api/trial-signup/redeem", trialSignupRedeemLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleTrialSignupRedeem)))
mux.Handle("/api/entitlements/refresh", hostedEntitlementRefreshLimiter.Middleware(http.HandlerFunc(hostedEntitlementHandlers.HandleRefresh)))