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(cloudcp): allow portal sign-in for commercial users

Richard Courtman44f3e0b6e085
diff --git a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md
index d399531bb0..51431ad21e 100644
--- a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md
+++ b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md
@@ -82,6 +82,19 @@ One user may belong to multiple accounts. One account may own multiple hosted
workspaces and multiple self-hosted licenses. MSP is therefore an account kind
with stronger workspace-management needs, not a completely separate portal.
+Portal authentication must follow that same commercial identity model. `Pulse
+Account` sign-in cannot be limited to hosted-tenant members only; the portal
+magic-link path must accept both:
+
+1. hosted Cloud/MSP identities that already resolve through the control-plane
+ tenant/account registry
+2. self-hosted commercial identities that resolve through the shared
+ license/commercial account surface even when they have no hosted tenant
+
+When the portal explicitly requests a portal-target magic link, the resulting
+verification flow must create a control-plane session and return the user to
+`/portal` rather than forcing a tenant handoff redirect.
+
## Canonical Information Architecture
The future Pulse account surface should be one shell with product-aware areas,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 0bb24c5138..5c9db88038 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -227,6 +227,15 @@ portal source tree now also owns explicit runtime/bootstrap type definitions
plus a package-local `tsc --noEmit` gate, so future account-shell work should
extend the typed source boundary instead of reviving opaque global runtime
objects, document-wide render events, or untyped embedded asset edits.
+The public magic-link request and verification contract that feeds that shell
+is now explicit as well. Portal-target requests from
+`internal/cloudcp/portal/frontend/src/api.ts` must keep the opaque success
+posture for unknown emails, but they must resolve real login capability
+through both hosted account membership and the shared commercial identity
+lookup against the license/account surface. When the request target is
+`portal`, `internal/cloudcp/auth/handlers.go` must create a control-plane
+session and redirect back to `/portal` instead of forcing hosted tenant
+handoff semantics.
Hosted Pulse Cloud tenant-org AI reads now also follow that same canonical
rule: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`,
`internal/api/ai_handler.go`, and `internal/api/hosted_billing_state.go`
diff --git a/internal/cloudcp/auth/handlers.go b/internal/cloudcp/auth/handlers.go
index 7f307cbefc..9cff188942 100644
--- a/internal/cloudcp/auth/handlers.go
+++ b/internal/cloudcp/auth/handlers.go
@@ -18,6 +18,7 @@ import (
)
const handoffTTL = 60 * time.Second
+const portalRedirectPath = "/portal"
type adminGenerateMagicLinkRequest struct {
Email string `json:"email"`
@@ -71,6 +72,38 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDi
return
}
+ if token.Target == MagicLinkTargetPortal {
+ userID, err := ensureAccountUser(reg, token.Email)
+ if err != nil {
+ auditEvent(r, "cp_magic_link_verify", "failure").
+ Err(err).
+ Str("email", token.Email).
+ Str("target", token.Target).
+ Str("reason", "user_resolution_failed").
+ Msg("Magic link verification failed")
+ writeError(w, http.StatusInternalServerError, "session_error", "Unable to establish portal session")
+ return
+ }
+ if err := setSessionCookie(w, svc, reg, userID, token.Email); err != nil {
+ auditEvent(r, "cp_magic_link_verify", "failure").
+ Err(err).
+ Str("email", token.Email).
+ Str("target", token.Target).
+ Str("reason", "session_issue_failed").
+ Msg("Magic link verification failed")
+ writeError(w, http.StatusInternalServerError, "session_error", "Unable to establish portal session")
+ return
+ }
+
+ auditEvent(r, "cp_magic_link_verify", "success").
+ Str("email", token.Email).
+ Str("target", token.Target).
+ Msg("Magic link verified, redirecting to Pulse Account")
+
+ http.Redirect(w, r, portalRedirectPath, http.StatusTemporaryRedirect)
+ return
+ }
+
// Look up tenant to confirm it exists and is active.
tenant, err := reg.Get(token.TenantID)
if err != nil || tenant == nil {
@@ -119,34 +152,18 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDi
Str("tenant_id", tenant.ID).
Str("email", token.Email).
Msg("Failed to establish control-plane session identity")
- } else if sessionVersion, err := reg.GetUserSessionVersion(userID); err != nil {
- log.Warn().
- Err(err).
- Str("tenant_id", tenant.ID).
- Str("email", token.Email).
- Str("user_id", userID).
- Msg("Failed to read user session version")
- } else if sessionToken, err := svc.GenerateSessionTokenWithVersion(userID, token.Email, sessionVersion, SessionTTL); err != nil {
+ } else if err := setSessionCookie(w, svc, reg, userID, token.Email); err != nil {
log.Warn().
Err(err).
Str("tenant_id", tenant.ID).
Str("email", token.Email).
Msg("Failed to issue control-plane session")
- } else {
- http.SetCookie(w, &http.Cookie{
- Name: SessionCookieName,
- Value: sessionToken,
- Path: "/",
- HttpOnly: true,
- Secure: true,
- SameSite: http.SameSiteLaxMode,
- MaxAge: int(SessionTTL.Seconds()),
- })
}
auditEvent(r, "cp_magic_link_verify", "success").
Str("tenant_id", tenant.ID).
Str("email", token.Email).
+ Str("target", token.Target).
Msg("Magic link verified, redirecting to tenant handoff")
http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
@@ -328,16 +345,30 @@ func clearSessionCookie(w http.ResponseWriter) {
})
}
-func ensureAccountUserAndMembership(reg *registry.TenantRegistry, tenant *registry.Tenant, email string) (string, error) {
- if reg == nil {
- return "", fmt.Errorf("registry unavailable")
+func setSessionCookie(w http.ResponseWriter, svc *Service, reg *registry.TenantRegistry, userID, email string) error {
+ sessionVersion, err := reg.GetUserSessionVersion(userID)
+ if err != nil {
+ return fmt.Errorf("read user session version: %w", err)
}
- if tenant == nil {
- return "", fmt.Errorf("tenant is required")
+ sessionToken, err := svc.GenerateSessionTokenWithVersion(userID, email, sessionVersion, SessionTTL)
+ if err != nil {
+ return fmt.Errorf("issue session token: %w", err)
}
- accountID := strings.TrimSpace(tenant.AccountID)
- if accountID == "" {
- return "", fmt.Errorf("tenant has no account id")
+ http.SetCookie(w, &http.Cookie{
+ Name: SessionCookieName,
+ Value: sessionToken,
+ Path: "/",
+ HttpOnly: true,
+ Secure: true,
+ SameSite: http.SameSiteLaxMode,
+ MaxAge: int(SessionTTL.Seconds()),
+ })
+ return nil
+}
+
+func ensureAccountUser(reg *registry.TenantRegistry, email string) (string, error) {
+ if reg == nil {
+ return "", fmt.Errorf("registry unavailable")
}
email = strings.ToLower(strings.TrimSpace(email))
if email == "" {
@@ -371,24 +402,48 @@ func ensureAccountUserAndMembership(reg *registry.TenantRegistry, tenant *regist
return "", fmt.Errorf("user resolution failed")
}
- m, err := reg.GetMembership(accountID, user.ID)
+ _ = reg.UpdateUserLastLogin(user.ID)
+ return user.ID, nil
+}
+
+func ensureAccountUserAndMembership(reg *registry.TenantRegistry, tenant *registry.Tenant, email string) (string, error) {
+ if reg == nil {
+ return "", fmt.Errorf("registry unavailable")
+ }
+ if tenant == nil {
+ return "", fmt.Errorf("tenant is required")
+ }
+ accountID := strings.TrimSpace(tenant.AccountID)
+ if accountID == "" {
+ return "", fmt.Errorf("tenant has no account id")
+ }
+ email = strings.ToLower(strings.TrimSpace(email))
+ if email == "" {
+ return "", fmt.Errorf("email is required")
+ }
+
+ userID, err := ensureAccountUser(reg, email)
+ if err != nil {
+ return "", err
+ }
+
+ m, err := reg.GetMembership(accountID, userID)
if err != nil {
return "", fmt.Errorf("lookup membership: %w", err)
}
if m == nil {
newMembership := &registry.AccountMembership{
AccountID: accountID,
- UserID: user.ID,
+ UserID: userID,
Role: registry.MemberRoleOwner,
}
if createErr := reg.CreateMembership(newMembership); createErr != nil {
- reloaded, reloadErr := reg.GetMembership(accountID, user.ID)
+ reloaded, reloadErr := reg.GetMembership(accountID, userID)
if reloadErr != nil || reloaded == nil {
return "", fmt.Errorf("create membership: %w", createErr)
}
}
}
- _ = reg.UpdateUserLastLogin(user.ID)
- return user.ID, nil
+ return userID, nil
}
diff --git a/internal/cloudcp/auth/handlers_magiclink_test.go b/internal/cloudcp/auth/handlers_magiclink_test.go
new file mode 100644
index 0000000000..f08fb2d9a8
--- /dev/null
+++ b/internal/cloudcp/auth/handlers_magiclink_test.go
@@ -0,0 +1,145 @@
+package auth
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/cloudauth"
+)
+
+func TestHandleMagicLinkVerifyPortalTargetCreatesPortalSession(t *testing.T) {
+ dir := t.TempDir()
+ reg, err := registry.NewTenantRegistry(dir)
+ if err != nil {
+ t.Fatalf("NewTenantRegistry: %v", err)
+ }
+ t.Cleanup(func() { _ = reg.Close() })
+
+ svc, err := NewService(dir)
+ if err != nil {
+ t.Fatalf("NewService: %v", err)
+ }
+ t.Cleanup(svc.Close)
+
+ token, err := svc.GeneratePortalToken("[email protected]")
+ if err != nil {
+ t.Fatalf("GeneratePortalToken: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/auth/magic-link/verify?token="+token, nil)
+ rec := httptest.NewRecorder()
+
+ HandleMagicLinkVerify(svc, reg, filepath.Join(dir, "tenants"), "cloud.example.com")(rec, req)
+
+ if rec.Code != http.StatusTemporaryRedirect {
+ t.Fatalf("status=%d body=%q", rec.Code, rec.Body.String())
+ }
+ if got := rec.Header().Get("Location"); got != "/portal" {
+ t.Fatalf("location=%q, want %q", got, "/portal")
+ }
+ cookie := rec.Result().Cookies()
+ if len(cookie) == 0 || cookie[0].Name != SessionCookieName || strings.TrimSpace(cookie[0].Value) == "" {
+ t.Fatalf("expected %s session cookie, got %#v", SessionCookieName, cookie)
+ }
+
+ user, err := reg.GetUserByEmail("[email protected]")
+ if err != nil {
+ t.Fatalf("GetUserByEmail: %v", err)
+ }
+ if user == nil {
+ t.Fatal("expected portal user to be created")
+ }
+ accountIDs, err := reg.ListAccountsByUser(user.ID)
+ if err != nil {
+ t.Fatalf("ListAccountsByUser: %v", err)
+ }
+ if len(accountIDs) != 0 {
+ t.Fatalf("accountIDs=%v, want no memberships for portal-only login", accountIDs)
+ }
+}
+
+func TestHandleMagicLinkVerifyTenantTargetStillRedirectsToTenantHandoff(t *testing.T) {
+ dir := t.TempDir()
+ reg, err := registry.NewTenantRegistry(dir)
+ if err != nil {
+ t.Fatalf("NewTenantRegistry: %v", err)
+ }
+ t.Cleanup(func() { _ = reg.Close() })
+
+ accountID, err := registry.GenerateAccountID()
+ if err != nil {
+ t.Fatalf("GenerateAccountID: %v", err)
+ }
+ if err := reg.CreateAccount(&registry.Account{
+ ID: accountID,
+ Kind: registry.AccountKindIndividual,
+ DisplayName: "Hosted Account",
+ }); err != nil {
+ t.Fatalf("CreateAccount: %v", err)
+ }
+ if err := reg.Create(&registry.Tenant{
+ ID: "t-tenant-1",
+ AccountID: accountID,
+ Email: "[email protected]",
+ DisplayName: "Hosted Workspace",
+ State: registry.TenantStateActive,
+ }); err != nil {
+ t.Fatalf("Create tenant: %v", err)
+ }
+
+ tenantsDir := filepath.Join(dir, "tenants")
+ tenantDir := filepath.Join(tenantsDir, "t-tenant-1")
+ if err := os.MkdirAll(tenantDir, 0o700); err != nil {
+ t.Fatalf("MkdirAll tenant dir: %v", err)
+ }
+ handoffKey, err := cloudauth.GenerateHandoffKey()
+ if err != nil {
+ t.Fatalf("GenerateHandoffKey: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(tenantDir, cloudauth.HandoffKeyFile), handoffKey, 0o600); err != nil {
+ t.Fatalf("WriteFile handoff key: %v", err)
+ }
+
+ svc, err := NewService(dir)
+ if err != nil {
+ t.Fatalf("NewService: %v", err)
+ }
+ t.Cleanup(svc.Close)
+
+ token, err := svc.GenerateToken("[email protected]", "t-tenant-1")
+ if err != nil {
+ t.Fatalf("GenerateToken: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/auth/magic-link/verify?token="+token, nil)
+ rec := httptest.NewRecorder()
+
+ HandleMagicLinkVerify(svc, reg, tenantsDir, "cloud.example.com")(rec, req)
+
+ if rec.Code != http.StatusTemporaryRedirect {
+ t.Fatalf("status=%d body=%q", rec.Code, rec.Body.String())
+ }
+ location := rec.Header().Get("Location")
+ if !strings.HasPrefix(location, "https://t-tenant-1.cloud.example.com/auth/cloud-handoff?token=") {
+ t.Fatalf("location=%q, want tenant handoff redirect", location)
+ }
+ user, err := reg.GetUserByEmail("[email protected]")
+ if err != nil {
+ t.Fatalf("GetUserByEmail: %v", err)
+ }
+ if user == nil {
+ t.Fatal("expected tenant user to exist")
+ }
+ membership, err := reg.GetMembership(accountID, user.ID)
+ if err != nil {
+ t.Fatalf("GetMembership: %v", err)
+ }
+ if membership == nil {
+ t.Fatal("expected tenant owner membership to be created")
+ }
+}
diff --git a/internal/cloudcp/auth/magiclink.go b/internal/cloudcp/auth/magiclink.go
index ef2c24385e..089035cfa2 100644
--- a/internal/cloudcp/auth/magiclink.go
+++ b/internal/cloudcp/auth/magiclink.go
@@ -21,12 +21,16 @@ const (
magicLinkPrefix = "ml1_"
hmacKeyFile = ".cp_magic_link_key"
hmacKeySize = 32
+
+ MagicLinkTargetTenantHandoff = "tenant_handoff"
+ MagicLinkTargetPortal = "portal"
)
// Token holds the validated data from a consumed magic link token.
type Token struct {
Email string
TenantID string
+ Target string
ExpiresAt time.Time
}
@@ -67,13 +71,33 @@ func NewService(cpDataDir string) (*Service, error) {
// GenerateToken creates a new magic link token for the given email and tenant.
// Returns a string in the format "ml1_<random>" that can be included in a URL.
func (s *Service) GenerateToken(email, tenantID string) (string, error) {
+ return s.generateToken(email, tenantID, MagicLinkTargetTenantHandoff)
+}
+
+// GeneratePortalToken creates a new magic link token that signs the user into
+// the Pulse Account portal without requiring a tenant handoff target.
+func (s *Service) GeneratePortalToken(email string) (string, error) {
+ return s.generateToken(email, "", MagicLinkTargetPortal)
+}
+
+func (s *Service) generateToken(email, tenantID, target string) (string, error) {
if s == nil {
return "", fmt.Errorf("magic link service not configured")
}
email = strings.ToLower(strings.TrimSpace(email))
tenantID = strings.TrimSpace(tenantID)
- if email == "" || tenantID == "" {
- return "", fmt.Errorf("email and tenantID are required")
+ target = strings.TrimSpace(target)
+ if email == "" {
+ return "", fmt.Errorf("email is required")
+ }
+ if target == "" {
+ target = MagicLinkTargetTenantHandoff
+ }
+ if target == MagicLinkTargetTenantHandoff && tenantID == "" {
+ return "", fmt.Errorf("tenantID is required")
+ }
+ if target != MagicLinkTargetTenantHandoff && target != MagicLinkTargetPortal {
+ return "", fmt.Errorf("target is invalid")
}
expiresAt := s.now().UTC().Add(s.ttl)
@@ -88,6 +112,7 @@ func (s *Service) GenerateToken(email, tenantID string) (string, error) {
if err := s.store.Put(tokenHash, &TokenRecord{
Email: email,
TenantID: tenantID,
+ Target: target,
ExpiresAt: expiresAt,
}); err != nil {
return "", err
@@ -115,6 +140,7 @@ func (s *Service) ValidateToken(token string) (*Token, error) {
return &Token{
Email: rec.Email,
TenantID: rec.TenantID,
+ Target: rec.Target,
ExpiresAt: rec.ExpiresAt,
}, nil
}
diff --git a/internal/cloudcp/auth/magiclink_store.go b/internal/cloudcp/auth/magiclink_store.go
index 1a20cb0605..22608cbf53 100644
--- a/internal/cloudcp/auth/magiclink_store.go
+++ b/internal/cloudcp/auth/magiclink_store.go
@@ -36,6 +36,7 @@ func ensureOwnerOnlyDir(dir string) error {
type TokenRecord struct {
Email string
TenantID string
+ Target string
ExpiresAt time.Time
Used bool
}
@@ -96,6 +97,7 @@ func (s *Store) initSchema() error {
token_hash TEXT PRIMARY KEY,
email TEXT NOT NULL,
tenant_id TEXT NOT NULL,
+ target TEXT NOT NULL DEFAULT '` + MagicLinkTargetTenantHandoff + `',
expires_at INTEGER NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
@@ -107,9 +109,43 @@ func (s *Store) initSchema() error {
if _, err := s.db.Exec(schema); err != nil {
return fmt.Errorf("init magic link schema: %w", err)
}
+ if err := ensureMagicLinkTargetColumn(s.db); err != nil {
+ return fmt.Errorf("ensure magic link target column: %w", err)
+ }
return nil
}
+func ensureMagicLinkTargetColumn(db *sql.DB) error {
+ rows, err := db.Query(`PRAGMA table_info(magic_link_tokens)`)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var (
+ cid int
+ name string
+ columnType string
+ notNull int
+ defaultVal sql.NullString
+ primaryKey int
+ )
+ if err := rows.Scan(&cid, &name, &columnType, &notNull, &defaultVal, &primaryKey); err != nil {
+ return err
+ }
+ if name == "target" {
+ return nil
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return err
+ }
+
+ _, err = db.Exec(`ALTER TABLE magic_link_tokens ADD COLUMN target TEXT NOT NULL DEFAULT '` + MagicLinkTargetTenantHandoff + `'`)
+ return err
+}
+
func (s *Store) cleanupLoop() {
ticker := time.NewTicker(storeCleanupInterval)
defer ticker.Stop()
@@ -133,9 +169,19 @@ func (s *Store) Put(tokenHash []byte, rec *TokenRecord) error {
if len(tokenHash) == 0 {
return fmt.Errorf("tokenHash is required")
}
- if rec == nil || rec.Email == "" || rec.TenantID == "" || rec.ExpiresAt.IsZero() {
+ if rec == nil || rec.Email == "" || rec.ExpiresAt.IsZero() {
return fmt.Errorf("token record is required")
}
+ target := strings.TrimSpace(rec.Target)
+ if target == "" {
+ target = MagicLinkTargetTenantHandoff
+ }
+ if target == MagicLinkTargetTenantHandoff && strings.TrimSpace(rec.TenantID) == "" {
+ return fmt.Errorf("tenant-target tokens require tenantID")
+ }
+ if target != MagicLinkTargetTenantHandoff && target != MagicLinkTargetPortal {
+ return fmt.Errorf("target is invalid")
+ }
key := hex.EncodeToString(tokenHash)
now := time.Now().UTC().Unix()
@@ -148,9 +194,9 @@ func (s *Store) Put(tokenHash []byte, rec *TokenRecord) error {
}
defer s.mu.Unlock()
_, err := db.Exec(
- `INSERT OR REPLACE INTO magic_link_tokens (token_hash, email, tenant_id, expires_at, used, created_at, used_at)
- VALUES (?, ?, ?, ?, 0, ?, NULL)`,
- key, rec.Email, rec.TenantID, rec.ExpiresAt.UTC().Unix(), now,
+ `INSERT OR REPLACE INTO magic_link_tokens (token_hash, email, tenant_id, target, expires_at, used, created_at, used_at)
+ VALUES (?, ?, ?, ?, ?, 0, ?, NULL)`,
+ key, rec.Email, rec.TenantID, target, rec.ExpiresAt.UTC().Unix(), now,
)
if err != nil {
return fmt.Errorf("put magic link token: %w", err)
@@ -188,12 +234,12 @@ func (s *Store) Consume(tokenHash []byte, now time.Time) (*TokenRecord, error) {
}
}()
- var email, tenantID string
+ var email, tenantID, target string
var expiresAtUnix int64
var usedInt int
- row := tx.QueryRow(`SELECT email, tenant_id, expires_at, used FROM magic_link_tokens WHERE token_hash = ?`, key)
- if scanErr := row.Scan(&email, &tenantID, &expiresAtUnix, &usedInt); scanErr != nil {
+ row := tx.QueryRow(`SELECT email, tenant_id, target, expires_at, used FROM magic_link_tokens WHERE token_hash = ?`, key)
+ if scanErr := row.Scan(&email, &tenantID, &target, &expiresAtUnix, &usedInt); scanErr != nil {
if errors.Is(scanErr, sql.ErrNoRows) {
return nil, ErrTokenInvalid
}
@@ -227,6 +273,7 @@ func (s *Store) Consume(tokenHash []byte, now time.Time) (*TokenRecord, error) {
return &TokenRecord{
Email: email,
TenantID: tenantID,
+ Target: target,
ExpiresAt: expiresAt,
Used: true,
}, nil
diff --git a/internal/cloudcp/auth/magiclink_store_queryplan_test.go b/internal/cloudcp/auth/magiclink_store_queryplan_test.go
index 627a61b85a..cd1bf0dc2c 100644
--- a/internal/cloudcp/auth/magiclink_store_queryplan_test.go
+++ b/internal/cloudcp/auth/magiclink_store_queryplan_test.go
@@ -22,7 +22,7 @@ func TestMagicLinkStoreQueryPlansUseIndexes(t *testing.T) {
}{
{
name: "consume lookup uses token primary key",
- query: `SELECT email, tenant_id, expires_at, used FROM magic_link_tokens WHERE token_hash = ?`,
+ query: `SELECT email, tenant_id, target, expires_at, used FROM magic_link_tokens WHERE token_hash = ?`,
args: []any{hex.EncodeToString(tokenHash)},
wantIndex: "sqlite_autoindex_magic_link_tokens_1",
},
@@ -70,6 +70,7 @@ func newMagicLinkPlanTestStore(t *testing.T) (*Store, []byte, time.Time) {
rec := &TokenRecord{
Email: fmt.Sprintf("user%[email protected]", i),
TenantID: fmt.Sprintf("tenant-%02d", i%12),
+ Target: MagicLinkTargetTenantHandoff,
ExpiresAt: base.Add(time.Duration(i-64) * time.Minute),
}
if err := store.Put(tokenHash, rec); err != nil {
diff --git a/internal/cloudcp/auth/magiclink_test.go b/internal/cloudcp/auth/magiclink_test.go
index 7661f5a111..2b4e5f788a 100644
--- a/internal/cloudcp/auth/magiclink_test.go
+++ b/internal/cloudcp/auth/magiclink_test.go
@@ -67,6 +67,37 @@ func TestValidateToken_Valid(t *testing.T) {
if result.TenantID != "t-xyz" {
t.Errorf("tenantID = %q, want t-xyz", result.TenantID)
}
+ if result.Target != MagicLinkTargetTenantHandoff {
+ t.Errorf("target = %q, want %q", result.Target, MagicLinkTargetTenantHandoff)
+ }
+}
+
+func TestGeneratePortalToken_Valid(t *testing.T) {
+ dir := t.TempDir()
+ svc, err := NewService(dir)
+ if err != nil {
+ t.Fatalf("NewService: %v", err)
+ }
+ defer svc.Close()
+
+ token, err := svc.GeneratePortalToken("[email protected]")
+ if err != nil {
+ t.Fatalf("GeneratePortalToken: %v", err)
+ }
+
+ result, err := svc.ValidateToken(token)
+ if err != nil {
+ t.Fatalf("ValidateToken: %v", err)
+ }
+ if result.Email != "[email protected]" {
+ t.Errorf("email = %q, want [email protected]", result.Email)
+ }
+ if result.TenantID != "" {
+ t.Errorf("tenantID = %q, want empty", result.TenantID)
+ }
+ if result.Target != MagicLinkTargetPortal {
+ t.Errorf("target = %q, want %q", result.Target, MagicLinkTargetPortal)
+ }
}
func TestValidateToken_AlreadyUsed(t *testing.T) {
diff --git a/internal/cloudcp/commercial_identity.go b/internal/cloudcp/commercial_identity.go
new file mode 100644
index 0000000000..9f4c2aae4c
--- /dev/null
+++ b/internal/cloudcp/commercial_identity.go
@@ -0,0 +1,87 @@
+package cloudcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+const defaultLicenseServerURL = "https://license.pulserelay.pro"
+
+type CommercialIdentityLookupResult struct {
+ Email string `json:"email"`
+ HasCommercialIdentity bool `json:"has_commercial_identity"`
+ Sources []string `json:"sources,omitempty"`
+ V5LicenseCount int `json:"v5_license_count"`
+ V6LicenseCount int `json:"v6_license_count"`
+ StripeCustomerID string `json:"stripe_customer_id,omitempty"`
+}
+
+type commercialIdentityLookup interface {
+ LookupCommercialIdentity(ctx context.Context, email string) (*CommercialIdentityLookupResult, error)
+}
+
+type commercialIdentityClient struct {
+ baseURL string
+ adminToken string
+ httpClient *http.Client
+}
+
+func newCommercialIdentityClient(cfg *CPConfig) commercialIdentityLookup {
+ if cfg == nil {
+ return nil
+ }
+ adminToken := strings.TrimSpace(cfg.LicenseAdminToken)
+ if adminToken == "" {
+ return nil
+ }
+ baseURL := strings.TrimRight(strings.TrimSpace(cfg.LicenseServerURL), "/")
+ if baseURL == "" {
+ baseURL = defaultLicenseServerURL
+ }
+ return &commercialIdentityClient{
+ baseURL: baseURL,
+ adminToken: adminToken,
+ httpClient: &http.Client{Timeout: 10 * time.Second},
+ }
+}
+
+func (c *commercialIdentityClient) LookupCommercialIdentity(ctx context.Context, email string) (*CommercialIdentityLookupResult, error) {
+ if c == nil {
+ return nil, nil
+ }
+ email = strings.TrimSpace(email)
+ if email == "" {
+ return nil, fmt.Errorf("email is required")
+ }
+
+ endpoint := c.baseURL + "/v1/admin/commercial/lookup?email=" + url.QueryEscape(email)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return nil, fmt.Errorf("create commercial identity request: %w", err)
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("X-API-Token", c.adminToken)
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("commercial identity request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
+ return nil, fmt.Errorf("commercial identity lookup returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ var result CommercialIdentityLookupResult
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil {
+ return nil, fmt.Errorf("decode commercial identity response: %w", err)
+ }
+ return &result, nil
+}
diff --git a/internal/cloudcp/config.go b/internal/cloudcp/config.go
index a387aa4405..7f41d42fa9 100644
--- a/internal/cloudcp/config.go
+++ b/internal/cloudcp/config.go
@@ -41,6 +41,8 @@ type CPConfig struct {
RequireEmailProvider bool
ResendAPIKey string // Resend API key (optional — if empty, emails are logged)
EmailFrom string // Sender email address (e.g. "[email protected]")
+ LicenseServerURL string
+ LicenseAdminToken string
}
// TenantsDir returns the directory where per-tenant data is stored.
@@ -125,6 +127,8 @@ func LoadConfig() (*CPConfig, error) {
RequireEmailProvider: envOrDefaultBool("CP_REQUIRE_EMAIL_PROVIDER", true),
ResendAPIKey: strings.TrimSpace(os.Getenv("RESEND_API_KEY")),
EmailFrom: envOrDefault("PULSE_EMAIL_FROM", "[email protected]"),
+ LicenseServerURL: strings.TrimSpace(envOrDefault("PULSE_LICENSE_SERVER_URL", defaultLicenseServerURL)),
+ LicenseAdminToken: strings.TrimSpace(os.Getenv("PULSE_LICENSE_ADMIN_TOKEN")),
}
if err := cfg.validate(); err != nil {
@@ -219,6 +223,18 @@ func (c *CPConfig) validate() error {
if parsedBaseURL.Host == "" {
return fmt.Errorf("CP_BASE_URL must include a host")
}
+ if c.LicenseServerURL != "" {
+ parsedLicenseURL, err := url.Parse(c.LicenseServerURL)
+ if err != nil {
+ return fmt.Errorf("PULSE_LICENSE_SERVER_URL must be a valid URL: %w", err)
+ }
+ if parsedLicenseURL.Scheme != "http" && parsedLicenseURL.Scheme != "https" {
+ return fmt.Errorf("PULSE_LICENSE_SERVER_URL must use http or https scheme")
+ }
+ if parsedLicenseURL.Host == "" {
+ return fmt.Errorf("PULSE_LICENSE_SERVER_URL must include a host")
+ }
+ }
return nil
}
diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.json
index cb2fe3eea2..8ea01b3b52 100644
--- a/internal/cloudcp/portal/dist/build_manifest.json
+++ b/internal/cloudcp/portal/dist/build_manifest.json
@@ -1,5 +1,5 @@
{
- "source_hash": "a41c0f493009a2110dc67108737842f8e0941d20366700fd5f0398e690a71b5b",
+ "source_hash": "6c3fac3d004ef32e5bee17d4f8f80a569a64e0ee8582c417d79c7c537cce8d6d",
"build_inputs": [
"package.json",
"tsconfig.json",
diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.js
index f3619f9881..6a9c5f917d 100644
--- a/internal/cloudcp/portal/dist/portal_app.js
+++ b/internal/cloudcp/portal/dist/portal_app.js
@@ -284,7 +284,7 @@
return request(bootstrap().magic_link_request_path, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ email })
+ body: JSON.stringify({ email, target: "portal" })
}, "Failed to send magic link.");
},
logout: function() {
diff --git a/internal/cloudcp/portal/frontend/src/api.ts b/internal/cloudcp/portal/frontend/src/api.ts
index f18bc1cd18..f83d98a921 100644
--- a/internal/cloudcp/portal/frontend/src/api.ts
+++ b/internal/cloudcp/portal/frontend/src/api.ts
@@ -133,7 +133,7 @@ export function createPortalAPI(context: PortalAPIContext): PortalAPI {
return request<PortalMagicLinkResponse>(bootstrap().magic_link_request_path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ email: email }),
+ body: JSON.stringify({ email: email, target: 'portal' }),
}, 'Failed to send magic link.');
},
logout: function() {
diff --git a/internal/cloudcp/portal/frontend/src/app.test.ts b/internal/cloudcp/portal/frontend/src/app.test.ts
index 58a349007d..ef5a723f51 100644
--- a/internal/cloudcp/portal/frontend/src/app.test.ts
+++ b/internal/cloudcp/portal/frontend/src/app.test.ts
@@ -209,7 +209,7 @@ describe('portal app', function() {
'/api/public/magic-link/request',
expect.objectContaining({
method: 'POST',
- body: JSON.stringify({ email: '[email protected]' }),
+ body: JSON.stringify({ email: '[email protected]', target: 'portal' }),
})
);
expect(document.getElementById('portal-app-root')?.textContent).toContain("If that email is registered, you'll receive a magic link shortly.");
diff --git a/internal/cloudcp/public_cloud_signup_handlers.go b/internal/cloudcp/public_cloud_signup_handlers.go
index 875aa9b328..e3b60ef790 100644
--- a/internal/cloudcp/public_cloud_signup_handlers.go
+++ b/internal/cloudcp/public_cloud_signup_handlers.go
@@ -154,7 +154,9 @@ type PublicCloudSignupHandlers struct {
registry *registry.TenantRegistry
magicLinks interface {
GenerateToken(email, tenantID string) (string, error)
+ GeneratePortalToken(email string) (string, error)
}
+ commercialIdentities commercialIdentityLookup
emailSender cpemail.Sender
createCheckoutSession func(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error)
}
@@ -182,16 +184,26 @@ type publicCloudSignupRequest struct {
}
type publicMagicLinkRequest struct {
- Email string `json:"email"`
+ Email string `json:"email"`
+ Target string `json:"target,omitempty"`
}
+type publicMagicLinkTarget string
+
+const (
+ publicMagicLinkTargetDefault publicMagicLinkTarget = ""
+ publicMagicLinkTargetPortal publicMagicLinkTarget = "portal"
+)
+
func NewPublicCloudSignupHandlers(cfg *CPConfig, reg *registry.TenantRegistry, magicLinks interface {
GenerateToken(email, tenantID string) (string, error)
+ GeneratePortalToken(email string) (string, error)
}, emailSender cpemail.Sender) *PublicCloudSignupHandlers {
return &PublicCloudSignupHandlers{
cfg: cfg,
registry: reg,
magicLinks: magicLinks,
+ commercialIdentities: newCommercialIdentityClient(cfg),
emailSender: emailSender,
createCheckoutSession: stripesession.New,
}
@@ -389,9 +401,10 @@ func (h *PublicCloudSignupHandlers) HandlePublicMagicLinkRequest(w http.Response
writePublicSignupError(w, http.StatusBadRequest, "invalid_email", "Invalid email format")
return
}
+ target := parsePublicMagicLinkTarget(req.Target)
const msg = "If that email is registered, you'll receive a magic link shortly."
- if h.registry == nil || h.magicLinks == nil {
+ if h.magicLinks == nil {
writePublicSignupJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": msg,
@@ -399,26 +412,16 @@ func (h *PublicCloudSignupHandlers) HandlePublicMagicLinkRequest(w http.Response
return
}
- tenantID, ok, err := h.findTenantForEmail(email)
+ token, issued, tenantID, err := h.issueMagicLinkToken(r.Context(), email, target)
if err != nil {
- log.Warn().Err(err).Str("email", email).Msg("public magic link request: tenant lookup failed")
- writePublicSignupJSON(w, http.StatusOK, map[string]any{
- "success": true,
- "message": msg,
- })
- return
- }
- if !ok {
+ log.Warn().Err(err).Str("email", email).Str("target", string(target)).Msg("public magic link request: token generation failed")
writePublicSignupJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": msg,
})
return
}
-
- token, err := h.magicLinks.GenerateToken(email, tenantID)
- if err != nil {
- log.Warn().Err(err).Str("email", email).Str("tenant_id", tenantID).Msg("public magic link request: token generation failed")
+ if !issued {
writePublicSignupJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": msg,
@@ -442,6 +445,48 @@ func (h *PublicCloudSignupHandlers) HandlePublicMagicLinkRequest(w http.Response
})
}
+func parsePublicMagicLinkTarget(raw string) publicMagicLinkTarget {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case string(publicMagicLinkTargetPortal):
+ return publicMagicLinkTargetPortal
+ default:
+ return publicMagicLinkTargetDefault
+ }
+}
+
+func (h *PublicCloudSignupHandlers) issueMagicLinkToken(ctx context.Context, email string, target publicMagicLinkTarget) (token string, issued bool, tenantID string, err error) {
+ tenantID, hasTenant, err := h.findTenantForEmail(email)
+ if err != nil {
+ return "", false, "", err
+ }
+
+ switch target {
+ case publicMagicLinkTargetPortal:
+ if hasTenant {
+ token, err := h.magicLinks.GeneratePortalToken(email)
+ return token, err == nil, tenantID, err
+ }
+ if h.commercialIdentities == nil {
+ return "", false, "", nil
+ }
+ identity, err := h.commercialIdentities.LookupCommercialIdentity(ctx, email)
+ if err != nil {
+ return "", false, "", err
+ }
+ if identity == nil || !identity.HasCommercialIdentity {
+ return "", false, "", nil
+ }
+ token, err := h.magicLinks.GeneratePortalToken(email)
+ return token, err == nil, "", err
+ default:
+ if !hasTenant {
+ return "", false, "", nil
+ }
+ token, err := h.magicLinks.GenerateToken(email, tenantID)
+ return token, err == nil, tenantID, err
+ }
+}
+
func (h *PublicCloudSignupHandlers) createCheckout(email, orgName string, tier cloudTier) (string, error) {
if h.cfg == nil {
return "", fmt.Errorf("control plane config is missing")
@@ -515,6 +560,9 @@ func (h *PublicCloudSignupHandlers) renderSignupPage(w http.ResponseWriter, r *h
}
func (h *PublicCloudSignupHandlers) findTenantForEmail(email string) (string, bool, error) {
+ if h.registry == nil {
+ return "", false, nil
+ }
tenants, err := h.registry.List()
if err != nil {
return "", false, err
diff --git a/internal/cloudcp/public_cloud_signup_handlers_test.go b/internal/cloudcp/public_cloud_signup_handlers_test.go
index d56c304893..19a233eedc 100644
--- a/internal/cloudcp/public_cloud_signup_handlers_test.go
+++ b/internal/cloudcp/public_cloud_signup_handlers_test.go
@@ -15,15 +15,16 @@ import (
)
type captureMagicLinkGenerator struct {
- calls int
- email string
- tenantID string
- token string
- err error
+ tenantCalls int
+ portalCalls int
+ email string
+ tenantID string
+ token string
+ err error
}
func (c *captureMagicLinkGenerator) GenerateToken(email, tenantID string) (string, error) {
- c.calls++
+ c.tenantCalls++
c.email = email
c.tenantID = tenantID
if c.err != nil {
@@ -32,6 +33,32 @@ func (c *captureMagicLinkGenerator) GenerateToken(email, tenantID string) (strin
return c.token, nil
}
+func (c *captureMagicLinkGenerator) GeneratePortalToken(email string) (string, error) {
+ c.portalCalls++
+ c.email = email
+ c.tenantID = ""
+ if c.err != nil {
+ return "", c.err
+ }
+ return c.token, nil
+}
+
+type captureCommercialIdentityLookup struct {
+ calls int
+ email string
+ result *CommercialIdentityLookupResult
+ err error
+}
+
+func (c *captureCommercialIdentityLookup) LookupCommercialIdentity(_ context.Context, email string) (*CommercialIdentityLookupResult, error) {
+ c.calls++
+ c.email = email
+ if c.err != nil {
+ return nil, c.err
+ }
+ return c.result, nil
+}
+
type captureEmailSender struct {
calls int
msg cpemail.Message
@@ -217,8 +244,11 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestKnownTenantSendsEmail(t *t
if rec.Code != http.StatusOK {
t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
}
- if magic.calls != 1 {
- t.Fatalf("magic GenerateToken calls=%d, want 1", magic.calls)
+ if magic.tenantCalls != 1 {
+ t.Fatalf("magic GenerateToken calls=%d, want 1", magic.tenantCalls)
+ }
+ if magic.portalCalls != 0 {
+ t.Fatalf("magic GeneratePortalToken calls=%d, want 0", magic.portalCalls)
}
if magic.tenantID != "t-test-1" {
t.Fatalf("magic tenantID=%q, want %q", magic.tenantID, "t-test-1")
@@ -234,6 +264,91 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestKnownTenantSendsEmail(t *t
}
}
+func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalTargetKnownTenantUsesPortalToken(t *testing.T) {
+ dir := t.TempDir()
+ reg, err := registry.NewTenantRegistry(dir)
+ if err != nil {
+ t.Fatalf("NewTenantRegistry: %v", err)
+ }
+ t.Cleanup(func() { _ = reg.Close() })
+
+ if err := reg.Create(&registry.Tenant{
+ ID: "t-portal-1",
+ AccountID: "a-portal-1",
+ Email: "[email protected]",
+ DisplayName: "Pulse Labs",
+ State: registry.TenantStateActive,
+ }); err != nil {
+ t.Fatalf("Create tenant: %v", err)
+ }
+
+ magic := &captureMagicLinkGenerator{token: "ml_portal_123"}
+ emailSender := &captureEmailSender{}
+ h := NewPublicCloudSignupHandlers(&CPConfig{
+ BaseURL: "https://cloud.example.com",
+ EmailFrom: "[email protected]",
+ }, reg, magic, emailSender)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/public/magic-link/request", strings.NewReader(`{"email":"[email protected]","target":"portal"}`))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+
+ h.HandlePublicMagicLinkRequest(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ if magic.portalCalls != 1 {
+ t.Fatalf("magic GeneratePortalToken calls=%d, want 1", magic.portalCalls)
+ }
+ if magic.tenantCalls != 0 {
+ t.Fatalf("magic GenerateToken calls=%d, want 0", magic.tenantCalls)
+ }
+ if emailSender.calls != 1 {
+ t.Fatalf("email sender calls=%d, want 1", emailSender.calls)
+ }
+}
+
+func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalTargetCommercialOnlyUsesPortalToken(t *testing.T) {
+ magic := &captureMagicLinkGenerator{token: "ml_portal_456"}
+ emailSender := &captureEmailSender{}
+ lookup := &captureCommercialIdentityLookup{
+ result: &CommercialIdentityLookupResult{
+ Email: "[email protected]",
+ HasCommercialIdentity: true,
+ Sources: []string{"v5_license"},
+ V5LicenseCount: 1,
+ },
+ }
+ h := NewPublicCloudSignupHandlers(&CPConfig{
+ BaseURL: "https://cloud.example.com",
+ EmailFrom: "[email protected]",
+ }, nil, magic, emailSender)
+ h.commercialIdentities = lookup
+
+ req := httptest.NewRequest(http.MethodPost, "/api/public/magic-link/request", strings.NewReader(`{"email":"[email protected]","target":"portal"}`))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+
+ h.HandlePublicMagicLinkRequest(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ if lookup.calls != 1 {
+ t.Fatalf("commercial lookup calls=%d, want 1", lookup.calls)
+ }
+ if magic.portalCalls != 1 {
+ t.Fatalf("magic GeneratePortalToken calls=%d, want 1", magic.portalCalls)
+ }
+ if magic.tenantCalls != 0 {
+ t.Fatalf("magic GenerateToken calls=%d, want 0", magic.tenantCalls)
+ }
+ if emailSender.calls != 1 {
+ t.Fatalf("email sender calls=%d, want 1", emailSender.calls)
+ }
+}
+
func TestPublicCloudSignupCheckoutMetadataIncludesPlanVersion(t *testing.T) {
// Use a real Stripe price ID from PriceIDToPlanVersion so plan_version is set.
h := NewPublicCloudSignupHandlers(&CPConfig{