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(api): validate hosted magic-link URL before token mint

rcourtmane391d631d16e
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 0a62ea72e6..720aece4b4 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -139,7 +139,7 @@
"test",
"./internal/api",
"-run",
- "TestHostedLifecycle|TestHostedSignupSuccess|TestHostedSignupValidationFailures|TestHostedSignupHostedModeGate|TestHostedSignupRateLimit|TestHostedSignupRateLimit_NoProvisioningSideEffects|TestHostedSignupCleanupOnRBACFailure|TestHostedSignupFailsClosedWithoutPublicURL",
+ "TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation|TestHostedLifecycle|TestHostedSignupSuccess|TestHostedSignupValidationFailures|TestHostedSignupHostedModeGate|TestHostedSignupRateLimit|TestHostedSignupRateLimit_NoProvisioningSideEffects|TestHostedSignupCleanupOnRBACFailure|TestHostedSignupFailsClosedWithoutPublicURL|TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation",
"-count=1"
]
},
@@ -176,6 +176,11 @@
"path": "frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/contract_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/api/hosted_lifecycle_integration_test.go",
@@ -186,6 +191,11 @@
"path": "internal/api/hosted_signup_handlers_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/stripe_webhook_handlers_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/hosted/provisioner_test.go",
@@ -957,7 +967,7 @@
"test",
"./internal/api",
"-run",
- "TestHostedLifecycle|TestHostedOrgAdminHandlers|TestHostedSignupSuccess|TestHostedSignupValidationFailures|TestHostedSignupHostedModeGate|TestHostedSignupRateLimit|TestHostedSignupRateLimit_NoProvisioningSideEffects|TestHostedSignupCleanupOnRBACFailure|TestHostedSignupFailsClosedWithoutPublicURL|TestStripeWebhook_",
+ "TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation|TestHostedLifecycle|TestHostedOrgAdminHandlers|TestHostedSignupSuccess|TestHostedSignupValidationFailures|TestHostedSignupHostedModeGate|TestHostedSignupRateLimit|TestHostedSignupRateLimit_NoProvisioningSideEffects|TestHostedSignupCleanupOnRBACFailure|TestHostedSignupFailsClosedWithoutPublicURL|TestStripeWebhook_",
"-count=1"
]
},
@@ -1050,6 +1060,11 @@
"path": "frontend-modern/src/components/Settings/__tests__/OrganizationBillingPanel.test.tsx",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/contract_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/api/hosted_lifecycle_integration_test.go",
@@ -1065,6 +1080,11 @@
"path": "internal/api/hosted_signup_handlers_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/stripe_webhook_handlers_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/cloudcp/stripe/cloud_lifecycle_integration_test.go",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index baa22f2555..d86ccccf59 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -5879,6 +5879,16 @@ adds missing, auto-detected-only, invalid, invalid-high-precedence,
persisted token-state checks. The self-hosted precedence and validated
live-origin fallback remain covered by that diagnostics proof and
`TestContract_RequestOriginCannotRetargetTokenBearingCommands`.
+The adjacent hosted returning-user and Stripe checkout magic-link callers now
+resolve the same canonical external URL before persisting their one-time token.
+Unavailable configuration leaves both in-memory and SQLite magic-link state
+empty; the public caller retains its enumeration-resistant generic response
+and the Stripe caller retains checkout/event idempotency. These credentials
+grant browser-session entry only after the existing stable organization-
+principal verification and do not become agent enrollment, setup, install,
+profile, update, or fleet authority. Proof lives in
+`TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation` and
+`TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation`.
### Runtime branding stays outside agent lifecycle authority
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index dd5b646077..6302588cf0 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -8961,6 +8961,23 @@ route, proves zero in-memory and persisted token mutation on every hosted
failure, and preserves both configured-URL precedence and the self-hosted
request-origin fallback.
+Hosted magic-link issuance follows the same mutation-order contract. The
+registered `/api/public/magic-link/request` handler must resolve the canonical
+hosted external URL before organization lookup or `GenerateToken`, return the
+same generic `200 OK` body for registered and unknown emails when that URL is
+unavailable, and leave both the in-memory and SQLite magic-link stores empty.
+Stripe `checkout.session.completed` processing must resolve that URL before
+best-effort token generation too; failure skips only sign-in delivery while
+billing projection, customer indexing, event completion, and duplicate replay
+remain successful and idempotent. Neither path may recover from missing,
+auto-detected-only, invalid, or invalid-higher-precedence hosted configuration
+through direct Host or trusted/untrusted forwarded headers. Configured
+`PublicURL` and higher-precedence `AgentConnectURL` remain the successful
+targets. `TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation`
+and `TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation` prove
+that boundary with exact in-memory/SQLite token counts and adjacent success,
+self-hosted, enumeration-resistance, and replay cases.
+
### Runtime branding is a narrow presentation contract
`GET /api/runtime/branding` is the authenticated `monitoring:read` boundary
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 12decc1901..c6eb10e377 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -726,6 +726,12 @@ the App/AppLayout, routing, and desktop Actions journey tests.
billing for a server-linked org, but it must not send a sign-in link merely
because Stripe `customer_email` matches contact metadata with no stored
principal.
+ The webhook must also resolve the canonical hosted external URL before it
+ generates or persists the one-time token. Missing, auto-detected-only,
+ invalid, or invalid-higher-precedence hosted URL configuration skips only
+ the optional sign-in delivery; checkout billing projection, customer-org
+ indexing, handled-event completion, and duplicate replay remain successful
+ and idempotent with no unreachable credential record left behind.
Tenant-targeted hosted magic-link handoff must fail closed when the
control-plane registry cannot resolve a stable account `User.ID`; it must
not sign a tenant handoff with a blank subject and let the tenant runtime
@@ -2827,6 +2833,17 @@ edge: syntactically valid signup requests return one uniform `202 Accepted`
Pulse Account message whether the backend provisioned/sent email or suppressed
side effects due to the owner-email rate limit, so the route does not reveal
prior email usage through `201` versus `429` drift.
+Returning-user magic-link requests now apply the same fail-closed delivery
+posture to hosted URL configuration. The registered public request handler
+resolves the canonical configured external URL before account lookup or token
+persistence; unavailable configuration returns the existing generic `200 OK`
+response for both registered and unknown emails and leaves in-memory and
+SQLite token state empty. Checkout completion uses that same resolver before
+its optional token generation, so a URL failure cannot turn a successfully
+handled Stripe event into an endlessly retried billing mutation or an
+unreachable stored credential. The adversarial proof is
+`TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation` plus
+`TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation`.
Hosted billing-state normalization now follows the same rule: a missing
`plan_version` must remain missing instead of being synthesized from
`subscription_state`, while explicit trial defaults remain explicit.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index f52df152b7..8654ee1a5e 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -5255,6 +5255,15 @@ slice; registered-route proof lives in
`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`,
while the existing settings architecture proof continues to own the Public
URL guidance.
+The same backend boundary now covers returning-user and Stripe post-checkout
+magic links before their one-time token is persisted. The public request UI
+contract remains unchanged: unavailable hosted URL configuration produces the
+same generic accepted response for registered and unknown email and exposes no
+configuration diagnostic or account-existence signal, while checkout simply
+skips its optional sign-in delivery. No frontend runtime file changes in this
+slice; the API proofs are
+`TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation` and
+`TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation`.
`frontend-modern/src/utils/discoveryPresentation.ts` now owns the
customer-facing discovery-section framing copy, scan-scope labels, subnet
guidance, command-execution settings targets, API Access handoff labels, and
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index 8d6d239857..ae52a35376 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -238,6 +238,14 @@ helper so handlers do not duplicate membership lookup or accidentally bind
sessions to email. A matching owner/member contact email without a stored
`OwnerUserID` or member `UserID` is not a principal; the helper must fail
closed instead of manufacturing a session key from email.
+Before that organization lookup can lead to one-time token persistence, the
+public hosted magic-link route must first resolve a valid canonical hosted
+external URL. Unavailable URL configuration therefore returns the same generic
+response for registered and unknown contact emails without touching either
+supported token store, while configured URL success still reaches this stable
+principal resolver. Stripe completion applies the same ordering before its
+best-effort organization-member delivery and must not let an optional URL
+failure disturb billing or event idempotency.
If one contact email matches multiple distinct stored principals, the model
must also fail closed instead of selecting a principal by owner/member row
order.
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index bfed968c4c..be46734682 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2258,6 +2258,14 @@ path. Router-level proof lives in
`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`,
while the self-hosted request-origin matrix remains in those diagnostics cases
and `TestContract_RequestOriginCannotRetargetTokenBearingCommands`.
+Hosted returning-user and Stripe checkout magic-link paths likewise perform one
+O(1) configured-URL resolution before account lookup or token persistence.
+Unavailable configuration adds no token-store write or cleanup scan: the public
+route returns its bounded generic response and the Stripe path completes its
+existing billing/index/deduper work while skipping only optional email
+delivery. In-memory and SQLite proof plus duplicate-event coverage lives in
+`TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation` and
+`TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation`.
### Runtime branding remains a bounded bootstrap read
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 9a4deb0242..c67e6b7398 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1877,6 +1877,19 @@ untrusted-forwarded request evidence; the install/setup proof also follows the
returned setup artifact through the public script route so the rendered
token-bearing shell body remains bound to the configured origin.
+The returning-user and post-checkout magic-link paths are credential-target
+consumers of that same resolver. They must resolve a valid authoritative hosted
+URL before `GenerateToken`, so missing, auto-detected-only, invalid, or invalid-
+higher-precedence configuration cannot leave an unreachable HMAC token record
+and cannot fall through to direct Host or trusted/untrusted forwarded headers.
+The public route preserves one generic `200 OK` response for registered and
+unknown email while leaving both supported stores empty; Stripe completion
+skips only best-effort delivery while preserving billing and event idempotency.
+Configured `PublicURL` and higher-precedence `AgentConnectURL` remain valid
+targets. Exact in-memory/SQLite state and adversarial header proof lives in
+`TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation` and
+`TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation`.
+
### The global security banner no longer scores a truncated status payload
`/api/security/status` in `internal/api/router_routes_auth_security.go` returns
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index ed0c185a60..e9a627d4c1 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -4964,6 +4964,14 @@ state unchanged and creates no recovery state. The router-level
`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`
proves that boundary for missing, auto-detected-only, invalid, precedence, and
configured success cases without widening storage or recovery authority.
+The shared public and Stripe-completion magic-link callers now resolve the same
+canonical hosted URL before one-time token persistence. Their unavailable-URL
+paths leave exact in-memory and SQLite token state empty; the Stripe caller
+still completes billing, customer indexing, event handling, and duplicate
+replay. Those changes create no recovery point, backup artifact, restore
+authority, storage identity, or recovery-local retry contract. Router/handler
+proof lives in `TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation`
+and `TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation`.
The shared `frontend-modern/src/App.tsx` shell boundary this subsystem consumes
gained one authority gate on its global banner block. The banners rendered
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 0f0fe49b1d..23a31475fd 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -22921,6 +22921,304 @@ func TestContract_RequestOriginCannotRetargetTokenBearingCommands(t *testing.T)
})
}
+func TestContract_HostedMagicLinkRequestValidatesOriginBeforeMutation(t *testing.T) {
+ type originHeaders struct {
+ host string
+ remoteAddr string
+ trustedProxyCIDR string
+ forwardedHost string
+ forwardedProto string
+ }
+ type storeFactory struct {
+ name string
+ new func(*testing.T) (MagicLinkStore, func(*testing.T) int)
+ }
+
+ storeFactories := []storeFactory{
+ {
+ name: "in-memory",
+ new: func(t *testing.T) (MagicLinkStore, func(*testing.T) int) {
+ t.Helper()
+ store := NewInMemoryMagicLinkStore()
+ return store, func(t *testing.T) int {
+ t.Helper()
+ store.mu.RLock()
+ defer store.mu.RUnlock()
+ return len(store.tokens)
+ }
+ },
+ },
+ {
+ name: "sqlite",
+ new: func(t *testing.T) (MagicLinkStore, func(*testing.T) int) {
+ t.Helper()
+ store, err := NewSQLiteMagicLinkStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewSQLiteMagicLinkStore: %v", err)
+ }
+ return store, func(t *testing.T) int {
+ t.Helper()
+ var count int
+ if err := store.db.QueryRow(`SELECT COUNT(*) FROM magic_link_tokens`).Scan(&count); err != nil {
+ t.Fatalf("count SQLite magic-link tokens: %v", err)
+ }
+ return count
+ }
+ },
+ },
+ }
+
+ newRouter := func(
+ t *testing.T,
+ hosted bool,
+ publicURL string,
+ autoDetected bool,
+ agentConnectURL string,
+ headers originHeaders,
+ factory storeFactory,
+ ) (*Router, *magicLinkCaptureEmailer, func(*testing.T) int) {
+ t.Helper()
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", headers.trustedProxyCIDR)
+ resetTrustedProxyCIDRsForTests()
+
+ dataPath := t.TempDir()
+ persistence := config.NewMultiTenantPersistence(dataPath)
+ now := time.Now().UTC()
+ if err := persistence.SaveOrganization(&models.Organization{
+ ID: "org_magic_origin",
+ DisplayName: "Magic Origin",
+ CreatedAt: now,
+ OwnerUserID: "u_magic_origin_owner",
+ OwnerEmail: "[email protected]",
+ Members: []models.OrganizationMember{{
+ UserID: "u_magic_origin_owner",
+ Email: "[email protected]",
+ Role: models.OrgRoleOwner,
+ AddedAt: now,
+ AddedBy: "u_magic_origin_owner",
+ }},
+ }); err != nil {
+ t.Fatalf("SaveOrganization: %v", err)
+ }
+
+ store, countTokens := factory.new(t)
+ emailer := &magicLinkCaptureEmailer{}
+ service := NewMagicLinkServiceWithKey(
+ []byte("0123456789abcdef0123456789abcdef"),
+ store,
+ emailer,
+ NewRateLimiter(100, time.Hour),
+ )
+ t.Cleanup(service.Stop)
+
+ router := &Router{
+ mux: http.NewServeMux(),
+ hostedMode: hosted,
+ multiTenant: persistence,
+ config: &config.Config{
+ DataPath: dataPath,
+ FrontendPort: 7655,
+ PublicURL: publicURL,
+ PublicURLAutoDetected: autoDetected,
+ AgentConnectURL: agentConnectURL,
+ },
+ }
+ handler := NewMagicLinkHandlers(persistence, service, hosted, router.resolvePublicURL)
+ router.registerHostedRoutes(nil, handler, nil)
+ t.Cleanup(func() {
+ if router.signupRateLimiter != nil {
+ router.signupRateLimiter.Stop()
+ }
+ if router.handoffExchangeRateLimiter != nil {
+ router.handoffExchangeRateLimiter.Stop()
+ }
+ })
+ return router, emailer, countTokens
+ }
+
+ doRequest := func(t *testing.T, router *Router, email string, headers originHeaders) *httptest.ResponseRecorder {
+ t.Helper()
+ body, err := json.Marshal(map[string]string{"email": email})
+ if err != nil {
+ t.Fatalf("marshal magic-link request: %v", err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/public/magic-link/request", bytes.NewReader(body))
+ req.Host = headers.host
+ req.RemoteAddr = headers.remoteAddr
+ if headers.forwardedHost != "" {
+ req.Header.Set("X-Forwarded-Host", headers.forwardedHost)
+ }
+ if headers.forwardedProto != "" {
+ req.Header.Set("X-Forwarded-Proto", headers.forwardedProto)
+ }
+ rec := httptest.NewRecorder()
+ router.mux.ServeHTTP(rec, req)
+ return rec
+ }
+
+ assertAccepted := func(t *testing.T, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ var response struct {
+ Success bool `json:"success"`
+ Message string `json:"message"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode magic-link response: %v", err)
+ }
+ if !response.Success || response.Message != magicLinkRequestAcceptedMessage {
+ t.Fatalf("response = %#v, want generic accepted shape", response)
+ }
+ if strings.Contains(rec.Body.String(), "configured") || strings.Contains(rec.Body.String(), "attacker") {
+ t.Fatalf("response disclosed URL configuration or request authority: %q", rec.Body.String())
+ }
+ }
+
+ failureCases := []struct {
+ name string
+ publicURL string
+ autoDetected bool
+ agentConnectURL string
+ headers originHeaders
+ }{
+ {
+ name: "missing configuration ignores hostile direct Host and untrusted forwarding",
+ headers: originHeaders{
+ host: "[email protected]/path",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "auto-detected URL is not hosted authority",
+ publicURL: "https://auto-detected.example",
+ autoDetected: true,
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "invalid PublicURL ignores trusted forwarding",
+ publicURL: "https://[email protected]",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "192.0.2.44:41000",
+ trustedProxyCIDR: "192.0.2.0/24",
+ forwardedHost: "trusted-forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "invalid higher-precedence AgentConnectURL does not fall through",
+ publicURL: "https://configured.example",
+ agentConnectURL: "https://[email protected]",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ }
+
+ for _, factory := range storeFactories {
+ factory := factory
+ t.Run(factory.name, func(t *testing.T) {
+ for _, tc := range failureCases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ router, emailer, countTokens := newRouter(t, true, tc.publicURL, tc.autoDetected, tc.agentConnectURL, tc.headers, factory)
+ registered := doRequest(t, router, "[email protected]", tc.headers)
+ unknown := doRequest(t, router, "[email protected]", tc.headers)
+ assertAccepted(t, registered)
+ assertAccepted(t, unknown)
+ if registered.Body.String() != unknown.Body.String() {
+ t.Fatalf("registered and unknown responses differ: registered=%q unknown=%q", registered.Body.String(), unknown.Body.String())
+ }
+ if got := countTokens(t); got != 0 {
+ t.Fatalf("stored magic-link token count = %d, want exactly 0", got)
+ }
+ if len(emailer.urls) != 0 || len(emailer.to) != 0 {
+ t.Fatalf("magic-link email side effects = to:%v urls:%v, want none", emailer.to, emailer.urls)
+ }
+ })
+ }
+ })
+ }
+
+ successCases := []struct {
+ name string
+ publicURL string
+ agentConnectURL string
+ wantBaseURL string
+ headers originHeaders
+ }{
+ {
+ name: "configured PublicURL defeats hostile direct Host and untrusted forwarding",
+ publicURL: "https://configured.example/base/",
+ wantBaseURL: "https://configured.example/base",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "http",
+ },
+ },
+ {
+ name: "configured AgentConnectURL outranks PublicURL and trusted forwarding",
+ publicURL: "https://configured.example",
+ agentConnectURL: "https://agents.configured.example/",
+ wantBaseURL: "https://agents.configured.example",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "192.0.2.44:41000",
+ trustedProxyCIDR: "192.0.2.0/24",
+ forwardedHost: "trusted-forwarded-attacker.example",
+ forwardedProto: "http",
+ },
+ },
+ }
+
+ for _, factory := range storeFactories {
+ factory := factory
+ for _, tc := range successCases {
+ tc := tc
+ t.Run(factory.name+" "+tc.name, func(t *testing.T) {
+ router, emailer, countTokens := newRouter(t, true, tc.publicURL, false, tc.agentConnectURL, tc.headers, factory)
+ rec := doRequest(t, router, "[email protected]", tc.headers)
+ assertAccepted(t, rec)
+ if got := countTokens(t); got != 1 {
+ t.Fatalf("stored magic-link token count = %d, want exactly 1", got)
+ }
+ if len(emailer.to) != 1 || !strings.EqualFold(emailer.to[0], "[email protected]") || len(emailer.urls) != 1 {
+ t.Fatalf("magic-link email = to:%v urls:%v, want one owner delivery", emailer.to, emailer.urls)
+ }
+ if !strings.HasPrefix(emailer.urls[0], tc.wantBaseURL+"/api/public/magic-link/verify?") || strings.Contains(emailer.urls[0], "attacker") {
+ t.Fatalf("magic-link URL was not bound to configured base %q: %q", tc.wantBaseURL, emailer.urls[0])
+ }
+ })
+ }
+ }
+
+ t.Run("self-hosted public route remains unavailable", func(t *testing.T) {
+ headers := originHeaders{host: "pulse.lan:7655", remoteAddr: "198.51.100.20:41000"}
+ router, emailer, countTokens := newRouter(t, false, "", false, "", headers, storeFactories[0])
+ rec := doRequest(t, router, "[email protected]", headers)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusNotFound, rec.Body.String())
+ }
+ if got := countTokens(t); got != 0 || len(emailer.urls) != 0 {
+ t.Fatalf("self-hosted magic-link side effects: tokens=%d urls=%v", got, emailer.urls)
+ }
+ })
+}
+
func TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation(t *testing.T) {
const existingToken = "hosted-diagnostics-existing.12345678"
diff --git a/internal/api/magic_link_handlers.go b/internal/api/magic_link_handlers.go
index 1a05447bf8..71fc19f049 100644
--- a/internal/api/magic_link_handlers.go
+++ b/internal/api/magic_link_handlers.go
@@ -14,6 +14,8 @@ import (
const magicLinkRequestBodyLimit = 16 * 1024
+const magicLinkRequestAcceptedMessage = "If that email is registered, you'll receive a magic link shortly."
+
type MagicLinkHandlers struct {
persistence *config.MultiTenantPersistence
service *MagicLinkService
@@ -74,52 +76,39 @@ func (h *MagicLinkHandlers) HandlePublicMagicLinkRequest(w http.ResponseWriter,
// Always return 200 to avoid leaking whether the email exists.
// Rate limiting is still enforced by silently not sending additional links.
if !h.service.AllowRequest(email) {
- writeJSON(w, http.StatusOK, map[string]interface{}{
- "success": true,
- "message": "If that email is registered, you'll receive a magic link shortly.",
- })
+ writeMagicLinkRequestAccepted(w)
+ return
+ }
+
+ baseURL := ""
+ if h.resolvePublicURL != nil {
+ baseURL = h.resolvePublicURL(r)
+ }
+ // Hosted mode must never fall back to request Host header (host header injection risk).
+ // Resolve the canonical external URL before looking up the account or minting a
+ // credential so unavailable configuration keeps the response uniform and leaves
+ // token storage untouched.
+ if baseURL == "" {
+ writeMagicLinkRequestAccepted(w)
return
}
orgID, ok, err := h.findOrgForEmail(email)
if err != nil {
log.Warn().Err(err).Str("email", email).Msg("Magic link request: failed to resolve org")
- writeJSON(w, http.StatusOK, map[string]interface{}{
- "success": true,
- "message": "If that email is registered, you'll receive a magic link shortly.",
- })
+ writeMagicLinkRequestAccepted(w)
return
}
if !ok {
// Unknown email: don't send mail, but still return 200.
- writeJSON(w, http.StatusOK, map[string]interface{}{
- "success": true,
- "message": "If that email is registered, you'll receive a magic link shortly.",
- })
+ writeMagicLinkRequestAccepted(w)
return
}
token, err := h.service.GenerateToken(email, orgID)
if err != nil {
log.Warn().Err(err).Str("email", email).Str("org_id", orgID).Msg("Magic link request: failed to generate token")
- writeJSON(w, http.StatusOK, map[string]interface{}{
- "success": true,
- "message": "If that email is registered, you'll receive a magic link shortly.",
- })
- return
- }
-
- baseURL := ""
- if h.resolvePublicURL != nil {
- baseURL = h.resolvePublicURL(r)
- }
- // Hosted mode must never fall back to request Host header (host header injection risk).
- // If public URL isn't configured, fail closed by not sending any email.
- if baseURL == "" {
- writeJSON(w, http.StatusOK, map[string]interface{}{
- "success": true,
- "message": "If that email is registered, you'll receive a magic link shortly.",
- })
+ writeMagicLinkRequestAccepted(w)
return
}
@@ -128,9 +117,13 @@ func (h *MagicLinkHandlers) HandlePublicMagicLinkRequest(w http.ResponseWriter,
// Still 200 to avoid revealing existence.
}
+ writeMagicLinkRequestAccepted(w)
+}
+
+func writeMagicLinkRequestAccepted(w http.ResponseWriter) {
writeJSON(w, http.StatusOK, map[string]interface{}{
"success": true,
- "message": "If that email is registered, you'll receive a magic link shortly.",
+ "message": magicLinkRequestAcceptedMessage,
})
}
diff --git a/internal/api/payments_webhook_handlers.go b/internal/api/payments_webhook_handlers.go
index 1e3f398842..570acca0b8 100644
--- a/internal/api/payments_webhook_handlers.go
+++ b/internal/api/payments_webhook_handlers.go
@@ -311,16 +311,19 @@ func (h *StripeWebhookHandlers) handleCheckoutSessionCompleted(ctx context.Conte
// Best-effort: issue a magic link so the user can sign in quickly after checkout.
// (In dev/staging this is log-only; production should swap in a real emailer.)
if h.magicLinks != nil && email != "" {
- // Only send a link to an existing org member/owner. Stripe customer email is user-controlled.
- userID, role, ok := org.ResolvePrincipalByEmail(email)
- if ok && strings.TrimSpace(userID) != "" && models.IsValidOrganizationRole(role) && h.magicLinks.AllowRequest(email) {
- token, genErr := h.magicLinks.GenerateToken(email, orgID)
- if genErr == nil {
- baseURL := ""
- if h.publicURL != nil && r != nil {
- baseURL = h.publicURL(r)
- }
- if baseURL != "" {
+ baseURL := ""
+ if h.publicURL != nil && r != nil {
+ baseURL = h.publicURL(r)
+ }
+ // URL resolution is best-effort, but it must precede token persistence.
+ // A completed checkout remains successful and idempotently handled when no
+ // canonical hosted URL is available; only the optional sign-in delivery is skipped.
+ if baseURL != "" {
+ // Only send a link to an existing org member/owner. Stripe customer email is user-controlled.
+ userID, role, ok := org.ResolvePrincipalByEmail(email)
+ if ok && strings.TrimSpace(userID) != "" && models.IsValidOrganizationRole(role) && h.magicLinks.AllowRequest(email) {
+ token, genErr := h.magicLinks.GenerateToken(email, orgID)
+ if genErr == nil {
if sendErr := h.magicLinks.SendMagicLink(email, orgID, token, baseURL); sendErr != nil {
log.Warn().Err(sendErr).Str("email", email).Str("org_id", orgID).Msg("Stripe checkout: failed to send magic link")
}
diff --git a/internal/api/stripe_webhook_handlers_test.go b/internal/api/stripe_webhook_handlers_test.go
index 305a47017e..d8706c01dc 100644
--- a/internal/api/stripe_webhook_handlers_test.go
+++ b/internal/api/stripe_webhook_handlers_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "strings"
"sync"
"testing"
"time"
@@ -661,6 +662,272 @@ func TestStripeWebhook_DoesNotSendMagicLinkWithoutPublicURL(t *testing.T) {
}
}
+func TestStripeWebhook_CheckoutMagicLinkValidatesOriginBeforeMutation(t *testing.T) {
+ type originHeaders struct {
+ host string
+ remoteAddr string
+ trustedProxyCIDR string
+ forwardedHost string
+ forwardedProto string
+ }
+ type storeFactory struct {
+ name string
+ new func(*testing.T) (MagicLinkStore, func(*testing.T) int)
+ }
+ type testCase struct {
+ name string
+ publicURL string
+ autoDetected bool
+ agentConnectURL string
+ wantBaseURL string
+ headers originHeaders
+ }
+
+ storeFactories := []storeFactory{
+ {
+ name: "in-memory",
+ new: func(t *testing.T) (MagicLinkStore, func(*testing.T) int) {
+ t.Helper()
+ store := NewInMemoryMagicLinkStore()
+ return store, func(t *testing.T) int {
+ t.Helper()
+ store.mu.RLock()
+ defer store.mu.RUnlock()
+ return len(store.tokens)
+ }
+ },
+ },
+ {
+ name: "sqlite",
+ new: func(t *testing.T) (MagicLinkStore, func(*testing.T) int) {
+ t.Helper()
+ store, err := NewSQLiteMagicLinkStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewSQLiteMagicLinkStore: %v", err)
+ }
+ return store, func(t *testing.T) int {
+ t.Helper()
+ var count int
+ if err := store.db.QueryRow(`SELECT COUNT(*) FROM magic_link_tokens`).Scan(&count); err != nil {
+ t.Fatalf("count SQLite magic-link tokens: %v", err)
+ }
+ return count
+ }
+ },
+ },
+ }
+
+ cases := []testCase{
+ {
+ name: "missing configuration ignores hostile direct Host and untrusted forwarding",
+ headers: originHeaders{
+ host: "[email protected]/path",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "auto-detected URL is not hosted authority",
+ publicURL: "https://auto-detected.example",
+ autoDetected: true,
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "invalid PublicURL ignores trusted forwarding",
+ publicURL: "https://[email protected]",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "192.0.2.44:41000",
+ trustedProxyCIDR: "192.0.2.0/24",
+ forwardedHost: "trusted-forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "invalid higher-precedence AgentConnectURL does not fall through",
+ publicURL: "https://configured.example",
+ agentConnectURL: "https://[email protected]",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "configured PublicURL defeats hostile direct Host and untrusted forwarding",
+ publicURL: "https://configured.example/base/",
+ wantBaseURL: "https://configured.example/base",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "http",
+ },
+ },
+ {
+ name: "configured AgentConnectURL outranks PublicURL and trusted forwarding",
+ publicURL: "https://configured.example",
+ agentConnectURL: "https://agents.configured.example/",
+ wantBaseURL: "https://agents.configured.example",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "192.0.2.44:41000",
+ trustedProxyCIDR: "192.0.2.0/24",
+ forwardedHost: "trusted-forwarded-attacker.example",
+ forwardedProto: "http",
+ },
+ },
+ }
+
+ for _, factory := range storeFactories {
+ factory := factory
+ for _, tc := range cases {
+ tc := tc
+ t.Run(factory.name+" "+tc.name, func(t *testing.T) {
+ t.Setenv("STRIPE_WEBHOOK_SECRET", "whsec_magic_link_origin_order")
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", tc.headers.trustedProxyCIDR)
+ resetTrustedProxyCIDRsForTests()
+
+ dataPath := t.TempDir()
+ persistence := config.NewMultiTenantPersistence(dataPath)
+ rbacProvider := NewTenantRBACProvider(dataPath)
+ t.Cleanup(func() { _ = rbacProvider.Close() })
+ billingStore := config.NewFileBillingStore(dataPath)
+ createTestOrg(t, persistence, "org_magic_checkout", "[email protected]")
+
+ store, countTokens := factory.new(t)
+ emailer := &captureEmailer{}
+ magicLinks := NewMagicLinkServiceWithKey(
+ []byte("0123456789abcdef0123456789abcdef"),
+ store,
+ emailer,
+ NewRateLimiter(100, time.Hour),
+ )
+ t.Cleanup(magicLinks.Stop)
+
+ urlRouter := &Router{
+ hostedMode: true,
+ config: &config.Config{
+ PublicURL: tc.publicURL,
+ PublicURLAutoDetected: tc.autoDetected,
+ AgentConnectURL: tc.agentConnectURL,
+ },
+ }
+ handler := NewStripeWebhookHandlers(
+ billingStore,
+ persistence,
+ rbacProvider,
+ magicLinks,
+ urlRouter.resolvePublicURL,
+ true,
+ dataPath,
+ )
+
+ event := map[string]any{
+ "id": "evt_checkout_magic_link_origin_order",
+ "type": "checkout.session.completed",
+ "data": map[string]any{
+ "object": map[string]any{
+ "id": "cs_magic_link_origin_order",
+ "mode": "subscription",
+ "customer": "cus_magic_link_origin_order",
+ "customer_email": "[email protected]",
+ "subscription": "sub_magic_link_origin_order",
+ "metadata": map[string]any{
+ "org_id": "org_magic_checkout",
+ "org_name": "Magic Checkout",
+ "plan_version": "cloud-v1",
+ },
+ },
+ },
+ }
+ payload, err := json.Marshal(event)
+ if err != nil {
+ t.Fatalf("marshal Stripe event: %v", err)
+ }
+ signed := webhook.GenerateTestSignedPayload(&webhook.UnsignedPayload{
+ Payload: payload,
+ Secret: "whsec_magic_link_origin_order",
+ Timestamp: time.Now(),
+ Scheme: "v1",
+ })
+
+ post := func(t *testing.T) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/stripe", bytes.NewReader(payload))
+ req.Host = tc.headers.host
+ req.RemoteAddr = tc.headers.remoteAddr
+ if tc.headers.forwardedHost != "" {
+ req.Header.Set("X-Forwarded-Host", tc.headers.forwardedHost)
+ }
+ if tc.headers.forwardedProto != "" {
+ req.Header.Set("X-Forwarded-Proto", tc.headers.forwardedProto)
+ }
+ req.Header.Set("Stripe-Signature", signed.Header)
+ rec := httptest.NewRecorder()
+ handler.HandleStripeWebhook(rec, req)
+ return rec
+ }
+
+ first := post(t)
+ if first.Code != http.StatusOK || !strings.Contains(first.Body.String(), `"status":"processed"`) {
+ t.Fatalf("first checkout status = %d body=%s, want processed 200", first.Code, first.Body.String())
+ }
+ wantTokens := 0
+ if tc.wantBaseURL != "" {
+ wantTokens = 1
+ }
+ if got := countTokens(t); got != wantTokens {
+ t.Fatalf("stored magic-link token count after processed event = %d, want exactly %d", got, wantTokens)
+ }
+
+ second := post(t)
+ if second.Code != http.StatusOK || !strings.Contains(second.Body.String(), `"status":"duplicate"`) {
+ t.Fatalf("duplicate checkout status = %d body=%s, want duplicate 200", second.Code, second.Body.String())
+ }
+ if got := countTokens(t); got != wantTokens {
+ t.Fatalf("stored magic-link token count after duplicate event = %d, want exactly %d", got, wantTokens)
+ }
+
+ state, err := billingStore.GetBillingState("org_magic_checkout")
+ if err != nil {
+ t.Fatalf("GetBillingState: %v", err)
+ }
+ if state == nil || state.SubscriptionState != entitlements.SubStateActive || state.StripeCustomerID != "cus_magic_link_origin_order" {
+ t.Fatalf("billing state = %#v, want active checkout projection", state)
+ }
+ mappedOrgID, ok, err := handler.index.LookupOrgID("cus_magic_link_origin_order")
+ if err != nil || !ok || mappedOrgID != "org_magic_checkout" {
+ t.Fatalf("customer index = org:%q ok:%t err:%v", mappedOrgID, ok, err)
+ }
+
+ if tc.wantBaseURL == "" {
+ if emailer.Count() != 0 {
+ t.Fatalf("magic-link sends = %d, want 0 when canonical URL is unavailable", emailer.Count())
+ }
+ return
+ }
+ if emailer.Count() != 1 {
+ t.Fatalf("magic-link sends = %d, want exactly 1 across duplicate delivery", emailer.Count())
+ }
+ emailer.mu.Lock()
+ magicLinkURL := emailer.calls[0].url
+ emailer.mu.Unlock()
+ if !strings.HasPrefix(magicLinkURL, tc.wantBaseURL+"/api/public/magic-link/verify?") || strings.Contains(magicLinkURL, "attacker") {
+ t.Fatalf("magic-link URL was not bound to configured base %q: %q", tc.wantBaseURL, magicLinkURL)
+ }
+ })
+ }
+ }
+}
+
func TestStripeWebhook_SubscriptionDeleted_RevokesCapabilities(t *testing.T) {
tests := []struct {
name string