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.

Harden cloud handoff membership authorization

rcourtman02e9107ac47e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 74a1be45e9..fe425e9264 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -647,13 +647,15 @@ prior chat session. Lifecycle-adjacent mobile pairing and setup flows depend
on `/api/ai/approvals` becoming ready from the first governed settings save,
not only after some earlier process-start or chat-start side effect has
already initialized the approval store.
-That same shared dependency now also assumes hosted cloud handoff makes tenant
-org access real before browser lifecycle continues. Lifecycle-adjacent opens
+That same shared dependency now also assumes hosted cloud handoff authorizes
+tenant org access 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.
+but the canonical contract is that a successful handoff exchange may continue
+only when the handed-off account already has server-owned tenant membership.
+The exchange path must derive the effective role from the existing owner/member
+record, reject any handoff claim that would upgrade that stored role, and fail
+closed when the tenant org still has a blank `OwnerUserID` instead of letting
+the first owner-shaped token claim the tenant during browser session minting.
Lifecycle-owned paywalls now also follow the shared commercial navigation
contract. `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx` and
`frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts` may
@@ -695,9 +697,11 @@ and memory do not silently pay for disk/network guest fan-out.
That same hosted continuity contract also applies to the older direct tenant
magic-link path. Lifecycle-adjacent control-plane redirects through
`/auth/cloud-handoff` must preserve canonical account/user/role identity in the
-handoff token long enough for the tenant runtime to repair org membership
-before it lands in protected hosted routes, rather than letting direct opens
-diverge from the newer portal exchange path.
+handoff token long enough for the tenant runtime to validate the existing org
+membership and derive the bounded effective role before it lands in protected
+hosted routes. Direct opens must fail closed on missing membership, blank-owner
+orgs, or owner/admin role escalation attempts instead of diverging from the
+newer portal exchange path by repairing org metadata on arrival.
That same shared `internal/api/` dependency also assumes telemetry
transparency remains explicitly system-settings-owned. When lifecycle-adjacent
setup or router work touches shared `internal/api/` files, telemetry preview
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 9d730fe8c9..232e487392 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -207,7 +207,17 @@ the canonical monitored-system blocked payload.
16. Keep Patrol intelligence summary transport semantics single-voiced: the canonical overall-health payload and Patrol run-history payload together must support one primary assessment plus one explicit verification explanation, and frontend consumers must not need to derive a second compact assessment or verification verdict row from the same payloads beneath the primary summary card.
17. Keep Pulse Mobile relay credential minting and permission ownership on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, `internal/api/auth.go`, `internal/api/relay_mobile_capability.go`, `internal/api/router_routes_ai_relay.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator and governed route gates, but browser callers must only consume that route and must not define the mobile runtime scope, compatibility gate list, route inventory, or token-purpose metadata locally.
18. Keep hosted tenant browser-session precedence on the shared auth boundary: `internal/api/auth.go`, `internal/api/contract_test.go`, and hosted tenant callers must treat a valid `pulse_session` as authoritative before any API-only token fallback or no-local-auth anonymous fallback, so cloud handoff can continue into protected hosted routes without flattening the operator back to `anonymous` or forcing a browser session through bearer-token-only mode after the tenant has minted API tokens.
+ That same shared auth boundary also owns hosted handoff authorization. `internal/api/cloud_handoff.go`,
+ `internal/api/cloud_handoff_handlers.go`, and hosted tenant callers must derive the effective tenant role from
+ pre-existing server-side org membership only, rather than trusting the handoff JWT to append missing members,
+ repair org metadata, or upgrade roles on arrival. Handoff may mint a browser session only when the tenant org
+ already contains the account as the owner or a member with a valid stored role, and tenant orgs with a blank
+ `OwnerUserID` must fail closed instead of being claimed by the first owner-shaped handoff token.
19. Keep tenant settings-scope authorization aligned with org management: `internal/api/security_setup_fix.go`, `internal/api/contract_test.go`, and settings-bound hosted callers must allow the current non-default org owner/admin membership to exercise privileged tenant routes, rather than requiring a separate configured local admin identity after hosted handoff.
+ Hosted handoff must not be treated as an org-management side effect for that same privilege boundary. Only
+ canonical invitation, membership-management, or explicit owner-transfer flows may create tenant membership or
+ change the stored owner/admin role. Shared auth routes and downstream settings consumers must treat handoff role
+ claims as bounded by the server-owned membership record, never as authority to elevate tenant privileges.
20. Keep mobile onboarding payload reads aligned with the server-owned relay-mobile credential: `internal/api/router_routes_ai_relay.go`, `internal/api/onboarding_handlers.go`, and `internal/api/contract_test.go` must allow the dedicated `relay:mobile:access` scope to reach the governed QR, deep-link, and connection-validation payloads without reintroducing a broader `settings:read` requirement for token-authenticated pairing clients.
That same shared relay/runtime boundary also owns hostname target
equivalence for agent command routing. `internal/api/router_routes_ai_relay.go`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 689f800d06..48a00b72fb 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -797,12 +797,14 @@ knowledge, and discovery records may discover legacy identifier-derived files
only for migration, and the next successful write must replace those legacy
paths with hashed canonical names so operator-controlled identifiers do not
become durable filesystem path segments.
-That same hosted handoff dependency also assumes the exchange path repairs
+That same hosted handoff dependency also assumes the exchange path authorizes
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.
+control-plane handoff must see a real tenant member session backed by a
+pre-existing owner/member record, not a freshly minted browser cookie created
+by appending missing members or upgrading roles from the handoff token.
+Missing tenant membership, blank-owner orgs, and role-escalation claims must
+all fail closed before protected recovery routes load.
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
@@ -2248,8 +2250,10 @@ admin identity that hosted tenants do not carry.
That same hosted continuity assumption also applies when operators arrive via
the older direct tenant magic-link path. Recovery- and storage-adjacent hosted
opens that still redirect through `/auth/cloud-handoff` must carry enough
-canonical account/role identity for the tenant runtime to repair membership
-before protected routes load, not just the newer portal exchange path.
+canonical account/role identity for the tenant runtime to validate existing
+membership and derive the stored effective role before protected routes load,
+not just the newer portal exchange path. The direct path must not repair org
+membership, claim a blank owner, or honor role upgrades from handoff claims.
That same adjacent onboarding boundary must also keep the dedicated
relay-mobile bootstrap credential sufficient for QR, deep-link, and
connection-validation reads, so hosted recovery/support flows that hand a
diff --git a/internal/api/cloud_handoff.go b/internal/api/cloud_handoff.go
index 315e22ac7e..243a8c00f4 100644
--- a/internal/api/cloud_handoff.go
+++ b/internal/api/cloud_handoff.go
@@ -3,6 +3,7 @@ package api
import (
"crypto/sha256"
"encoding/hex"
+ "errors"
"net/http"
"os"
"path/filepath"
@@ -56,12 +57,21 @@ func HandleCloudHandoff(dataPath string) http.HandlerFunc {
http.Redirect(w, r, "/login?error=handoff_invalid", http.StatusTemporaryRedirect)
return
}
- if err := ensureHandoffOrganizationMembership(dataPath, tenantID, email, claims.Role); err != nil {
+ if _, err := authorizeHandoffOrganizationMembership(dataPath, tenantID, email, claims.Role); err != nil {
+ if errors.Is(err, errHandoffAuthorizationDenied) {
+ log.Warn().
+ Err(err).
+ Str("tenant_id", tenantID).
+ Str("email", email).
+ Msg("Cloud handoff authorization denied")
+ http.Redirect(w, r, "/login?error=handoff_invalid", http.StatusTemporaryRedirect)
+ return
+ }
log.Error().
Err(err).
Str("tenant_id", tenantID).
Str("email", email).
- Msg("Cloud handoff membership repair failed")
+ Msg("Cloud handoff authorization lookup failed")
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
diff --git a/internal/api/cloud_handoff_handlers.go b/internal/api/cloud_handoff_handlers.go
index cb9fbd062e..b863d52283 100644
--- a/internal/api/cloud_handoff_handlers.go
+++ b/internal/api/cloud_handoff_handlers.go
@@ -27,6 +27,8 @@ const (
handoffPrivateFilePerm = 0o600
)
+var errHandoffAuthorizationDenied = errors.New("handoff authorization denied")
+
type cloudHandoffClaims struct {
AccountID string `json:"account_id"`
Email string `json:"email"`
@@ -357,7 +359,12 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
return
}
- if err := ensureHandoffOrganizationMembership(configDir, tenantID, claims.Email, claims.Role); err != nil {
+ effectiveRole, err := authorizeHandoffOrganizationMembership(configDir, tenantID, claims.Email, claims.Role)
+ if err != nil {
+ if errors.Is(err, errHandoffAuthorizationDenied) {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
@@ -414,7 +421,7 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
"account_id": claims.AccountID,
"user_id": claims.Subject,
"email": claims.Email,
- "role": claims.Role,
+ "role": string(effectiveRole),
"jti": claims.ID,
"exp": claims.ExpiresAt.Time.UTC().Format(time.RFC3339),
}
@@ -428,72 +435,54 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
}
}
-func ensureHandoffOrganizationMembership(configDir, tenantID, email, role string) error {
+func authorizeHandoffOrganizationMembership(configDir, tenantID, email, role string) (models.OrganizationRole, error) {
mtp := config.NewMultiTenantPersistence(configDir)
org, err := mtp.LoadOrganization(tenantID)
if err != nil {
- return fmt.Errorf("load tenant organization %s: %w", tenantID, err)
+ 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
+ return "", fmt.Errorf("%w: tenant organization %s is missing", errHandoffAuthorizationDenied, 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
+
+ email = normalizeHandoffEmail(email)
+ if email == "" {
+ return "", fmt.Errorf("%w: handoff email is empty", errHandoffAuthorizationDenied)
}
- 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
+ effectiveRole := models.OrganizationRole("")
+ if strings.EqualFold(strings.TrimSpace(org.OwnerUserID), email) {
+ effectiveRole = models.OrgRoleOwner
+ } else {
+ for i := range org.Members {
+ if !strings.EqualFold(strings.TrimSpace(org.Members[i].UserID), email) {
+ continue
}
- org.Members[i].AddedBy = addedBy
+ effectiveRole = models.NormalizeOrganizationRole(org.Members[i].Role)
+ break
}
- 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 effectiveRole == "" {
+ return "", fmt.Errorf("%w: no pre-existing membership for %s", errHandoffAuthorizationDenied, email)
+ }
+ if !models.IsValidOrganizationRole(effectiveRole) {
+ return "", fmt.Errorf("%w: stored role %q for %s is invalid", errHandoffAuthorizationDenied, effectiveRole, email)
+ }
+ if effectiveRole == models.OrgRoleOwner && strings.TrimSpace(org.OwnerUserID) == "" {
+ return "", fmt.Errorf("%w: tenant organization %s has blank owner", errHandoffAuthorizationDenied, tenantID)
}
- if desiredRole == models.OrgRoleOwner && strings.TrimSpace(org.OwnerUserID) == "" {
- org.OwnerUserID = email
+ desiredRole := models.OrganizationRoleFromAccountRole(role)
+ if !models.OrganizationRoleAtLeast(effectiveRole, desiredRole) {
+ return "", fmt.Errorf(
+ "%w: requested role %q exceeds stored role %q for %s",
+ errHandoffAuthorizationDenied,
+ desiredRole,
+ effectiveRole,
+ email,
+ )
}
- return mtp.SaveOrganization(org)
+ return effectiveRole, nil
}
diff --git a/internal/api/cloud_handoff_handlers_test.go b/internal/api/cloud_handoff_handlers_test.go
index 88d666b6bd..728e4361cb 100644
--- a/internal/api/cloud_handoff_handlers_test.go
+++ b/internal/api/cloud_handoff_handlers_test.go
@@ -43,6 +43,26 @@ func makeExchangeRequest(t *testing.T, handler http.HandlerFunc, host, token str
return rec
}
+func saveHandoffTestOrganization(t *testing.T, configDir string, org *models.Organization) *config.MultiTenantPersistence {
+ t.Helper()
+ mtp := config.NewMultiTenantPersistence(configDir)
+ if strings.TrimSpace(org.DisplayName) == "" {
+ org.DisplayName = org.ID
+ }
+ if org.CreatedAt.IsZero() {
+ org.CreatedAt = time.Now().UTC()
+ }
+ if strings.TrimSpace(string(org.Status)) == "" {
+ org.Status = models.OrgStatusActive
+ } else {
+ org.Status = models.NormalizeOrgStatus(org.Status)
+ }
+ if err := mtp.SaveOrganization(org); err != nil {
+ t.Fatalf("SaveOrganization() error = %v", err)
+ }
+ return mtp
+}
+
func TestIsSQLiteUniqueViolation(t *testing.T) {
if isSQLiteUniqueViolation(nil) {
t.Fatal("expected nil error to return false")
@@ -294,6 +314,18 @@ func TestHandleHandoffExchange(t *testing.T) {
handler := HandleHandoffExchange(configDir)
tenantID := "tenant-a"
host := tenantID + ".example.com"
+ saveHandoffTestOrganization(t, configDir, &models.Organization{
+ ID: tenantID,
+ DisplayName: "Tenant A",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ Members: []models.OrganizationMember{
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ },
+ })
t.Run("missing token returns bad request", func(t *testing.T) {
t.Setenv("PULSE_TENANT_ID", "")
@@ -451,6 +483,13 @@ func TestHandleHandoffExchangeBrowserFlowSetsSessionCookies(t *testing.T) {
handler := HandleHandoffExchange(configDir)
tenantID := "tenant-browser"
+ saveHandoffTestOrganization(t, configDir, &models.Organization{
+ ID: tenantID,
+ DisplayName: "Tenant Browser",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ })
token := signHandoffToken(t, key, cloudHandoffClaims{
AccountID: "acct-browser",
@@ -505,7 +544,7 @@ func TestHandleHandoffExchangeBrowserFlowSetsSessionCookies(t *testing.T) {
}
}
-func TestHandleHandoffExchangeEnsuresTenantOrganizationMembership(t *testing.T) {
+func TestHandleHandoffExchangeRejectsMissingTenantOrganizationMembership(t *testing.T) {
key := []byte("test-handoff-key")
configDir := t.TempDir()
resetSessionStoreForTests()
@@ -524,8 +563,7 @@ func TestHandleHandoffExchangeEnsuresTenantOrganizationMembership(t *testing.T)
}
tenantID := "tenant-membership"
- mtp := config.NewMultiTenantPersistence(configDir)
- if err := mtp.SaveOrganization(&models.Organization{
+ mtp := saveHandoffTestOrganization(t, configDir, &models.Organization{
ID: tenantID,
DisplayName: "Membership Test",
Status: models.OrgStatusActive,
@@ -534,9 +572,7 @@ func TestHandleHandoffExchangeEnsuresTenantOrganizationMembership(t *testing.T)
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{
@@ -553,8 +589,8 @@ func TestHandleHandoffExchangeEnsuresTenantOrganizationMembership(t *testing.T)
})
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())
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusForbidden, rec.Body.String())
}
org, err := mtp.LoadOrganization(tenantID)
@@ -564,11 +600,118 @@ func TestHandleHandoffExchangeEnsuresTenantOrganizationMembership(t *testing.T)
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 got := org.GetMemberRole("[email protected]"); got != "" {
+ t.Fatalf("role for [email protected] = %q, want empty", got)
+ }
+ if org.CanUserAccess("[email protected]") {
+ t.Fatal("expected handed-off user to remain outside the tenant organization")
}
- if !org.CanUserAccess("[email protected]") {
- t.Fatal("expected handed-off user to have tenant organization access")
+}
+
+func TestHandleHandoffExchangeRejectsRoleEscalationFromClaims(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-role-escalation"
+ mtp := saveHandoffTestOrganization(t, configDir, &models.Organization{
+ ID: tenantID,
+ DisplayName: "Role Escalation Test",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ Members: []models.OrganizationMember{
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ {UserID: "[email protected]", Role: models.OrgRoleViewer, AddedAt: time.Now().UTC()},
+ },
+ })
+
+ token := signHandoffToken(t, key, cloudHandoffClaims{
+ AccountID: "acct-role-escalation",
+ Email: "[email protected]",
+ Role: "owner",
+ RegisteredClaims: jwt.RegisteredClaims{
+ ID: "jti-role-escalation",
+ Subject: "user-role-escalation",
+ Issuer: cloudHandoffIssuer,
+ Audience: jwt.ClaimStrings{tenantID},
+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
+ },
+ })
+
+ rec := makeExchangeRequest(t, HandleHandoffExchange(configDir), tenantID+".example.com", token)
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusForbidden, rec.Body.String())
+ }
+
+ org, err := mtp.LoadOrganization(tenantID)
+ if err != nil {
+ t.Fatalf("LoadOrganization() error = %v", err)
+ }
+ if got := org.GetMemberRole("[email protected]"); got != models.OrgRoleViewer {
+ t.Fatalf("role for [email protected] = %q, want %q", got, models.OrgRoleViewer)
+ }
+}
+
+func TestHandleHandoffExchangeRejectsOwnerHandoffWhenOwnerUserIDBlank(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-blank-owner"
+ saveHandoffTestOrganization(t, configDir, &models.Organization{
+ ID: tenantID,
+ DisplayName: "Blank Owner Test",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "",
+ Members: []models.OrganizationMember{
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ },
+ })
+
+ token := signHandoffToken(t, key, cloudHandoffClaims{
+ AccountID: "acct-blank-owner",
+ Email: "[email protected]",
+ Role: "owner",
+ RegisteredClaims: jwt.RegisteredClaims{
+ ID: "jti-blank-owner",
+ Subject: "user-blank-owner",
+ Issuer: cloudHandoffIssuer,
+ Audience: jwt.ClaimStrings{tenantID},
+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
+ },
+ })
+
+ rec := makeExchangeRequest(t, HandleHandoffExchange(configDir), tenantID+".example.com", token)
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusForbidden, rec.Body.String())
}
}
diff --git a/internal/api/cloud_handoff_test.go b/internal/api/cloud_handoff_test.go
index 0958344cb9..36297f593f 100644
--- a/internal/api/cloud_handoff_test.go
+++ b/internal/api/cloud_handoff_test.go
@@ -10,7 +10,6 @@ import (
"testing"
"time"
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/pkg/cloudauth"
)
@@ -28,6 +27,13 @@ func TestHandleCloudHandoffRejectsReplay(t *testing.T) {
if err != nil {
t.Fatalf("sign handoff token: %v", err)
}
+ saveHandoffTestOrganization(t, dataPath, &models.Organization{
+ ID: "tenant-1",
+ DisplayName: "Tenant One",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ })
handler := HandleCloudHandoff(dataPath)
@@ -70,6 +76,13 @@ func TestHandleCloudHandoffSetsTenantOrgCookie(t *testing.T) {
if err != nil {
t.Fatalf("sign handoff token: %v", err)
}
+ saveHandoffTestOrganization(t, dataPath, &models.Organization{
+ ID: "tenant-1",
+ DisplayName: "Tenant One",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ })
handler := HandleCloudHandoff(dataPath)
@@ -127,16 +140,35 @@ func TestHandleCloudHandoffRejectsInvalidTenantID(t *testing.T) {
func TestHandleCloudHandoffLowercasesSessionEmailIdentity(t *testing.T) {
resetPersistentAuthStoresForTests()
t.Cleanup(resetPersistentAuthStoresForTests)
+ sessionsMu.Lock()
+ allSessions = make(map[string][]string)
+ sessionsMu.Unlock()
dataPath := t.TempDir()
key := []byte("0123456789abcdef0123456789abcdef")
if err := os.WriteFile(filepath.Join(dataPath, cloudauth.HandoffKeyFile), key, 0o600); err != nil {
t.Fatalf("write handoff key: %v", err)
}
- token, err := cloudauth.Sign(key, "[email protected]", "tenant-1", 5*time.Minute)
+ token, err := cloudauth.SignWithClaims(key, cloudauth.Claims{
+ Email: "[email protected]",
+ TenantID: "tenant-1",
+ AccountID: "acct-mixed-email",
+ UserID: "user-mixed-email",
+ Role: "owner",
+ }, 5*time.Minute)
if err != nil {
t.Fatalf("sign handoff token: %v", err)
}
+ saveHandoffTestOrganization(t, dataPath, &models.Organization{
+ ID: "tenant-1",
+ DisplayName: "Tenant One",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ Members: []models.OrganizationMember{
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ },
+ })
handler := HandleCloudHandoff(dataPath)
@@ -147,28 +179,33 @@ func TestHandleCloudHandoffLowercasesSessionEmailIdentity(t *testing.T) {
if rec.Code != http.StatusTemporaryRedirect {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusTemporaryRedirect)
}
+ if got := rec.Header().Get("Location"); got != "/" {
+ t.Fatalf("redirect = %q, want %q", got, "/")
+ }
- var sessionCookie *http.Cookie
- for _, c := range rec.Result().Cookies() {
- if strings.HasPrefix(c.Name, "pulse_session") {
- sessionCookie = c
+ sessionsMu.RLock()
+ tracked := append([]string(nil), allSessions["[email protected]"]...)
+ sessionsMu.RUnlock()
+ if len(tracked) == 0 {
+ t.Fatal("expected normalized user session to be tracked")
+ }
+
+ var session *SessionData
+ for i := len(tracked) - 1; i >= 0; i-- {
+ session = GetSessionStore().GetSession(tracked[i])
+ if session != nil {
break
}
}
- if sessionCookie == nil {
- t.Fatal("expected pulse_session cookie to be set")
- }
-
- session := GetSessionStore().GetSession(sessionCookie.Value)
if session == nil {
- t.Fatal("expected session to exist")
+ t.Fatal("expected tracked session to exist in the session store")
}
if session.Username != "[email protected]" {
t.Fatalf("session username = %q, want %q", session.Username, "[email protected]")
}
}
-func TestHandleCloudHandoffEnsuresTenantOrganizationMembershipFromClaims(t *testing.T) {
+func TestHandleCloudHandoffUsesExistingTenantOrganizationMembership(t *testing.T) {
resetPersistentAuthStoresForTests()
t.Cleanup(resetPersistentAuthStoresForTests)
dataPath := t.TempDir()
@@ -178,8 +215,7 @@ func TestHandleCloudHandoffEnsuresTenantOrganizationMembershipFromClaims(t *test
}
tenantID := "tenant-claims-membership"
- mtp := config.NewMultiTenantPersistence(dataPath)
- if err := mtp.SaveOrganization(&models.Organization{
+ mtp := saveHandoffTestOrganization(t, dataPath, &models.Organization{
ID: tenantID,
DisplayName: "Claims Membership",
Status: models.OrgStatusActive,
@@ -187,10 +223,9 @@ func TestHandleCloudHandoffEnsuresTenantOrganizationMembershipFromClaims(t *test
OwnerUserID: "[email protected]",
Members: []models.OrganizationMember{
{UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
},
- }); err != nil {
- t.Fatalf("save organization: %v", err)
- }
+ })
token, err := cloudauth.SignWithClaims(key, cloudauth.Claims{
@@ -227,3 +262,49 @@ func TestHandleCloudHandoffEnsuresTenantOrganizationMembershipFromClaims(t *test
t.Fatalf("member role = %q, want %q", got, models.OrgRoleOwner)
}
}
+
+func TestHandleCloudHandoffRejectsMissingTenantOrganizationMembership(t *testing.T) {
+ resetPersistentAuthStoresForTests()
+ t.Cleanup(resetPersistentAuthStoresForTests)
+ dataPath := t.TempDir()
+ key := []byte("0123456789abcdef0123456789abcdef")
+ if err := os.WriteFile(filepath.Join(dataPath, cloudauth.HandoffKeyFile), key, 0o600); err != nil {
+ t.Fatalf("write handoff key: %v", err)
+ }
+
+ tenantID := "tenant-missing-membership"
+ saveHandoffTestOrganization(t, dataPath, &models.Organization{
+ ID: tenantID,
+ DisplayName: "Missing Membership",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ Members: []models.OrganizationMember{
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ },
+ })
+
+ token, err := cloudauth.SignWithClaims(key, cloudauth.Claims{
+ Email: "[email protected]",
+ TenantID: tenantID,
+ AccountID: "acct-missing-membership",
+ UserID: "user-missing-membership",
+ Role: "owner",
+ }, 5*time.Minute)
+ if err != nil {
+ t.Fatalf("sign handoff token: %v", err)
+ }
+
+ handler := HandleCloudHandoff(dataPath)
+
+ req := httptest.NewRequest(http.MethodGet, "/auth/cloud-handoff?token="+url.QueryEscape(token), nil)
+ rec := httptest.NewRecorder()
+ handler(rec, req)
+
+ if rec.Code != http.StatusTemporaryRedirect {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusTemporaryRedirect, rec.Body.String())
+ }
+ if got := rec.Header().Get("Location"); got != "/login?error=handoff_invalid" {
+ t.Fatalf("redirect = %q, want %q", got, "/login?error=handoff_invalid")
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 55d4586ed1..080872872b 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -6849,6 +6849,13 @@ func TestContract_HandoffExchangeJSONSnapshot(t *testing.T) {
handler := HandleHandoffExchange(configDir)
tenantID := "tenant-contract"
+ saveHandoffTestOrganization(t, configDir, &models.Organization{
+ ID: tenantID,
+ DisplayName: "Contract Tenant",
+ Status: models.OrgStatusActive,
+ CreatedAt: time.Now().UTC(),
+ OwnerUserID: "[email protected]",
+ })
t.Setenv("PULSE_TENANT_ID", "")
token := signHandoffToken(t, key, cloudHandoffClaims{
AccountID: "acct-contract",
@@ -6934,7 +6941,7 @@ func TestContract_TenantAIServiceAvoidsSnapshotProviderBridge(t *testing.T) {
}
}
-func TestContract_HostedCloudHandoffEnsuresTenantOrganizationMembership(t *testing.T) {
+func TestContract_HostedCloudHandoffUsesExistingTenantOrganizationMembership(t *testing.T) {
key := []byte("test-handoff-key")
configDir := t.TempDir()
resetSessionStoreForTests()
@@ -6953,8 +6960,7 @@ func TestContract_HostedCloudHandoffEnsuresTenantOrganizationMembership(t *testi
}
tenantID := "tenant-contract-membership"
- mtp := config.NewMultiTenantPersistence(configDir)
- if err := mtp.SaveOrganization(&models.Organization{
+ mtp := saveHandoffTestOrganization(t, configDir, &models.Organization{
ID: tenantID,
DisplayName: "Contract Membership",
Status: models.OrgStatusActive,
@@ -6962,10 +6968,9 @@ func TestContract_HostedCloudHandoffEnsuresTenantOrganizationMembership(t *testi
OwnerUserID: "[email protected]",
Members: []models.OrganizationMember{
{UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ {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",
@@ -7009,7 +7014,7 @@ func TestContract_HostedCloudHandoffEnsuresTenantOrganizationMembership(t *testi
}
}
-func TestContract_HostedDirectCloudHandoffPreservesMembershipClaims(t *testing.T) {
+func TestContract_HostedDirectCloudHandoffUsesExistingTenantMembership(t *testing.T) {
key := []byte("test-direct-handoff-key")
configDir := t.TempDir()
resetPersistentAuthStoresForTests()
@@ -7020,8 +7025,7 @@ func TestContract_HostedDirectCloudHandoffPreservesMembershipClaims(t *testing.T
}
tenantID := "tenant-direct-contract"
- mtp := config.NewMultiTenantPersistence(configDir)
- if err := mtp.SaveOrganization(&models.Organization{
+ mtp := saveHandoffTestOrganization(t, configDir, &models.Organization{
ID: tenantID,
DisplayName: "Direct Contract Membership",
Status: models.OrgStatusActive,
@@ -7029,10 +7033,9 @@ func TestContract_HostedDirectCloudHandoffPreservesMembershipClaims(t *testing.T
OwnerUserID: "[email protected]",
Members: []models.OrganizationMember{
{UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
+ {UserID: "[email protected]", Role: models.OrgRoleOwner, AddedAt: time.Now().UTC()},
},
- }); err != nil {
- t.Fatalf("save organization: %v", err)
- }
+ })
token, err := cloudauth.SignWithClaims(key, cloudauth.Claims{