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.

Require stored principal for checkout magic links

rcourtman002d68cef745
diff --git a/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md
index 92bf591aa9..5cd556d311 100644
--- a/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md
+++ b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md
@@ -93,6 +93,10 @@ principal once a stable user ID exists.
returning the existing org for magic-link delivery.
4. Webhook payloads must never create organizations or memberships from email.
They may update billing only after server-owned org/customer linkage exists.
+ Post-checkout magic-link delivery from a webhook must also resolve the
+ Stripe contact email through current server-side org membership first;
+ matching contact metadata with a blank owner/member principal is not enough
+ to send a sign-in link.
5. Legacy email-keyed records may be accepted only at migration boundaries and
should be canonicalized to stable user IDs when the stable ID is known.
6. Self-hosted OIDC and SAML sessions bind to an opaque principal derived from
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index a4809b845f..6a613933a0 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -200,6 +200,11 @@ profile and assignment columns, but embedded table framing must route through
lifecycle-adjacent routes: shared auth must mint a browser session only for
a stored organization principal, not for a contact email on a blank
owner/member row.
+ Checkout webhook magic-link delivery follows that same shared-auth
+ dependency: lifecycle-adjacent consumers may observe billing activation
+ after server-owned org linkage, but they must not treat Stripe contact email
+ as fleet authority unless the API-owned organization resolver maps it to a
+ stored owner/member principal first.
API-token owner metadata follows the same rule: lifecycle-adjacent setup or
mobile-pairing token flows may consume the shared token helper, but they
must not pass extension metadata that authors or overwrites `owner_user_id`.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 1efb6d246e..af778378ea 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -406,6 +406,11 @@ the canonical monitored-system blocked payload.
Magic-link request and verify paths must fail closed when contact email
matches a blank owner/member principal instead of sending or accepting a
token that would turn email into the session identity.
+ Checkout webhook post-payment magic-link delivery follows the same
+ resolver-owned rule: Stripe `customer_email` can drive only best-effort
+ delivery after server-owned org linkage is validated, and it must not send
+ when the linked org row has matching contact metadata but no stored
+ owner/member principal.
Public hosted signup must therefore keep the generated owner user ID
server-side for org metadata and RBAC assignment while using returned
contact email only for `GenerateToken`/`SendMagicLink`; the accepted signup
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 8828bc1b09..fa287d0b1b 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -244,6 +244,11 @@ runtime gating as separate unlinked claims.
verification must re-read the tenant organization and session as the stored
stable owner/member principal, so an old token cannot keep email as the
runtime identity or survive removal from tenant membership.
+ Stripe checkout webhook magic-link delivery must use that same organization
+ resolver before sending the best-effort sign-in link; a webhook may activate
+ 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.
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
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index f50e99e58a..58af911eaa 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -82,6 +82,11 @@ Hosted public magic-link sessions follow the same dependent-auth contract:
storage/recovery-adjacent routes may consume the resulting browser session, but
shared auth must reject blank owner/member principals rather than minting an
email-keyed session from delivery metadata.
+Checkout webhook magic-link delivery is part of that same dependent-auth
+boundary: storage/recovery may observe billing activation for a server-linked
+org, but Stripe contact email must not become recovery or storage authority
+unless the shared API organization resolver maps it to a stored owner/member
+principal first.
The canonical actor vocabulary for those shared sessions is
`docs/release-control/v6/internal/IDENTITY_INVARIANTS.md`; recovery and storage
work may consume accepted org access, but must not mint or widen access from a
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index c21c00f19a..6bcd3efe8a 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -117,6 +117,42 @@ func TestContract_HostedMagicLinkStablePrincipalProof(t *testing.T) {
}
}
+func TestContract_CheckoutMagicLinkDeliveryRequiresStoredPrincipalProof(t *testing.T) {
+ source, err := os.ReadFile(filepath.Clean("payments_webhook_handlers.go"))
+ if err != nil {
+ t.Fatalf("read payments_webhook_handlers.go: %v", err)
+ }
+ text := string(source)
+ for _, required := range []string{
+ "ResolvePrincipalByEmail(email)",
+ "models.IsValidOrganizationRole(role)",
+ "GenerateToken(email, orgID)",
+ "SendMagicLink(email, orgID, token, baseURL)",
+ } {
+ if !strings.Contains(text, required) {
+ t.Fatalf("payments_webhook_handlers.go must contain %q", required)
+ }
+ }
+ for _, forbidden := range []string{
+ "strings.EqualFold(org.OwnerEmail, email)",
+ "strings.EqualFold(org.OwnerUserID, email)",
+ "strings.EqualFold(m.Email, email)",
+ "strings.EqualFold(m.UserID, email)",
+ } {
+ if strings.Contains(text, forbidden) {
+ t.Fatalf("payments_webhook_handlers.go must not contain legacy contact-email membership pattern %q", forbidden)
+ }
+ }
+
+ identityDoc, err := os.ReadFile(filepath.Clean("../../docs/release-control/v6/internal/IDENTITY_INVARIANTS.md"))
+ if err != nil {
+ t.Fatalf("read identity invariant contract: %v", err)
+ }
+ if !strings.Contains(string(identityDoc), "Post-checkout magic-link delivery") {
+ t.Fatal("identity invariant contract must cover checkout magic-link delivery")
+ }
+}
+
func TestContract_HostedHandoffRequiresStableSubjectProof(t *testing.T) {
directSource, err := os.ReadFile(filepath.Clean("cloud_handoff.go"))
if err != nil {
diff --git a/internal/api/payments_webhook_handlers.go b/internal/api/payments_webhook_handlers.go
index 919206ac08..4dfdc76401 100644
--- a/internal/api/payments_webhook_handlers.go
+++ b/internal/api/payments_webhook_handlers.go
@@ -17,6 +17,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rs/zerolog/log"
"github.com/stripe/stripe-go/v82"
"github.com/stripe/stripe-go/v82/webhook"
@@ -312,27 +313,17 @@ func (h *StripeWebhookHandlers) handleCheckoutSessionCompleted(ctx context.Conte
// (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.
- sendTo := ""
- if strings.EqualFold(org.OwnerEmail, email) || strings.EqualFold(org.OwnerUserID, email) {
- sendTo = email
- } else {
- for _, m := range org.Members {
- if strings.EqualFold(m.Email, email) || strings.EqualFold(m.UserID, email) {
- sendTo = email
- break
- }
- }
- }
- if sendTo != "" && h.magicLinks.AllowRequest(sendTo) {
- token, genErr := h.magicLinks.GenerateToken(sendTo, orgID)
+ 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 != "" {
- if sendErr := h.magicLinks.SendMagicLink(sendTo, orgID, token, baseURL); sendErr != nil {
- log.Warn().Err(sendErr).Str("email", sendTo).Str("org_id", orgID).Msg("Stripe checkout: failed to send magic link")
+ 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 b3630b1356..90f886fc90 100644
--- a/internal/api/stripe_webhook_handlers_test.go
+++ b/internal/api/stripe_webhook_handlers_test.go
@@ -523,6 +523,83 @@ func TestStripeWebhook_CheckoutCompleted_UsesContactEmailForStableOwnerIdentity(
}
}
+func TestStripeWebhook_CheckoutCompleted_DoesNotSendMagicLinkForBlankOrganizationPrincipal(t *testing.T) {
+ t.Setenv("STRIPE_WEBHOOK_SECRET", "whsec_test_blank_owner_contact")
+
+ tmp := t.TempDir()
+ persistence := config.NewMultiTenantPersistence(tmp)
+ rbacProvider := NewTenantRBACProvider(tmp)
+ billingStore := config.NewFileBillingStore(tmp)
+
+ emailer := &captureEmailer{}
+ magicLinks := NewMagicLinkServiceWithKey([]byte("01234567890123456789012345678901"), nil, emailer, nil)
+ t.Cleanup(magicLinks.Stop)
+
+ publicURL := func(_ *http.Request) string { return "https://pulse.example.test" }
+ h := NewStripeWebhookHandlers(billingStore, persistence, rbacProvider, magicLinks, publicURL, true, tmp)
+
+ orgID := "org_blank_owner_contact"
+ if _, err := persistence.GetPersistence(orgID); err != nil {
+ t.Fatalf("GetPersistence(%s): %v", orgID, err)
+ }
+ if err := persistence.SaveOrganization(&models.Organization{
+ ID: orgID,
+ DisplayName: "Blank Owner Contact",
+ CreatedAt: time.Now().UTC(),
+ OwnerEmail: "[email protected]",
+ }); err != nil {
+ t.Fatalf("SaveOrganization(%s): %v", orgID, err)
+ }
+
+ event := map[string]any{
+ "id": "evt_checkout_blank_owner_contact",
+ "type": "checkout.session.completed",
+ "data": map[string]any{
+ "object": map[string]any{
+ "id": "cs_blank_owner_contact",
+ "mode": "subscription",
+ "customer": "cus_blank_owner_contact",
+ "customer_email": "[email protected]",
+ "subscription": "sub_blank_owner_contact",
+ "metadata": map[string]any{
+ "org_id": orgID,
+ "org_name": "Blank Owner Contact",
+ "plan_version": "cloud-v1",
+ },
+ },
+ },
+ }
+ payload, err := json.Marshal(event)
+ if err != nil {
+ t.Fatalf("marshal event: %v", err)
+ }
+ signed := webhook.GenerateTestSignedPayload(&webhook.UnsignedPayload{
+ Payload: payload,
+ Secret: "whsec_test_blank_owner_contact",
+ Timestamp: time.Now(),
+ Scheme: "v1",
+ })
+
+ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/stripe", bytes.NewReader(payload))
+ req.Header.Set("Stripe-Signature", signed.Header)
+ rr := httptest.NewRecorder()
+ h.HandleStripeWebhook(rr, req)
+ if rr.Code != http.StatusOK {
+ t.Fatalf("status=%d, want %d: %s", rr.Code, http.StatusOK, rr.Body.String())
+ }
+ if emailer.Count() != 0 {
+ t.Fatalf("magic link send count=%d, want none for blank stored principal", emailer.Count())
+ }
+
+ state, err := billingStore.GetBillingState(orgID)
+ if err != nil {
+ t.Fatalf("GetBillingState: %v", err)
+ }
+ if state == nil || state.SubscriptionState != entitlements.SubStateActive {
+ t.Fatalf("billing state=%v, want active checkout billing despite skipped magic link", state)
+ }
+}
+
func TestStripeWebhook_DoesNotSendMagicLinkWithoutPublicURL(t *testing.T) {
t.Setenv("STRIPE_WEBHOOK_SECRET", "whsec_test_no_url")