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.

Render hosted trial rate limits inside trial UX

rcourtman445ef12a1d9f
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index c1ed61b95e..5f6d52f8be 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -248,6 +248,17 @@ That same rule also covers the self-hosted pricing page in
switch from trial to upgrade presentation, but the actual hosted handoff and
backend denial classification must still flow through the shared trial-start
owner instead of parsing raw trial-start status codes inline.
+The trial-start rate-limit contract is part of that same boundary. Local
+`/api/license/trial/start` retries are allowed as a short human-scale burst so
+operators can revisit the hosted handoff without getting locked out for a day,
+and both the local app server and hosted trial signup limiters must return the
+actual remaining backoff through `Retry-After` rather than a coarse full-window
+guess. Shared trial-start presentation must treat that backoff as canonical and
+surface it consistently instead of flattening every `429` into generic copy.
+For the hosted self-serve flow, that also means the public trial pages and form
+posts must render the owned Pulse trial experience with preserved instance/form
+state when rate limited, rather than dropping users onto a generic control-plane
+`Too Many Requests` response.
The hosted trial handoff page is part of that same boundary as well. It may
still use a secure hosted Stripe-backed session internally, but the customer
copy must present the flow as starting a trial for the originating Pulse
diff --git a/internal/cloudcp/ratelimit.go b/internal/cloudcp/ratelimit.go
index 44b62cf5d0..53c3f42ce2 100644
--- a/internal/cloudcp/ratelimit.go
+++ b/internal/cloudcp/ratelimit.go
@@ -29,6 +29,8 @@ type CPRateLimiter struct {
window time.Duration
}
+type CPRateLimitRejectedHandler func(w http.ResponseWriter, r *http.Request, retryAfter int)
+
// NewCPRateLimiter creates a rate limiter with the given limit per window.
func NewCPRateLimiter(limit int, window time.Duration) *CPRateLimiter {
if limit <= 0 {
@@ -46,10 +48,17 @@ func NewCPRateLimiter(limit int, window time.Duration) *CPRateLimiter {
// Allow checks whether the given IP is within the rate limit.
func (rl *CPRateLimiter) Allow(ip string) bool {
+ allowed, _ := rl.allowAt(ip, time.Now())
+ return allowed
+}
+
+// allowAt checks whether the given IP is within the rate limit at the provided
+// time and reports how long the caller should wait before retrying when
+// blocked.
+func (rl *CPRateLimiter) allowAt(ip string, now time.Time) (bool, time.Duration) {
rl.mu.Lock()
defer rl.mu.Unlock()
- now := time.Now()
cutoff := now.Add(-rl.window)
// Filter expired entries
@@ -62,26 +71,42 @@ func (rl *CPRateLimiter) Allow(ip string) bool {
if len(valid) >= rl.limit {
rl.attempts[ip] = valid
- return false
+ retryAfter := rl.window
+ if len(valid) > 0 {
+ retryAfter = valid[0].Add(rl.window).Sub(now)
+ }
+ if retryAfter < time.Second {
+ retryAfter = time.Second
+ }
+ return false, retryAfter
}
rl.attempts[ip] = append(valid, now)
- return true
+ return true, 0
}
// Middleware wraps an http.Handler with rate limiting.
func (rl *CPRateLimiter) Middleware(next http.Handler) http.Handler {
+ return rl.MiddlewareWithRejected(next, nil)
+}
+
+// MiddlewareWithRejected wraps an http.Handler with rate limiting and allows
+// callers to provide a custom blocked-response handler for customer-facing
+// flows such as hosted trial signup.
+func (rl *CPRateLimiter) MiddlewareWithRejected(next http.Handler, rejected CPRateLimitRejectedHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := clientIP(r)
- if !rl.Allow(ip) {
- retryAfter := int(math.Ceil(rl.window.Seconds()))
+ if allowed, retryDelay := rl.allowAt(ip, time.Now()); !allowed {
+ retryAfter := int(math.Ceil(retryDelay.Seconds()))
if retryAfter < 1 {
retryAfter = 1
}
- w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
- w.Header().Set("X-RateLimit-Limit", strconv.Itoa(rl.limit))
- w.Header().Set("X-RateLimit-Remaining", "0")
+ rl.writeRateLimitHeaders(w, retryAfter)
+ if rejected != nil {
+ rejected(w, r, retryAfter)
+ return
+ }
http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
return
}
@@ -89,6 +114,12 @@ func (rl *CPRateLimiter) Middleware(next http.Handler) http.Handler {
})
}
+func (rl *CPRateLimiter) writeRateLimitHeaders(w http.ResponseWriter, retryAfter int) {
+ w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
+ w.Header().Set("X-RateLimit-Limit", strconv.Itoa(rl.limit))
+ w.Header().Set("X-RateLimit-Remaining", "0")
+}
+
func clientIP(r *http.Request) string {
remote := extractRemoteIP(r.RemoteAddr)
if remote == "" {
diff --git a/internal/cloudcp/ratelimit_test.go b/internal/cloudcp/ratelimit_test.go
index fc5c0c4f53..6df2259340 100644
--- a/internal/cloudcp/ratelimit_test.go
+++ b/internal/cloudcp/ratelimit_test.go
@@ -73,6 +73,65 @@ func TestCPRateLimiterMiddleware_TooManyRequests(t *testing.T) {
if calls != 1 {
t.Fatalf("next handler calls after reject = %d, want 1", calls)
}
+ if rec2.Header().Get("Retry-After") == "" {
+ t.Fatal("expected Retry-After header")
+ }
+}
+
+func TestCPRateLimiterMiddlewareWithRejectedUsesCustomHandler(t *testing.T) {
+ rl := NewCPRateLimiter(1, time.Minute)
+ calls := 0
+ next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.WriteHeader(http.StatusNoContent)
+ })
+ h := rl.MiddlewareWithRejected(next, func(w http.ResponseWriter, r *http.Request, retryAfter int) {
+ if retryAfter < 1 {
+ t.Fatalf("retryAfter=%d, want positive", retryAfter)
+ }
+ http.Error(w, "custom blocked", http.StatusTooManyRequests)
+ })
+
+ req1 := httptest.NewRequest(http.MethodPost, "/start-pro-trial", nil)
+ req1.RemoteAddr = "198.51.100.7:1234"
+ rec1 := httptest.NewRecorder()
+ h.ServeHTTP(rec1, req1)
+ if rec1.Code != http.StatusNoContent {
+ t.Fatalf("first request status = %d, want %d", rec1.Code, http.StatusNoContent)
+ }
+
+ req2 := httptest.NewRequest(http.MethodPost, "/start-pro-trial", nil)
+ req2.RemoteAddr = "198.51.100.7:1234"
+ rec2 := httptest.NewRecorder()
+ h.ServeHTTP(rec2, req2)
+
+ if rec2.Code != http.StatusTooManyRequests {
+ t.Fatalf("second request status = %d, want %d", rec2.Code, http.StatusTooManyRequests)
+ }
+ if rec2.Body.String() != "custom blocked\n" {
+ t.Fatalf("blocked body=%q, want custom handler body", rec2.Body.String())
+ }
+ if calls != 1 {
+ t.Fatalf("next handler calls=%d, want 1", calls)
+ }
+ if rec2.Header().Get("Retry-After") == "" {
+ t.Fatal("expected Retry-After header")
+ }
+}
+
+func TestCPRateLimiterAllowAtReportsRemainingBackoff(t *testing.T) {
+ rl := NewCPRateLimiter(1, time.Minute)
+ ip := "198.51.100.44"
+ now := time.Unix(1710000000, 0).UTC()
+ rl.attempts[ip] = []time.Time{now.Add(-30 * time.Second)}
+
+ allowed, retryAfter := rl.allowAt(ip, now)
+ if allowed {
+ t.Fatal("expected request to be rejected")
+ }
+ if retryAfter < 29*time.Second || retryAfter > 31*time.Second {
+ t.Fatalf("retryAfter=%v, want about 30s", retryAfter)
+ }
}
func TestClientIP(t *testing.T) {
diff --git a/internal/cloudcp/routes.go b/internal/cloudcp/routes.go
index 2d8ff18c5c..d9c261c34c 100644
--- a/internal/cloudcp/routes.go
+++ b/internal/cloudcp/routes.go
@@ -118,10 +118,11 @@ 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)
- 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("/trial-signup/verify", trialSignupVerifyLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleVerifyEmail)))
- mux.Handle("/api/trial-signup/checkout", trialSignupCheckoutLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleCheckout)))
+ trialSignupRateLimited := trialSignupHandlers.HandleRateLimitedTrialSignup
+ mux.Handle("/start-pro-trial", trialSignupPageLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleStartProTrial), trialSignupRateLimited))
+ mux.Handle("/api/trial-signup/request-verification", trialSignupVerificationLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleRequestVerification), trialSignupRateLimited))
+ mux.Handle("/trial-signup/verify", trialSignupVerifyLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleVerifyEmail), trialSignupRateLimited))
+ mux.Handle("/api/trial-signup/checkout", trialSignupCheckoutLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleCheckout), trialSignupRateLimited))
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)))
diff --git a/internal/cloudcp/routes_test.go b/internal/cloudcp/routes_test.go
index 104165fa07..2f4619e75a 100644
--- a/internal/cloudcp/routes_test.go
+++ b/internal/cloudcp/routes_test.go
@@ -3,6 +3,7 @@ package cloudcp
import (
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"testing"
@@ -214,6 +215,74 @@ func TestRegisterRoutes_TrialSignupVerificationRateLimit(t *testing.T) {
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("rate-limited status=%d, want %d body=%q", rec.Code, http.StatusTooManyRequests, rec.Body.String())
}
+ if !strings.Contains(rec.Body.String(), "Too many trial setup attempts from this browser.") {
+ t.Fatalf("expected hosted rate-limit guidance, got %q", rec.Body.String())
+ }
+ if rec.Header().Get("Retry-After") == "" {
+ t.Fatal("expected Retry-After header")
+ }
+}
+
+func TestRegisterRoutes_TrialSignupCheckoutRateLimitRendersHostedPage(t *testing.T) {
+ dir := t.TempDir()
+ reg, err := registry.NewTenantRegistry(dir)
+ if err != nil {
+ t.Fatalf("NewTenantRegistry: %v", err)
+ }
+ t.Cleanup(func() { _ = reg.Close() })
+ trialStore, err := NewTrialSignupStore(dir)
+ if err != nil {
+ t.Fatalf("NewTrialSignupStore: %v", err)
+ }
+ t.Cleanup(func() { trialStore.Close() })
+
+ mux := http.NewServeMux()
+ RegisterRoutes(mux, &Deps{
+ Config: &CPConfig{
+ DataDir: dir,
+ AdminKey: "test-admin-key",
+ BaseURL: "https://cloud.example.com",
+ StripeWebhookSecret: "whsec_test",
+ },
+ Registry: reg,
+ TrialSignupStore: trialStore,
+ Version: "test",
+ })
+
+ form := url.Values{
+ "org_id": {"default"},
+ "return_url": {"https://pulse.example.com/auth/trial-activate"},
+ "instance_token": {"tsi_test"},
+ "name": {"Test User"},
+ "email": {"[email protected]"},
+ "company": {"Pulse Labs"},
+ }
+
+ for i := 0; i < 12; i++ {
+ req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.RemoteAddr = "198.51.100.35:7777"
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, req)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("attempt %d status=%d, want %d body=%q", i+1, rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.RemoteAddr = "198.51.100.35:7777"
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, req)
+ if rec.Code != http.StatusTooManyRequests {
+ t.Fatalf("rate-limited status=%d, want %d body=%q", rec.Code, http.StatusTooManyRequests, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "Too many trial setup attempts from this browser.") {
+ t.Fatalf("expected hosted rate-limit guidance, got %q", rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "[email protected]") {
+ t.Fatalf("expected submitted email to be preserved, got %q", rec.Body.String())
+ }
}
func TestRegisterRoutes_PublicCloudSignupRoutes(t *testing.T) {
diff --git a/internal/cloudcp/trial_signup_handlers.go b/internal/cloudcp/trial_signup_handlers.go
index 66402ddce8..f58c09b6cb 100644
--- a/internal/cloudcp/trial_signup_handlers.go
+++ b/internal/cloudcp/trial_signup_handlers.go
@@ -9,6 +9,7 @@ import (
"net/http"
"net/mail"
"net/url"
+ "strconv"
"strings"
"time"
@@ -1087,6 +1088,88 @@ func (h *TrialSignupHandlers) renderTrialSignupSuccessPage(w http.ResponseWriter
}
}
+func (h *TrialSignupHandlers) HandleRateLimitedTrialSignup(w http.ResponseWriter, r *http.Request, retryAfter int) {
+ data := h.trialSignupPageDataFromRequest(r)
+ data.ErrorMessage = trialSignupRateLimitMessage(retryAfter)
+ h.renderTrialSignupPage(w, r, http.StatusTooManyRequests, data)
+}
+
+func (h *TrialSignupHandlers) trialSignupPageDataFromRequest(r *http.Request) trialSignupPageData {
+ data := trialSignupPageData{
+ OrgID: trialSignupDefaultOrgID,
+ ReturnTarget: "your Pulse instance",
+ Cancelled: strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("cancelled")), "1"),
+ VerifiedToken: strings.TrimSpace(r.URL.Query().Get("verified")),
+ }
+
+ switch r.Method {
+ case http.MethodGet:
+ q := r.URL.Query()
+ data.OrgID = normalizeTrialOrgID(q.Get("org_id"))
+ data.ReturnURL = strings.TrimSpace(q.Get("return_url"))
+ data.InstanceToken = strings.TrimSpace(q.Get("instance_token"))
+ data.Name = strings.TrimSpace(q.Get("name"))
+ data.Email = strings.TrimSpace(q.Get("email"))
+ data.Company = strings.TrimSpace(q.Get("company"))
+ default:
+ if err := r.ParseForm(); err == nil {
+ data.OrgID = normalizeTrialOrgID(r.FormValue("org_id"))
+ data.ReturnURL = strings.TrimSpace(r.FormValue("return_url"))
+ data.InstanceToken = strings.TrimSpace(r.FormValue("instance_token"))
+ data.Name = strings.TrimSpace(r.FormValue("name"))
+ data.Email = strings.TrimSpace(r.FormValue("email"))
+ data.Company = strings.TrimSpace(r.FormValue("company"))
+ if verifiedToken := strings.TrimSpace(r.FormValue("verified_token")); verifiedToken != "" {
+ data.VerifiedToken = verifiedToken
+ }
+ }
+ }
+
+ if data.ReturnURL != "" {
+ data.ReturnTarget = summarizeTrialReturnTarget(data.ReturnURL)
+ }
+ if data.VerifiedToken == "" {
+ return data
+ }
+
+ record, err := h.lookupVerifiedTrialSignupRecord(data.VerifiedToken)
+ if err != nil || record == nil {
+ return data
+ }
+
+ data.OrgID = record.OrgID
+ data.ReturnURL = record.ReturnURL
+ data.InstanceToken = record.InstanceToken
+ data.ReturnTarget = summarizeTrialReturnTarget(record.ReturnURL)
+ data.Name = record.Name
+ data.Email = record.Email
+ data.Company = record.Company
+ data.Verified = true
+ return data
+}
+
+func trialSignupRateLimitMessage(retryAfter int) string {
+ return "Too many trial setup attempts from this browser. " + humanizeTrialSignupRetryAfter(retryAfter) + "."
+}
+
+func humanizeTrialSignupRetryAfter(retryAfter int) string {
+ if retryAfter <= 0 {
+ return "Try again later"
+ }
+ if retryAfter < 90 {
+ return "Try again in about a minute"
+ }
+ if retryAfter < 3600 {
+ minutes := int((time.Duration(retryAfter)*time.Second + time.Minute - 1) / time.Minute)
+ return "Try again in about " + strconv.Itoa(minutes) + " minutes"
+ }
+ hours := int((time.Duration(retryAfter)*time.Second + time.Hour - 1) / time.Hour)
+ if hours == 1 {
+ return "Try again in about 1 hour"
+ }
+ return "Try again in about " + strconv.Itoa(hours) + " hours"
+}
+
func (h *TrialSignupHandlers) lookupVerifiedTrialSignupRecord(verifiedToken string) (*TrialSignupRecord, error) {
if h.verificationStore == nil {
return nil, ErrTrialSignupRecordNotFound
diff --git a/internal/cloudcp/trial_signup_handlers_test.go b/internal/cloudcp/trial_signup_handlers_test.go
index 28b11d38a4..290d7396ba 100644
--- a/internal/cloudcp/trial_signup_handlers_test.go
+++ b/internal/cloudcp/trial_signup_handlers_test.go
@@ -40,6 +40,34 @@ func TestTrialSignupHandleStartProTrialRendersCheckoutForm(t *testing.T) {
}
}
+func TestTrialSignupHandleRateLimitedTrialSignupPreservesVerifiedCheckoutState(t *testing.T) {
+ h, _, sender := newTrialSignupTestHandler(t)
+ rawToken := requestTrialVerification(t, h, sender)
+ verifiedToken := verifyTrialRequest(t, h, rawToken)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(url.Values{
+ "verified_token": {verifiedToken},
+ }.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := httptest.NewRecorder()
+
+ h.HandleRateLimitedTrialSignup(rec, req, 120)
+
+ if rec.Code != http.StatusTooManyRequests {
+ t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusTooManyRequests, rec.Body.String())
+ }
+ body := rec.Body.String()
+ if !strings.Contains(body, "Too many trial setup attempts from this browser. Try again in about 2 minutes.") {
+ t.Fatalf("expected rate-limit guidance, got %q", body)
+ }
+ if !strings.Contains(body, "Backup link confirmed") {
+ t.Fatalf("expected verified state to be preserved, got %q", body)
+ }
+ if !strings.Contains(body, "[email protected]") {
+ t.Fatalf("expected verified email in response body")
+ }
+}
+
func TestTrialSignupHandleRequestVerificationSendsEmail(t *testing.T) {
h, _, sender := newTrialSignupTestHandler(t)
form := url.Values{