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(hosted): enforce tenant org membership during handoff

Richard Courtman55df4927e975
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f20edfc93c..af72339910 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -149,6 +149,13 @@ relay bootstrap reads use one effective hosted billing lease before
lifecycle-adjacent flows inspect runtime readiness, so install and setup
surfaces do not observe a tenant-org Pulse Assistant state that disagrees
with the machine-owned hosted entitlement already backing the same instance.
+That same shared dependency now also assumes hosted cloud handoff makes tenant
+org access real before browser lifecycle continues. Lifecycle-adjacent opens
+into hosted workspaces may depend on `internal/api/cloud_handoff_handlers.go`,
+but the canonical contract is that a successful handoff exchange must reconcile
+tenant organization membership for the handed-off account member before the
+browser follows the new session into protected routes, rather than landing on a
+fresh `access_denied` immediately after session minting.
Agent lifecycle owns the install/register/update continuity surfaces, but it
does not own unified-resource history or control-plane timeline persistence.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 6d08b32198..7204dc2f08 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -242,6 +242,15 @@ 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 tenant handoff now owns tenant-org access continuity too. When
+`internal/api/cloud_handoff_handlers.go` accepts a control-plane-minted handoff
+token, it must normalize the handed-off email, reconcile the tenant
+organization membership for that email from the asserted account role, and only
+then mint the hosted browser session and `pulse_org_id` cookie. A successful
+handoff exchange is therefore not just a session-creation event; it is the
+canonical contract that prevents hosted workspace opens from landing on an
+immediate `403 access_denied` because the tenant org metadata lagged behind the
+control-plane account membership truth.
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/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 4b9e7832b8..ce5298a5ca 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -258,6 +258,14 @@ operators can revisit the hosted handoff without getting locked out for a day,
and both the local app server and hosted trial signup limiters must return the
actual remaining backoff through `Retry-After` rather than a coarse full-window
guess. Shared trial-start presentation must treat that backoff as canonical and
+Hosted tenant organization seeding and hosted handoff role mapping now belong
+to the same cloud-paid truth too. `internal/cloudcp/stripe/provisioner.go`
+must seed tenant org members from the shared account-role-to-organization-role
+mapping, and hosted handoff/runtime consumers must preserve that same mapping
+when older workspaces need membership continuity repaired at open time. Cloud,
+MSP, and commercial account roles therefore have one canonical translation into
+tenant org permissions instead of drifting between provisioning-time seeds and
+handoff-time access repair.
surface it consistently instead of flattening every `429` into generic copy.
For the hosted self-serve flow, that also means the public trial pages and form
posts must render the owned Pulse trial experience with preserved instance/form
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 03db47dc9f..903cfd49e6 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -130,6 +130,12 @@ runtime data-dir authority being replaceable without hangs or leaked state,
and router teardown must close the exact session, CSRF, and recovery-token
workers that router initialized instead of assuming a later global auth-store
binding will clean them up.
+That same hosted handoff dependency also assumes the exchange path repairs
+tenant org access before redirecting the browser into protected routes.
+Recovery- and storage-adjacent hosted pages that open immediately after
+control-plane handoff must see a real tenant member session, not a freshly
+minted browser cookie that still fails tenant authorization because the org
+metadata lagged behind control-plane account membership.
That shared `internal/api/` dependency now also assumes hosted tenant AI
bootstrap and chat-runtime reads resolve through one effective hosted billing
lease before storage- or recovery-adjacent runtime consumers inspect
diff --git a/internal/api/cloud_handoff_handlers.go b/internal/api/cloud_handoff_handlers.go
index 36a52f2796..cb9fbd062e 100644
--- a/internal/api/cloud_handoff_handlers.go
+++ b/internal/api/cloud_handoff_handlers.go
@@ -15,6 +15,8 @@ import (
"time"
"github.com/golang-jwt/jwt/v5"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
_ "modernc.org/sqlite"
)
@@ -355,6 +357,11 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
return
}
+ if err := ensureHandoffOrganizationMembership(configDir, tenantID, claims.Email, claims.Role); err != nil {
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+
// Invalidate any pre-existing session to prevent session fixation attacks.
InvalidateOldSessionFromRequest(r)
@@ -420,3 +427,73 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
}
+
+func ensureHandoffOrganizationMembership(configDir, tenantID, email, role string) error {
+ mtp := config.NewMultiTenantPersistence(configDir)
+ org, err := mtp.LoadOrganization(tenantID)
+ if err != nil {
+ return fmt.Errorf("load tenant organization %s: %w", tenantID, err)
+ }
+
+ now := time.Now().UTC()
+ if org == nil {
+ org = &models.Organization{}
+ }
+ if strings.TrimSpace(org.ID) == "" {
+ org.ID = tenantID
+ }
+ if strings.TrimSpace(org.DisplayName) == "" {
+ org.DisplayName = tenantID
+ }
+ if models.NormalizeOrgStatus(org.Status) == "" {
+ org.Status = models.OrgStatusActive
+ } else {
+ org.Status = models.NormalizeOrgStatus(org.Status)
+ }
+ if org.CreatedAt.IsZero() {
+ org.CreatedAt = now
+ }
+
+ desiredRole := models.OrganizationRoleFromAccountRole(role)
+ memberFound := false
+ for i := range org.Members {
+ if !strings.EqualFold(strings.TrimSpace(org.Members[i].UserID), email) {
+ continue
+ }
+ memberFound = true
+ org.Members[i].UserID = email
+ if !models.OrganizationRoleAtLeast(org.Members[i].Role, desiredRole) {
+ org.Members[i].Role = desiredRole
+ }
+ if org.Members[i].AddedAt.IsZero() {
+ org.Members[i].AddedAt = now
+ }
+ if strings.TrimSpace(org.Members[i].AddedBy) == "" {
+ addedBy := strings.TrimSpace(org.OwnerUserID)
+ if addedBy == "" {
+ addedBy = email
+ }
+ org.Members[i].AddedBy = addedBy
+ }
+ break
+ }
+
+ if !memberFound {
+ addedBy := strings.TrimSpace(org.OwnerUserID)
+ if addedBy == "" {
+ addedBy = email
+ }
+ org.Members = append(org.Members, models.OrganizationMember{
+ UserID: email,
+ Role: desiredRole,
+ AddedAt: now,
+ AddedBy: addedBy,
+ })
+ }
+
+ if desiredRole == models.OrgRoleOwner && strings.TrimSpace(org.OwnerUserID) == "" {
+ org.OwnerUserID = email
+ }
+
+ return mtp.SaveOrganization(org)
+}
diff --git a/internal/api/cloud_handoff_handlers_test.go b/internal/api/cloud_handoff_handlers_test.go
index 6c4cc779b3..88d666b6bd 100644
--- a/internal/api/cloud_handoff_handlers_test.go
+++ b/internal/api/cloud_handoff_handlers_test.go
@@ -14,6 +14,8 @@ import (
"time"
"github.com/golang-jwt/jwt/v5"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
)
func signHandoffToken(t *testing.T, key []byte, claims cloudHandoffClaims) string {
@@ -503,6 +505,73 @@ func TestHandleHandoffExchangeBrowserFlowSetsSessionCookies(t *testing.T) {
}
}
+func TestHandleHandoffExchangeEnsuresTenantOrganizationMembership(t *testing.T) {
+ key := []byte("test-handoff-key")
+ configDir := t.TempDir()
+ resetSessionStoreForTests()
+ t.Cleanup(resetSessionStoreForTests)
+ resetCSRFStoreForTests()
+ t.Cleanup(resetCSRFStoreForTests)
+ InitSessionStore(configDir)
+ InitCSRFStore(configDir)
+
+ secretsDir := filepath.Join(configDir, "secrets")
+ if err := os.MkdirAll(secretsDir, 0o755); err != nil {
+ t.Fatalf("MkdirAll() error = %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(secretsDir, "handoff.key"), key, 0o600); err != nil {
+ t.Fatalf("WriteFile() error = %v", err)
+ }
+
+ tenantID := "tenant-membership"
+ mtp := config.NewMultiTenantPersistence(configDir)
+ if err := mtp.SaveOrganization(&models.Organization{
+ ID: tenantID,
+ DisplayName: "Membership Test",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ Members: []models.OrganizationMember{
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ },
+ }); err != nil {
+ t.Fatalf("SaveOrganization() error = %v", err)
+ }
+
+ handler := HandleHandoffExchange(configDir)
+ token := signHandoffToken(t, key, cloudHandoffClaims{
+ AccountID: "acct-membership",
+ Email: "[email protected]",
+ Role: "owner",
+ RegisteredClaims: jwt.RegisteredClaims{
+ ID: "jti-membership",
+ Subject: "user-membership",
+ Issuer: cloudHandoffIssuer,
+ Audience: jwt.ClaimStrings{tenantID},
+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
+ },
+ })
+
+ rec := makeExchangeRequest(t, handler, tenantID+".example.com", token)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+
+ org, err := mtp.LoadOrganization(tenantID)
+ if err != nil {
+ t.Fatalf("LoadOrganization() error = %v", err)
+ }
+ if org.OwnerUserID != "[email protected]" {
+ t.Fatalf("OwnerUserID = %q, want %q", org.OwnerUserID, "[email protected]")
+ }
+ if got := org.GetMemberRole("[email protected]"); got != models.OrgRoleOwner {
+ t.Fatalf("role for [email protected] = %q, want %q", got, models.OrgRoleOwner)
+ }
+ if !org.CanUserAccess("[email protected]") {
+ t.Fatal("expected handed-off user to have tenant organization access")
+ }
+}
+
func TestHandleHandoffExchangeKeyMissing(t *testing.T) {
handler := HandleHandoffExchange(t.TempDir())
t.Setenv("PULSE_TENANT_ID", "")
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index e33db06791..c577d84f6e 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -2686,6 +2686,81 @@ func TestContract_TenantAIServiceAvoidsSnapshotProviderBridge(t *testing.T) {
}
}
+func TestContract_HostedCloudHandoffEnsuresTenantOrganizationMembership(t *testing.T) {
+ key := []byte("test-handoff-key")
+ configDir := t.TempDir()
+ resetSessionStoreForTests()
+ t.Cleanup(resetSessionStoreForTests)
+ resetCSRFStoreForTests()
+ t.Cleanup(resetCSRFStoreForTests)
+ InitSessionStore(configDir)
+ InitCSRFStore(configDir)
+
+ secretsDir := filepath.Join(configDir, "secrets")
+ if err := os.MkdirAll(secretsDir, 0o755); err != nil {
+ t.Fatalf("mkdir secrets dir: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(secretsDir, "handoff.key"), key, 0o600); err != nil {
+ t.Fatalf("write handoff key: %v", err)
+ }
+
+ tenantID := "tenant-contract-membership"
+ mtp := config.NewMultiTenantPersistence(configDir)
+ if err := mtp.SaveOrganization(&models.Organization{
+ ID: tenantID,
+ DisplayName: "Contract Membership",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ Members: []models.OrganizationMember{
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ },
+ }); err != nil {
+ t.Fatalf("save organization: %v", err)
+ }
+
+ token := signHandoffToken(t, key, cloudHandoffClaims{
+ AccountID: "acct-contract-membership",
+ Email: "[email protected]",
+ Role: "owner",
+ RegisteredClaims: jwt.RegisteredClaims{
+ ID: "jti-contract-membership",
+ Subject: "user-contract-membership",
+ Issuer: cloudHandoffIssuer,
+ Audience: jwt.ClaimStrings{tenantID},
+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
+ },
+ })
+
+ form := url.Values{}
+ form.Set("token", token)
+ t.Setenv("PULSE_HOSTED_MODE", "true")
+ t.Setenv("PULSE_TENANT_ID", "")
+ t.Setenv("PULSE_PUBLIC_URL", "")
+ req := httptest.NewRequest(http.MethodPost, "/api/cloud/handoff/exchange?format=json", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+ req.Host = tenantID + ".cloud.pulserelay.pro"
+ req.RemoteAddr = "198.51.100.20:1234"
+ rec := httptest.NewRecorder()
+
+ HandleHandoffExchange(configDir).ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+
+ org, err := mtp.LoadOrganization(tenantID)
+ if err != nil {
+ t.Fatalf("load organization: %v", err)
+ }
+ if org.OwnerUserID != "[email protected]" {
+ t.Fatalf("ownerUserID=%q, want %q", org.OwnerUserID, "[email protected]")
+ }
+ if got := org.GetMemberRole("[email protected]"); got != models.OrgRoleOwner {
+ t.Fatalf("member role=%q, want %q", got, models.OrgRoleOwner)
+ }
+}
+
func TestContract_APITokenDeleteRejectsScopeEscalation(t *testing.T) {
router := &Router{
config: &config.Config{
diff --git a/internal/cloudcp/stripe/msp_lifecycle_integration_test.go b/internal/cloudcp/stripe/msp_lifecycle_integration_test.go
index fd42f61a01..29b9c62e80 100644
--- a/internal/cloudcp/stripe/msp_lifecycle_integration_test.go
+++ b/internal/cloudcp/stripe/msp_lifecycle_integration_test.go
@@ -17,6 +17,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/portal"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
@@ -580,6 +581,20 @@ func TestMSPLifecycle_CreateWorkspaceViaAPISeedsCreatorAsOwner(t *testing.T) {
}); err != nil {
t.Fatalf("CreateMembership: %v", err)
}
+ adminID, err := registry.GenerateUserID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.CreateUser(&registry.User{ID: adminID, Email: "[email protected]"}); err != nil {
+ t.Fatalf("CreateUser: %v", err)
+ }
+ if err := reg.CreateMembership(&registry.AccountMembership{
+ AccountID: accountID,
+ UserID: adminID,
+ Role: registry.MemberRoleAdmin,
+ }); err != nil {
+ t.Fatalf("CreateMembership: %v", err)
+ }
tenantMux := newTenantMux(reg, provisioner)
req := httptest.NewRequest(http.MethodPost, "/api/accounts/"+accountID+"/tenants", bytes.NewBufferString(`{"display_name":"Creator Seeded Workspace"}`))
@@ -611,6 +626,9 @@ func TestMSPLifecycle_CreateWorkspaceViaAPISeedsCreatorAsOwner(t *testing.T) {
if org.GetMemberRole("[email protected]") != "owner" {
t.Fatalf("legacy owner role = %q, want owner", org.GetMemberRole("[email protected]"))
}
+ if org.GetMemberRole("[email protected]") != models.OrganizationRoleFromAccountRole(string(registry.MemberRoleAdmin)) {
+ t.Fatalf("admin role = %q, want %q", org.GetMemberRole("[email protected]"), models.OrganizationRoleFromAccountRole(string(registry.MemberRoleAdmin)))
+ }
}
// TestMSPLifecycle_TenantIsolation verifies that workspaces from one MSP
diff --git a/internal/cloudcp/stripe/provisioner.go b/internal/cloudcp/stripe/provisioner.go
index 7f6cdd5084..0e51ae2822 100644
--- a/internal/cloudcp/stripe/provisioner.go
+++ b/internal/cloudcp/stripe/provisioner.go
@@ -172,21 +172,6 @@ func (p *Provisioner) ensureHostedDefaultPersistence(tenantDataDir string) error
return nil
}
-func mapAccountRoleToOrganizationRole(role registry.MemberRole) models.OrganizationRole {
- switch role {
- case registry.MemberRoleOwner:
- return models.OrgRoleOwner
- case registry.MemberRoleAdmin:
- return models.OrgRoleAdmin
- case registry.MemberRoleTech:
- return models.OrgRoleEditor
- case registry.MemberRoleReadOnly:
- return models.OrgRoleViewer
- default:
- return models.OrgRoleViewer
- }
-}
-
func (p *Provisioner) buildSeededTenantOrganization(accountID, tenantID, displayName, fallbackOwnerEmail string) (*models.Organization, error) {
now := time.Now().UTC()
org := &models.Organization{
@@ -232,7 +217,7 @@ func (p *Provisioner) buildSeededTenantOrganization(accountID, tenantID, display
if email == "" {
return nil, fmt.Errorf("account member %s has empty email", membership.UserID)
}
- role := mapAccountRoleToOrganizationRole(membership.Role)
+ role := models.OrganizationRoleFromAccountRole(string(membership.Role))
if existing, ok := memberSeeds[email]; !ok || models.OrganizationRoleAtLeast(role, existing.role) {
memberSeeds[email] = memberSeed{email: email, role: role}
}
diff --git a/internal/models/account_roles.go b/internal/models/account_roles.go
new file mode 100644
index 0000000000..3079d0aa0b
--- /dev/null
+++ b/internal/models/account_roles.go
@@ -0,0 +1,20 @@
+package models
+
+import "strings"
+
+// OrganizationRoleFromAccountRole maps control-plane commercial/account roles to
+// tenant organization roles for hosted handoff and seeded tenant metadata.
+func OrganizationRoleFromAccountRole(role string) OrganizationRole {
+ switch strings.ToLower(strings.TrimSpace(role)) {
+ case "owner":
+ return OrgRoleOwner
+ case "admin":
+ return OrgRoleAdmin
+ case "tech":
+ return OrgRoleEditor
+ case "read_only":
+ return OrgRoleViewer
+ default:
+ return OrgRoleViewer
+ }
+}