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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Require accepted Pulse Account invites before access binding
rcourtmane68bdc40e21a
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 12ee836c2d..4d50cefad2 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -805,7 +805,13 @@ fake disabled row state. That same typed bootstrap/runtime contract must alsoship the current hosted roster snapshot in the portal bootstrap payload so thefirst `Access` render is a real review surface rather than a fetch-first orerror-first placeholder; later member API reads remain refresh and mutation-follow-through. `Billing` follows the same shared runtime+follow-through. That same shared access contract must keep stable access+subject identity across bootstrap and mutation responses: hosted roster rows+carry `subject_id`, `state`, and optional `user_id`, unknown-email invites+return `202 Accepted` with `state=pending` instead of auto-binding a guessed+future user record, and portal magic-link verification may materialize that+pending subject into a membership only after the invited email authenticates+through the portal-owned session path. `Billing` follows the same shared runtimecontract: hosted billing remains the default primary path, self-hosted billingjobs open one panel at a time, and the runtime must reveal the active billingpanel on phone-width layouts instead of leaving it offscreen. The samediff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 8215b35d33..af5e361227 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -40,57 +40,62 @@ agreement, and cloud-specific enforcement rules.18. `pkg/licensing/purchase_return.go`19. `pkg/licensing/stripe_subscription.go`20. `pkg/licensing/monitored_system_limit.go`-21. `internal/cloudcp/account/tenant_handlers.go`-22. `internal/cloudcp/config.go`-23. `internal/cloudcp/entitlements/service.go`-24. `internal/cloudcp/portal/handlers.go`-25. `internal/cloudcp/portal/page.go`-26. `internal/cloudcp/public_cloud_signup_handlers.go`-27. `internal/cloudcp/registry/registry.go`-28. `internal/cloudcp/routes.go`-29. `internal/cloudcp/stripe/provisioner.go`-30. `internal/hosted/provisioner.go`-31. `frontend-modern/src/App.tsx`-32. `frontend-modern/src/AppLayout.tsx`-33. `frontend-modern/src/useAppRuntimeState.ts`-34. `frontend-modern/src/components/Commercial/MonitoredSystemDefinitionDisclosure.tsx`-35. `frontend-modern/src/components/Settings/BillingAdminPanel.tsx`-36. `frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx`-37. `frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx`-38. `frontend-modern/src/components/Settings/OrganizationBillingLoadingState.tsx`-39. `frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx`-40. `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`-41. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`-42. `frontend-modern/src/components/Settings/ProLicensePlanSection.tsx`-43. `frontend-modern/src/components/Settings/CommercialBillingSections.tsx`-44. `frontend-modern/src/components/Settings/SelfHostedCommercialRecoverySection.tsx`-45. `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`-46. `frontend-modern/src/components/Settings/RelayPairingSection.tsx`-47. `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`-48. `frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts`-49. `frontend-modern/src/components/Settings/useProLicensePanelState.ts`-50. `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`-51. `frontend-modern/src/pages/CloudPricing.tsx`-52. `frontend-modern/src/pages/HostedSignup.tsx`-53. `frontend-modern/src/pages/PricingHandoff.tsx`-54. `frontend-modern/src/utils/apiClient.ts`-55. `frontend-modern/src/utils/cloudPlans.ts`-56. `frontend-modern/src/utils/commercialBillingModel.ts`-57. `frontend-modern/src/utils/licensePresentation.ts`-58. `frontend-modern/src/utils/monitoredSystemPresentation.ts`-59. `frontend-modern/src/utils/pricingHandoff.ts`-60. `frontend-modern/src/utils/selfHostedPlans.ts`-61. `frontend-modern/src/utils/upgradePresentation.ts`-62. `frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts`-63. `pulse-pro:license-server/public_pricing.go`-64. `pulse-pro:license-server/v6_checkout.go`-65. `pulse-pro:landing-page/thanks.html`-66. `pulse-pro:scripts/grandfathered_recurring_cutover_preview.py`-67. `pulse-pro:scripts/validate_public_pricing_model.py`-68. `pulse-pro:V6_LAUNCH_CHECKLIST.md`-69. `pkg/licensing/trial_activation_public_key_override_dev.go`-70. `pkg/licensing/trial_activation_public_key_override_release.go`-71. `pkg/licensing/testing_helpers.go`+21. `internal/cloudcp/account/audit.go`+22. `internal/cloudcp/account/handlers.go`+23. `internal/cloudcp/account/tenant_handlers.go`+24. `internal/cloudcp/auth/handlers.go`+25. `internal/cloudcp/auth/session.go`+26. `internal/cloudcp/config.go`+27. `internal/cloudcp/entitlements/service.go`+28. `internal/cloudcp/portal/handlers.go`+29. `internal/cloudcp/portal/page.go`+30. `internal/cloudcp/public_cloud_signup_handlers.go`+31. `internal/cloudcp/registry/models.go`+32. `internal/cloudcp/registry/registry.go`+33. `internal/cloudcp/routes.go`+34. `internal/cloudcp/stripe/provisioner.go`+35. `internal/hosted/provisioner.go`+36. `frontend-modern/src/App.tsx`+37. `frontend-modern/src/AppLayout.tsx`+38. `frontend-modern/src/useAppRuntimeState.ts`+39. `frontend-modern/src/components/Commercial/MonitoredSystemDefinitionDisclosure.tsx`+40. `frontend-modern/src/components/Settings/BillingAdminPanel.tsx`+41. `frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx`+42. `frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx`+43. `frontend-modern/src/components/Settings/OrganizationBillingLoadingState.tsx`+44. `frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx`+45. `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`+46. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`+47. `frontend-modern/src/components/Settings/ProLicensePlanSection.tsx`+48. `frontend-modern/src/components/Settings/CommercialBillingSections.tsx`+49. `frontend-modern/src/components/Settings/SelfHostedCommercialRecoverySection.tsx`+50. `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`+51. `frontend-modern/src/components/Settings/RelayPairingSection.tsx`+52. `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`+53. `frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts`+54. `frontend-modern/src/components/Settings/useProLicensePanelState.ts`+55. `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`+56. `frontend-modern/src/pages/CloudPricing.tsx`+57. `frontend-modern/src/pages/HostedSignup.tsx`+58. `frontend-modern/src/pages/PricingHandoff.tsx`+59. `frontend-modern/src/utils/apiClient.ts`+60. `frontend-modern/src/utils/cloudPlans.ts`+61. `frontend-modern/src/utils/commercialBillingModel.ts`+62. `frontend-modern/src/utils/licensePresentation.ts`+63. `frontend-modern/src/utils/monitoredSystemPresentation.ts`+64. `frontend-modern/src/utils/pricingHandoff.ts`+65. `frontend-modern/src/utils/selfHostedPlans.ts`+66. `frontend-modern/src/utils/upgradePresentation.ts`+67. `frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts`+68. `pulse-pro:license-server/public_pricing.go`+69. `pulse-pro:license-server/v6_checkout.go`+70. `pulse-pro:landing-page/thanks.html`+71. `pulse-pro:scripts/grandfathered_recurring_cutover_preview.py`+72. `pulse-pro:scripts/validate_public_pricing_model.py`+73. `pulse-pro:V6_LAUNCH_CHECKLIST.md`+74. `pkg/licensing/trial_activation_public_key_override_dev.go`+75. `pkg/licensing/trial_activation_public_key_override_release.go`+76. `pkg/licensing/testing_helpers.go`## Shared Boundaries@@ -139,10 +144,10 @@ Community limit enforcement.1. Add or change limits through `pkg/licensing/`2. Add or change hosted entitlement issuance through `internal/cloudcp/entitlements/service.go`-3. Add or change control-plane plan storage through `internal/cloudcp/registry/registry.go`+3. Add or change control-plane plan storage through `internal/cloudcp/registry/models.go` and `internal/cloudcp/registry/registry.go`4. Add or change MSP account-scoped workspace provisioning entry handlers through `internal/cloudcp/account/tenant_handlers.go`5. Add or change public cloud self-serve signup price configuration or checkout gating through `internal/cloudcp/config.go` and `internal/cloudcp/public_cloud_signup_handlers.go`-6. Add or change the hosted account portal API, task-first browser shell, maintained portal frontend/bundle, or account-scoped workspace/access/billing handoff through `internal/cloudcp/portal/` and `internal/cloudcp/routes.go`+6. Add or change the hosted account portal API, Pulse Account access/auth/session handling, task-first browser shell, maintained portal frontend/bundle, or account-scoped workspace/access/billing handoff through `internal/cloudcp/account/audit.go`, `internal/cloudcp/account/handlers.go`, `internal/cloudcp/auth/handlers.go`, `internal/cloudcp/auth/session.go`, `internal/cloudcp/portal/`, and `internal/cloudcp/routes.go`That same customer-entry boundary owns the canonical hosted Cloud handoff:public Cloud entry, secure checkout return, and returning-customer sign-inmust converge on Pulse Account. Public Cloud signup stays canonical at@@ -1702,7 +1707,17 @@ That same task-first `Access` contractmust also start from bootstrap-owned roster truth: the first hosted rosterrender must come from the portal bootstrap payload itself, with later memberAPI reads reserved for refresh and mutation follow-through instead of-placeholder-first rendering. `Billing` follows+placeholder-first rendering. That same hosted access boundary also owns+invitation consent semantics: `internal/cloudcp/account/handlers.go` plus+`internal/cloudcp/registry/models.go` and `internal/cloudcp/registry/registry.go`+may persist pending invitation subjects for unknown emails, but they must not+auto-create users or memberships from invite input alone. Pending access rows+must remain explicit `pending` invitation subjects in the bootstrap roster and+member API until the invited email authenticates through the portal-owned+magic-link/session path in `internal/cloudcp/auth/handlers.go` and+`internal/cloudcp/auth/session.go`, and role or removal mutations on those+rows must target the invitation record rather than guessing a future user+identity. `Billing` followsthe same task-first rule: hosted billing leads when present, the self-hostedbilling, license, refund, and privacy paths reduce to explicit job pickers,and the active self-hosted billing panel must stay hidden until that exact jobdiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex bd7d30d72f..67af00dd05 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -1689,10 +1689,15 @@"frontend-modern/src/utils/selfHostedPlans.ts","frontend-modern/src/utils/upgradePresentation.ts","internal/api/public_signup_handlers.go",+ "internal/cloudcp/account/audit.go",+ "internal/cloudcp/account/handlers.go","internal/cloudcp/account/tenant_handlers.go",+ "internal/cloudcp/auth/handlers.go",+ "internal/cloudcp/auth/session.go","internal/cloudcp/config.go","internal/cloudcp/entitlements/service.go","internal/cloudcp/public_cloud_signup_handlers.go",+ "internal/cloudcp/registry/models.go","internal/cloudcp/registry/registry.go","internal/cloudcp/routes.go","internal/cloudcp/stripe/provisioner.go",@@ -1830,6 +1835,7 @@"label": "control-plane registry plan proof","match_prefixes": [],"match_files": [+ "internal/cloudcp/registry/models.go","internal/cloudcp/registry/registry.go"],"allow_same_subsystem_tests": false,@@ -1838,6 +1844,25 @@"internal/cloudcp/registry/registry_test.go"]},+ {+ "id": "pulse-account-access-and-auth",+ "label": "Pulse Account access and auth proof",+ "match_prefixes": [],+ "match_files": [+ "internal/cloudcp/account/audit.go",+ "internal/cloudcp/account/handlers.go",+ "internal/cloudcp/auth/handlers.go",+ "internal/cloudcp/auth/session.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/cloudcp/account/handlers_test.go",+ "internal/cloudcp/auth/handlers_magiclink_test.go",+ "internal/cloudcp/auth/handlers_test.go",+ "internal/cloudcp/portal/frontend/src/store.test.ts"+ ]+ },{"id": "msp-workspace-provisioning-handler","label": "MSP workspace provisioning handler proof",diff --git a/internal/cloudcp/account/handlers.go b/internal/cloudcp/account/handlers.goindex 7031c127f1..9eb01bd239 100644--- a/internal/cloudcp/account/handlers.go+++ b/internal/cloudcp/account/handlers.go@@ -12,11 +12,13 @@ import ("github.com/rs/zerolog/log")-type memberResponse struct {- UserID string `json:"user_id"`- Email string `json:"email"`- Role registry.MemberRole `json:"role"`- CreatedAt time.Time `json:"created_at"`+type accessSubjectResponse struct {+ SubjectID string `json:"subject_id"`+ UserID string `json:"user_id,omitempty"`+ Email string `json:"email"`+ Role registry.MemberRole `json:"role"`+ State registry.AccountAccessState `json:"state"`+ CreatedAt time.Time `json:"created_at"`}// HandleListMembers returns an authenticated handler that lists all members of an account.@@ -43,34 +45,12 @@ func HandleListMembers(reg *registry.TenantRegistry) http.HandlerFunc {return}- memberships, err := reg.ListMembersByAccount(accountID)+ actorRole, _ := requestActorRole(r)+ resp, err := accessSubjectsForActor(reg, accountID, actorRole)if err != nil {http.Error(w, "internal error", http.StatusInternalServerError)return}- if memberships == nil {- memberships = []*registry.AccountMembership{}- }-- resp := make([]memberResponse, 0, len(memberships))- for _, m := range memberships {- u, err := reg.GetUser(m.UserID)- if err != nil {- http.Error(w, "internal error", http.StatusInternalServerError)- return- }- if u == nil {- http.Error(w, "internal error", http.StatusInternalServerError)- return- }-- resp = append(resp, memberResponse{- UserID: m.UserID,- Email: u.Email,- Role: m.Role,- CreatedAt: m.CreatedAt,- })- }w.Header().Set("Content-Type", "application/json")encodeJSON(w, resp)@@ -82,6 +62,12 @@ type inviteMemberRequest struct {Role string `json:"role"`}+type inviteMemberResponse struct {+ SubjectID string `json:"subject_id"`+ UserID string `json:"user_id,omitempty"`+ State registry.AccountAccessState `json:"state"`+}+func requestActorRole(r *http.Request) (registry.MemberRole, bool) {if r == nil {return "", false@@ -97,6 +83,57 @@ func actorCanManageAccount(role registry.MemberRole) bool {return role == registry.MemberRoleOwner || role == registry.MemberRoleAdmin}+func accessSubjectsForActor(reg *registry.TenantRegistry, accountID string, actorRole registry.MemberRole) ([]accessSubjectResponse, error) {+ subjects, err := reg.ListAccessSubjectsByAccount(accountID)+ if err != nil {+ return nil, err+ }++ includePending := actorCanManageAccount(actorRole)+ resp := make([]accessSubjectResponse, 0, len(subjects))+ for _, subject := range subjects {+ if subject == nil {+ continue+ }+ if subject.State == registry.AccountAccessStatePending && !includePending {+ continue+ }+ resp = append(resp, accessSubjectResponse{+ SubjectID: subject.SubjectID,+ UserID: subject.UserID,+ Email: subject.Email,+ Role: subject.Role,+ State: subject.State,+ CreatedAt: subject.CreatedAt,+ })+ }+ return resp, nil+}++type accountAccessTarget struct {+ membership *registry.AccountMembership+ invitation *registry.AccountInvitation+}++func loadAccountAccessTarget(reg *registry.TenantRegistry, accountID string, subjectID string) (*accountAccessTarget, error) {+ membership, err := reg.GetMembership(accountID, subjectID)+ if err != nil {+ return nil, err+ }+ if membership != nil {+ return &accountAccessTarget{membership: membership}, nil+ }++ invitation, err := reg.GetInvitation(subjectID)+ if err != nil {+ return nil, err+ }+ if invitation != nil && invitation.AccountID == accountID {+ return &accountAccessTarget{invitation: invitation}, nil+ }+ return &accountAccessTarget{}, nil+}+// HandleInviteMember returns an authenticated handler that invites a user to an account.func HandleInviteMember(reg *registry.TenantRegistry) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {@@ -197,36 +234,51 @@ func HandleInviteMember(reg *registry.TenantRegistry) http.HandlerFunc {return}if u == nil {- userID, err := registry.GenerateUserID()- if err != nil {+ invitation := ®istry.AccountInvitation{+ AccountID: accountID,+ Email: email,+ Role: role,+ }+ if err := reg.UpsertInvitation(invitation); err != nil {auditEvent(r, "cp_account_member_invite", "failure").Err(err).Str("account_id", accountID).Str("email", email).- Str("reason", "user_id_generation_failed").+ Str("role", string(role)).+ Str("reason", "invitation_upsert_failed").Msg("Account member invite failed")http.Error(w, "internal error", http.StatusInternalServerError)return}- u = ®istry.User{- ID: userID,- Email: email,- }- if err := reg.CreateUser(u); err != nil {- // If a concurrent request created the user, fall back to lookup.- u2, gerr := reg.GetUserByEmail(email)- if gerr != nil || u2 == nil {- auditEvent(r, "cp_account_member_invite", "failure").- Err(err).- Str("account_id", accountID).- Str("email", email).- Str("reason", "user_create_failed").- Msg("Account member invite failed")- http.Error(w, "internal error", http.StatusInternalServerError)- return- }- u = u2++ storedInvitation, err := reg.GetInvitationByAccountAndEmail(accountID, email)+ if err != nil || storedInvitation == nil {+ auditEvent(r, "cp_account_member_invite", "failure").+ Err(err).+ Str("account_id", accountID).+ Str("email", email).+ Str("role", string(role)).+ Str("reason", "invitation_lookup_failed").+ Msg("Account member invite failed")+ http.Error(w, "internal error", http.StatusInternalServerError)+ return}++ auditEvent(r, "cp_account_member_invite", "success").+ Str("account_id", accountID).+ Str("subject_id", storedInvitation.ID).+ Str("email", email).+ Str("role", string(role)).+ Str("state", string(registry.AccountAccessStatePending)).+ Msg("Account invitation saved")++ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusAccepted)+ encodeJSON(w, inviteMemberResponse{+ SubjectID: storedInvitation.ID,+ State: registry.AccountAccessStatePending,+ })+ return}if err := reg.CreateMembership(®istry.AccountMembership{@@ -256,15 +308,33 @@ func HandleInviteMember(reg *registry.TenantRegistry) http.HandlerFunc {http.Error(w, "internal error", http.StatusInternalServerError)return}+ if err := reg.DeleteInvitationByAccountAndEmail(accountID, email); err != nil {+ auditEvent(r, "cp_account_member_invite", "failure").+ Err(err).+ Str("account_id", accountID).+ Str("user_id", u.ID).+ Str("email", email).+ Str("reason", "invitation_cleanup_failed").+ Msg("Account member invite failed")+ http.Error(w, "internal error", http.StatusInternalServerError)+ return+ }auditEvent(r, "cp_account_member_invite", "success").Str("account_id", accountID).- Str("user_id", u.ID).+ Str("subject_id", u.ID).Str("email", email).Str("role", string(role)).+ Str("state", string(registry.AccountAccessStateActive)).Msg("Account member invited")+ w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusCreated)+ encodeJSON(w, inviteMemberResponse{+ SubjectID: u.ID,+ UserID: u.ID,+ State: registry.AccountAccessStateActive,+ })}}@@ -343,33 +413,43 @@ func HandleUpdateMemberRole(reg *registry.TenantRegistry) http.HandlerFunc {return}- existing, err := reg.GetMembership(accountID, userID)+ target, err := loadAccountAccessTarget(reg, accountID, userID)if err != nil {auditEvent(r, "cp_account_member_role_update", "failure").Err(err).Str("account_id", accountID).Str("user_id", userID).- Str("reason", "membership_lookup_failed").+ Str("reason", "access_target_lookup_failed").Msg("Account member role update failed")http.Error(w, "internal error", http.StatusInternalServerError)return}- if existing == nil {++ currentRole := registry.MemberRole("")+ currentState := registry.AccountAccessStateActive+ switch {+ case target.membership != nil:+ currentRole = target.membership.Role+ currentState = registry.AccountAccessStateActive+ case target.invitation != nil:+ currentRole = target.invitation.Role+ currentState = registry.AccountAccessStatePending+ default:auditEvent(r, "cp_account_member_role_update", "failure").Str("account_id", accountID).Str("user_id", userID).- Str("reason", "membership_not_found").+ Str("reason", "access_target_not_found").Msg("Account member role update failed")- http.Error(w, "membership not found", http.StatusNotFound)+ http.Error(w, "access subject not found", http.StatusNotFound)return}- if (role == registry.MemberRoleOwner || existing.Role == registry.MemberRoleOwner) && actorRole != registry.MemberRoleOwner {+ if (role == registry.MemberRoleOwner || currentRole == registry.MemberRoleOwner) && actorRole != registry.MemberRoleOwner {auditEvent(r, "cp_account_member_role_update", "failure").Str("account_id", accountID).Str("user_id", userID).Str("actor_role", string(actorRole)).- Str("target_current_role", string(existing.Role)).+ Str("target_current_role", string(currentRole)).Str("target_new_role", string(role)).Str("reason", "owner_role_change_requires_owner_actor").Msg("Account member role update failed")@@ -377,7 +457,7 @@ func HandleUpdateMemberRole(reg *registry.TenantRegistry) http.HandlerFunc {return}- if existing.Role == registry.MemberRoleOwner && role != registry.MemberRoleOwner {+ if target.membership != nil && currentRole == registry.MemberRoleOwner && role != registry.MemberRoleOwner {memberships, listErr := reg.ListMembersByAccount(accountID)if listErr != nil {auditEvent(r, "cp_account_member_role_update", "failure").@@ -407,31 +487,54 @@ func HandleUpdateMemberRole(reg *registry.TenantRegistry) http.HandlerFunc {}}- if err := reg.UpdateMembershipRole(accountID, userID, role); err != nil {- if isNotFoundErr(err) {+ if target.membership != nil {+ if err := reg.UpdateMembershipRole(accountID, userID, role); err != nil {+ if isNotFoundErr(err) {+ auditEvent(r, "cp_account_member_role_update", "failure").+ Err(err).+ Str("account_id", accountID).+ Str("user_id", userID).+ Str("reason", "membership_not_found").+ Msg("Account member role update failed")+ http.Error(w, "membership not found", http.StatusNotFound)+ return+ }auditEvent(r, "cp_account_member_role_update", "failure").Err(err).Str("account_id", accountID).Str("user_id", userID).- Str("reason", "membership_not_found").+ Str("reason", "membership_update_failed").Msg("Account member role update failed")- http.Error(w, "membership not found", http.StatusNotFound)+ http.Error(w, "internal error", http.StatusInternalServerError)+ return+ }+ } else {+ if err := reg.UpdateInvitationRole(userID, role, ""); err != nil {+ if isNotFoundErr(err) {+ auditEvent(r, "cp_account_member_role_update", "failure").+ Err(err).+ Str("account_id", accountID).+ Str("user_id", userID).+ Str("reason", "invitation_not_found").+ Msg("Account member role update failed")+ http.Error(w, "invitation not found", http.StatusNotFound)+ return+ }+ auditEvent(r, "cp_account_member_role_update", "failure").+ Str("account_id", accountID).+ Str("user_id", userID).+ Str("reason", "invitation_update_failed").+ Msg("Account member role update failed")+ http.Error(w, "internal error", http.StatusInternalServerError)return}- auditEvent(r, "cp_account_member_role_update", "failure").- Err(err).- Str("account_id", accountID).- Str("user_id", userID).- Str("reason", "membership_update_failed").- Msg("Account member role update failed")- http.Error(w, "internal error", http.StatusInternalServerError)- return}auditEvent(r, "cp_account_member_role_update", "success").Str("account_id", accountID).Str("user_id", userID).- Str("old_role", string(existing.Role)).+ Str("state", string(currentState)).+ Str("old_role", string(currentRole)).Str("new_role", string(role)).Msg("Account member role updated")@@ -489,93 +592,128 @@ func HandleRemoveMember(reg *registry.TenantRegistry) http.HandlerFunc {return}- m, err := reg.GetMembership(accountID, userID)+ target, err := loadAccountAccessTarget(reg, accountID, userID)if err != nil {auditEvent(r, "cp_account_member_remove", "failure").Err(err).Str("account_id", accountID).Str("user_id", userID).- Str("reason", "membership_lookup_failed").+ Str("reason", "access_target_lookup_failed").Msg("Account member removal failed")http.Error(w, "internal error", http.StatusInternalServerError)return}- if m == nil {++ currentRole := registry.MemberRole("")+ currentState := registry.AccountAccessStateActive+ switch {+ case target.membership != nil:+ currentRole = target.membership.Role+ currentState = registry.AccountAccessStateActive+ case target.invitation != nil:+ currentRole = target.invitation.Role+ currentState = registry.AccountAccessStatePending+ default:auditEvent(r, "cp_account_member_remove", "failure").Str("account_id", accountID).Str("user_id", userID).- Str("reason", "membership_not_found").+ Str("reason", "access_target_not_found").Msg("Account member removal failed")- http.Error(w, "membership not found", http.StatusNotFound)+ http.Error(w, "access subject not found", http.StatusNotFound)return}- if m.Role == registry.MemberRoleOwner {+ if currentRole == registry.MemberRoleOwner {if actorRole != registry.MemberRoleOwner {auditEvent(r, "cp_account_member_remove", "failure").Str("account_id", accountID).Str("user_id", userID).Str("actor_role", string(actorRole)).- Str("target_role", string(m.Role)).+ Str("target_role", string(currentRole)).Str("reason", "owner_removal_requires_owner_actor").Msg("Account member removal failed")http.Error(w, "forbidden", http.StatusForbidden)return}- memberships, err := reg.ListMembersByAccount(accountID)- if err != nil {+ if target.membership != nil {+ memberships, err := reg.ListMembersByAccount(accountID)+ if err != nil {+ auditEvent(r, "cp_account_member_remove", "failure").+ Err(err).+ Str("account_id", accountID).+ Str("user_id", userID).+ Str("reason", "membership_list_failed").+ Msg("Account member removal failed")+ http.Error(w, "internal error", http.StatusInternalServerError)+ return+ }+ owners := 0+ for _, mm := range memberships {+ if mm.Role == registry.MemberRoleOwner {+ owners+++ }+ }+ if owners <= 1 {+ auditEvent(r, "cp_account_member_remove", "failure").+ Str("account_id", accountID).+ Str("user_id", userID).+ Str("reason", "cannot_remove_last_owner").+ Msg("Account member removal denied")+ http.Error(w, "cannot remove last owner", http.StatusConflict)+ return+ }+ }+ }++ if target.membership != nil {+ if err := reg.DeleteMembership(accountID, userID); err != nil {+ if isNotFoundErr(err) {+ auditEvent(r, "cp_account_member_remove", "failure").+ Err(err).+ Str("account_id", accountID).+ Str("user_id", userID).+ Str("reason", "membership_not_found").+ Msg("Account member removal failed")+ http.Error(w, "membership not found", http.StatusNotFound)+ return+ }auditEvent(r, "cp_account_member_remove", "failure").Err(err).Str("account_id", accountID).Str("user_id", userID).- Str("reason", "membership_list_failed").+ Str("reason", "membership_delete_failed").Msg("Account member removal failed")http.Error(w, "internal error", http.StatusInternalServerError)return}- owners := 0- for _, mm := range memberships {- if mm.Role == registry.MemberRoleOwner {- owners+++ } else {+ if err := reg.DeleteInvitation(userID); err != nil {+ if isNotFoundErr(err) {+ auditEvent(r, "cp_account_member_remove", "failure").+ Err(err).+ Str("account_id", accountID).+ Str("user_id", userID).+ Str("reason", "invitation_not_found").+ Msg("Account member removal failed")+ http.Error(w, "invitation not found", http.StatusNotFound)+ return}- }- if owners <= 1 {auditEvent(r, "cp_account_member_remove", "failure").Str("account_id", accountID).Str("user_id", userID).- Str("reason", "cannot_remove_last_owner").- Msg("Account member removal denied")- http.Error(w, "cannot remove last owner", http.StatusConflict)- return- }- }-- if err := reg.DeleteMembership(accountID, userID); err != nil {- if isNotFoundErr(err) {- auditEvent(r, "cp_account_member_remove", "failure").- Err(err).- Str("account_id", accountID).- Str("user_id", userID).- Str("reason", "membership_not_found").+ Str("reason", "invitation_delete_failed").Msg("Account member removal failed")- http.Error(w, "membership not found", http.StatusNotFound)+ http.Error(w, "internal error", http.StatusInternalServerError)return}- auditEvent(r, "cp_account_member_remove", "failure").- Err(err).- Str("account_id", accountID).- Str("user_id", userID).- Str("reason", "membership_delete_failed").- Msg("Account member removal failed")- http.Error(w, "internal error", http.StatusInternalServerError)- return}auditEvent(r, "cp_account_member_remove", "success").Str("account_id", accountID).Str("user_id", userID).- Str("removed_role", string(m.Role)).+ Str("state", string(currentState)).+ Str("removed_role", string(currentRole)).Msg("Account member removed")w.WriteHeader(http.StatusNoContent)diff --git a/internal/cloudcp/account/handlers_test.go b/internal/cloudcp/account/handlers_test.goindex 903f80260b..8e093eb3b7 100644--- a/internal/cloudcp/account/handlers_test.go+++ b/internal/cloudcp/account/handlers_test.go@@ -88,27 +88,76 @@ func TestInviteMember(t *testing.T) {req := httptest.NewRequest(http.MethodPost, "/api/accounts/"+accountID+"/members", bytes.NewBufferString(body))rec := doRequest(t, mux, req)- if rec.Code != http.StatusCreated {- t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusCreated, rec.Body.String())+ if rec.Code != http.StatusAccepted {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusAccepted, rec.Body.String())}u, err := reg.GetUserByEmail("[email protected]")if err != nil {t.Fatal(err)}- if u == nil {- t.Fatal("expected user to be created")+ if u != nil {+ t.Fatalf("expected invitation-only flow without user creation, got %+v", u)}- m, err := reg.GetMembership(accountID, u.ID)+ invitation, err := reg.GetInvitationByAccountAndEmail(accountID, "[email protected]")if err != nil {t.Fatal(err)}- if m == nil {- t.Fatal("expected membership to be created")+ if invitation == nil {+ t.Fatal("expected pending invitation to be stored")}- if m.Role != registry.MemberRoleTech {- t.Fatalf("role = %q, want %q", m.Role, registry.MemberRoleTech)+ if invitation.Role != registry.MemberRoleTech {+ t.Fatalf("role = %q, want %q", invitation.Role, registry.MemberRoleTech)+ }+}++func TestInviteMember_ListMembersIncludesPendingInvitationForManagers(t *testing.T) {+ reg := newTestRegistry(t)+ handler := HandleListMembers(reg)++ accountID, err := registry.GenerateAccountID()+ if err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateAccount(®istry.Account{ID: accountID, Kind: registry.AccountKindMSP, DisplayName: "Test"}); err != nil {+ t.Fatal(err)+ }+ if err := reg.UpsertInvitation(®istry.AccountInvitation{+ AccountID: accountID,+ Email: "[email protected]",+ Role: registry.MemberRoleAdmin,+ }); err != nil {+ t.Fatal(err)+ }++ req := httptest.NewRequest(http.MethodGet, "/api/accounts/"+accountID+"/members", nil)+ req.SetPathValue("account_id", accountID)+ req.Header.Set("X-User-Role", string(registry.MemberRoleOwner))+ rec := doRawRequest(t, http.HandlerFunc(handler), req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusOK, rec.Body.String())+ }++ var subjects []struct {+ SubjectID string `json:"subject_id"`+ State string `json:"state"`+ Email string `json:"email"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &subjects); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(subjects) != 1 {+ t.Fatalf("subjects = %+v, want single pending invitation", subjects)+ }+ if subjects[0].State != string(registry.AccountAccessStatePending) {+ t.Fatalf("state = %q, want %q", subjects[0].State, registry.AccountAccessStatePending)+ }+ if subjects[0].Email != "[email protected]" {+ t.Fatalf("email = %q, want %q", subjects[0].Email, "[email protected]")+ }+ if subjects[0].SubjectID == "" {+ t.Fatal("expected subject_id for pending invitation")}}@@ -351,7 +400,7 @@ func TestCannotRemoveLastOwner(t *testing.T) {func TestUpdateMemberRole_AdminCannotDemoteOwner(t *testing.T) {reg := newTestRegistry(t)- mux := newTestMux(reg)+ handler := HandleUpdateMemberRole(reg)accountID, err := registry.GenerateAccountID()if err != nil {@@ -384,8 +433,10 @@ func TestUpdateMemberRole_AdminCannotDemoteOwner(t *testing.T) {body := `{"role":"tech"}`req := httptest.NewRequest(http.MethodPatch, "/api/accounts/"+accountID+"/members/"+ownerID, bytes.NewBufferString(body))+ req.SetPathValue("account_id", accountID)+ req.SetPathValue("user_id", ownerID)req.Header.Set("X-User-Role", string(registry.MemberRoleAdmin))- rec := doRequest(t, mux, req)+ rec := doRawRequest(t, http.HandlerFunc(handler), req)if rec.Code != http.StatusForbidden {t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusForbidden, rec.Body.String())@@ -443,7 +494,7 @@ func TestUpdateMemberRole_CannotDemoteLastOwner(t *testing.T) {func TestRemoveMember_AdminCannotRemoveOwner(t *testing.T) {reg := newTestRegistry(t)- mux := newTestMux(reg)+ handler := HandleRemoveMember(reg)accountID, err := registry.GenerateAccountID()if err != nil {@@ -475,8 +526,10 @@ func TestRemoveMember_AdminCannotRemoveOwner(t *testing.T) {}req := httptest.NewRequest(http.MethodDelete, "/api/accounts/"+accountID+"/members/"+ownerID, nil)+ req.SetPathValue("account_id", accountID)+ req.SetPathValue("user_id", ownerID)req.Header.Set("X-User-Role", string(registry.MemberRoleAdmin))- rec := doRequest(t, mux, req)+ rec := doRawRequest(t, http.HandlerFunc(handler), req)if rec.Code != http.StatusForbidden {t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusForbidden, rec.Body.String())diff --git a/internal/cloudcp/auth/handlers.go b/internal/cloudcp/auth/handlers.goindex 5b76561543..b33ad10c9c 100644--- a/internal/cloudcp/auth/handlers.go+++ b/internal/cloudcp/auth/handlers.go@@ -448,6 +448,9 @@ func ensurePortalUser(reg *registry.TenantRegistry, email string) (string, errorif user == nil || strings.TrimSpace(user.ID) == "" {return "", fmt.Errorf("user resolution failed")}+ if err := reg.AcceptInvitationsForUser(email, user.ID); err != nil {+ return "", fmt.Errorf("accept account invitations: %w", err)+ }_ = reg.UpdateUserLastLogin(user.ID)return user.ID, nil}diff --git a/internal/cloudcp/auth/handlers_magiclink_test.go b/internal/cloudcp/auth/handlers_magiclink_test.goindex ba90c8044b..c3a06c17da 100644--- a/internal/cloudcp/auth/handlers_magiclink_test.go+++ b/internal/cloudcp/auth/handlers_magiclink_test.go@@ -64,6 +64,79 @@ func TestHandleMagicLinkVerifyPortalTargetCreatesPortalSession(t *testing.T) {}}+func TestHandleMagicLinkVerifyPortalTargetAcceptsPendingAccountInvitations(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(®istry.Account{+ ID: accountID,+ Kind: registry.AccountKindMSP,+ DisplayName: "Invited Account",+ }); err != nil {+ t.Fatalf("CreateAccount: %v", err)+ }+ if err := reg.UpsertInvitation(®istry.AccountInvitation{+ AccountID: accountID,+ Email: "[email protected]",+ Role: registry.MemberRoleTech,+ }); err != nil {+ t.Fatalf("UpsertInvitation: %v", err)+ }++ 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", "/portal")(rec, req)++ if rec.Code != http.StatusTemporaryRedirect {+ t.Fatalf("status=%d body=%q", rec.Code, rec.Body.String())+ }++ 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")+ }+ membership, err := reg.GetMembership(accountID, user.ID)+ if err != nil {+ t.Fatalf("GetMembership: %v", err)+ }+ if membership == nil {+ t.Fatal("expected pending invitation to become membership")+ }+ if membership.Role != registry.MemberRoleTech {+ t.Fatalf("membership.Role = %q, want %q", membership.Role, registry.MemberRoleTech)+ }+ invitation, err := reg.GetInvitationByAccountAndEmail(accountID, "[email protected]")+ if err != nil {+ t.Fatalf("GetInvitationByAccountAndEmail: %v", err)+ }+ if invitation != nil {+ t.Fatalf("expected accepted invitation to be removed, got %+v", invitation)+ }+}+func TestHandleMagicLinkVerifyTenantTargetStillRedirectsToTenantHandoff(t *testing.T) {dir := t.TempDir()reg, err := registry.NewTenantRegistry(dir)diff --git a/internal/cloudcp/portal/bootstrap.go b/internal/cloudcp/portal/bootstrap.goindex fb8124a028..67da9235f2 100644--- a/internal/cloudcp/portal/bootstrap.go+++ b/internal/cloudcp/portal/bootstrap.go@@ -17,9 +17,11 @@ type BootstrapWorkspace struct {}type BootstrapMember struct {- UserID string `json:"user_id"`+ SubjectID string `json:"subject_id"`+ UserID string `json:"user_id,omitempty"`Email string `json:"email"`Role string `json:"role"`+ State string `json:"state"`CreatedAt string `json:"created_at,omitempty"`}@@ -87,9 +89,11 @@ func BuildBootstrapDataWithSignupPath(authenticated bool, email string, accountscreatedAt = member.CreatedAt.UTC().Format(time.RFC3339)}members = append(members, BootstrapMember{+ SubjectID: member.SubjectID,UserID: member.UserID,Email: member.Email,Role: string(member.Role),+ State: string(member.State),CreatedAt: createdAt,})}diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.jsonindex 8115254237..10661025bb 100644--- a/internal/cloudcp/portal/dist/build_manifest.json+++ b/internal/cloudcp/portal/dist/build_manifest.json@@ -1,5 +1,5 @@{- "source_hash": "de861ffaf5a9cea5ea57c6314ce7615a991b5c302d717438758b702668c01828",+ "source_hash": "c5558e1c54558cd9722d83db8479de508085548b0cd6a6658b8eafb99805a14c","build_inputs": ["package.json","tsconfig.json",diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.jsindex aaaecb7ca9..8223702068 100644--- a/internal/cloudcp/portal/dist/portal_app.js+++ b/internal/cloudcp/portal/dist/portal_app.js@@ -204,10 +204,18 @@function countMembersByRole(members, role) {var count = 0;for (var i = 0; i < members.length; i += 1) {+ if ((members[i].state || "active") !== "active") continue;if (normalizePortalRole(members[i].role) === role) count += 1;}return count;}+ function countPendingMembers(members) {+ var count = 0;+ for (var i = 0; i < members.length; i += 1) {+ if ((members[i].state || "active") === "pending") count += 1;+ }+ return count;+ }function renderAccessStatsSummary(summary, isError) {return '<div class="access-stat-summary' + (isError ? " access-stat-summary-error" : "") + '">' + summary + "</div>";}@@ -252,7 +260,7 @@}var members = entry.accessQuery.data;stats.innerHTML = renderAccessStatsSummary(- "Members " + String(members.length) + " \u2022 Owners " + String(countMembersByRole(members, "owner")) + " \u2022 Admins " + String(countMembersByRole(members, "admin")) + " \u2022 Operators " + String(countMembersByRole(members, "tech") + countMembersByRole(members, "read_only")),+ "Members " + String(members.length - countPendingMembers(members)) + " \u2022 Pending " + String(countPendingMembers(members)) + " \u2022 Owners " + String(countMembersByRole(members, "owner")) + " \u2022 Admins " + String(countMembersByRole(members, "admin")) + " \u2022 Operators " + String(countMembersByRole(members, "tech") + countMembersByRole(members, "read_only")),false);}@@ -263,6 +271,7 @@}function renderAccessRoleControl(accountID, member, isOwner, canManage, activeJob) {var currentRole = normalizePortalRole(member.role);+ var subjectID = member.subject_id || member.user_id || "";var group = createAccessControlCell("access-control-cell-role");if (!canManage || activeJob !== "change_role") {var badge = document.createElement("span");@@ -290,11 +299,12 @@}sel.setAttribute("data-action", "change-role");sel.setAttribute("data-account-id", accountID);- sel.setAttribute("data-user-id", member.user_id);+ sel.setAttribute("data-user-id", subjectID);group.appendChild(sel);return group;}function renderAccessMemberAction(accountID, member, isOwner, canManage, activeJob) {+ var subjectID = member.subject_id || member.user_id || "";if (!canManage || activeJob !== "remove") {return null;}@@ -312,7 +322,7 @@btn.textContent = "Remove access";btn.setAttribute("data-action", "remove-member");btn.setAttribute("data-account-id", accountID);- btn.setAttribute("data-user-id", member.user_id);+ btn.setAttribute("data-user-id", subjectID);btn.setAttribute("data-member-email", member.email);group.appendChild(btn);return group;@@ -333,10 +343,16 @@roleBadge.className = "access-inline-role-badge";roleBadge.textContent = portalRoleLabel(member.role);topline.appendChild(roleBadge);+ if ((member.state || "active") === "pending") {+ var pendingBadge = document.createElement("span");+ pendingBadge.className = "access-inline-role-badge";+ pendingBadge.textContent = "Pending";+ topline.appendChild(pendingBadge);+ }identity.appendChild(topline);var caption = document.createElement("div");caption.className = "access-member-caption";- caption.textContent = portalRoleCapabilityCopy(member.role);+ caption.textContent = (member.state || "active") === "pending" ? "Invitation pending acceptance." : portalRoleCapabilityCopy(member.role);identity.appendChild(caption);row.appendChild(identity);row.appendChild(renderAccessRoleControl(accountID, member, isOwner, canManage, activeJob));@@ -807,9 +823,11 @@var cloned = [];for (var i = 0; i < members.length; i += 1) {cloned.push({+ subject_id: members[i].subject_id,email: members[i].email,role: members[i].role,user_id: members[i].user_id,+ state: members[i].state,created_at: members[i].created_at});}@@ -1174,12 +1192,12 @@return;}try {- await deps.api.inviteMember(accountID, { email, role: roleEl.value });+ var result = await deps.api.inviteMember(accountID, { email, role: roleEl.value });emailEl.value = "";if (!await refreshAccountAccessSection(accountID)) {return;}- deps.showToast("Member invited!");+ deps.showToast(result && result.state === "active" ? "Member added." : "Invitation saved.");} catch (error) {if (error instanceof PortalAPIError && error.status === 409) {deps.showToast("Member already exists.", true);@@ -2932,7 +2950,9 @@function normalizeMembers(members) {return members.map(function(member) {return {- ...member+ ...member,+ subject_id: member.subject_id || member.user_id || "",+ state: member.state || "active"};});}diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.ts b/internal/cloudcp/portal/frontend/src/account_runtime.tsindex 38db6175fd..353f272f42 100644--- a/internal/cloudcp/portal/frontend/src/account_runtime.ts+++ b/internal/cloudcp/portal/frontend/src/account_runtime.ts@@ -294,12 +294,12 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntimereturn;}try {- await deps.api.inviteMember(accountID, { email: email, role: roleEl.value });+ var result = await deps.api.inviteMember(accountID, { email: email, role: roleEl.value });emailEl.value = '';if (!await refreshAccountAccessSection(accountID)) {return;}- deps.showToast('Member invited!');+ deps.showToast(result && result.state === 'active' ? 'Member added.' : 'Invitation saved.');} catch (error) {if (error instanceof PortalAPIError && error.status === 409) {deps.showToast('Member already exists.', true);diff --git a/internal/cloudcp/portal/frontend/src/account_view.ts b/internal/cloudcp/portal/frontend/src/account_view.tsindex a8e88cbdb4..25295e4fe8 100644--- a/internal/cloudcp/portal/frontend/src/account_view.ts+++ b/internal/cloudcp/portal/frontend/src/account_view.ts@@ -138,11 +138,20 @@ function setContainerMessage(container: HTMLElement, title: string, msg: string,function countMembersByRole(members: PortalAccessMember[], role: string): number {var count = 0;for (var i = 0; i < members.length; i += 1) {+ if ((members[i].state || 'active') !== 'active') continue;if (normalizePortalRole(members[i].role) === role) count += 1;}return count;}+function countPendingMembers(members: PortalAccessMember[]): number {+ var count = 0;+ for (var i = 0; i < members.length; i += 1) {+ if ((members[i].state || 'active') === 'pending') count += 1;+ }+ return count;+}+function renderAccessStatsSummary(summary: string, isError: boolean): string {return '<div class="access-stat-summary' + (isError ? ' access-stat-summary-error' : '') + '">' + summary + '</div>';}@@ -191,7 +200,8 @@ function renderAccessStats(accountID: string, entry: PortalAccountUIEntry, canMavar members = entry.accessQuery.data;stats.innerHTML = renderAccessStatsSummary(- 'Members ' + String(members.length) + ' • ' ++ 'Members ' + String(members.length - countPendingMembers(members)) + ' • ' ++ 'Pending ' + String(countPendingMembers(members)) + ' • ' +'Owners ' + String(countMembersByRole(members, 'owner')) + ' • ' +'Admins ' + String(countMembersByRole(members, 'admin')) + ' • ' +'Operators ' + String(countMembersByRole(members, 'tech') + countMembersByRole(members, 'read_only')),@@ -207,6 +217,7 @@ function createAccessControlCell(className: string): HTMLDivElement {function renderAccessRoleControl(accountID: string, member: PortalAccessMember, isOwner: boolean, canManage: boolean, activeJob: PortalAccessJob): HTMLElement {var currentRole = normalizePortalRole(member.role);+ var subjectID = member.subject_id || member.user_id || '';var group = createAccessControlCell('access-control-cell-role');if (!canManage || activeJob !== 'change_role') {var badge = document.createElement('span');@@ -235,12 +246,13 @@ function renderAccessRoleControl(accountID: string, member: PortalAccessMember,}sel.setAttribute('data-action', 'change-role');sel.setAttribute('data-account-id', accountID);- sel.setAttribute('data-user-id', member.user_id);+ sel.setAttribute('data-user-id', subjectID);group.appendChild(sel);return group;}function renderAccessMemberAction(accountID: string, member: PortalAccessMember, isOwner: boolean, canManage: boolean, activeJob: PortalAccessJob): HTMLElement | null {+ var subjectID = member.subject_id || member.user_id || '';if (!canManage || activeJob !== 'remove') {return null;}@@ -259,7 +271,7 @@ function renderAccessMemberAction(accountID: string, member: PortalAccessMember,btn.textContent = 'Remove access';btn.setAttribute('data-action', 'remove-member');btn.setAttribute('data-account-id', accountID);- btn.setAttribute('data-user-id', member.user_id);+ btn.setAttribute('data-user-id', subjectID);btn.setAttribute('data-member-email', member.email);group.appendChild(btn);return group;@@ -286,11 +298,20 @@ function renderAccessMemberRow(accountID: string, member: PortalAccessMember, isroleBadge.textContent = portalRoleLabel(member.role);topline.appendChild(roleBadge);+ if ((member.state || 'active') === 'pending') {+ var pendingBadge = document.createElement('span');+ pendingBadge.className = 'access-inline-role-badge';+ pendingBadge.textContent = 'Pending';+ topline.appendChild(pendingBadge);+ }+identity.appendChild(topline);var caption = document.createElement('div');caption.className = 'access-member-caption';- caption.textContent = portalRoleCapabilityCopy(member.role);+ caption.textContent = (member.state || 'active') === 'pending'+ ? 'Invitation pending acceptance.'+ : portalRoleCapabilityCopy(member.role);identity.appendChild(caption);row.appendChild(identity);diff --git a/internal/cloudcp/portal/frontend/src/api.ts b/internal/cloudcp/portal/frontend/src/api.tsindex 3357ade022..5393c4da1c 100644--- a/internal/cloudcp/portal/frontend/src/api.ts+++ b/internal/cloudcp/portal/frontend/src/api.ts@@ -33,6 +33,12 @@ export interface PortalMemberInviteRequest {role: string;}+export interface PortalMemberInviteResponse {+ subject_id?: string;+ user_id?: string;+ state?: 'active' | 'pending';+}+export interface PortalMemberRoleRequest {role: string;}@@ -48,7 +54,7 @@ export interface PortalAPI {deleteWorkspace(accountID: string, tenantID: string): Promise<void>;openBilling(accountID: string): Promise<PortalBillingResponse>;listMembers(accountID: string): Promise<PortalAccessMember[]>;- inviteMember(accountID: string, body: PortalMemberInviteRequest): Promise<void>;+ inviteMember(accountID: string, body: PortalMemberInviteRequest): Promise<PortalMemberInviteResponse>;updateMemberRole(accountID: string, userID: string, body: PortalMemberRoleRequest): Promise<void>;removeMember(accountID: string, userID: string): Promise<void>;}@@ -181,7 +187,7 @@ export function createPortalAPI(context: PortalAPIContext): PortalAPI {return request<PortalAccessMember[]>(accountURL(accountID, '/members'), {}, 'Failed to load access roster.');},inviteMember: function(accountID: string, body: PortalMemberInviteRequest) {- return request<void>(accountURL(accountID, '/members'), {+ return request<PortalMemberInviteResponse>(accountURL(accountID, '/members'), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),diff --git a/internal/cloudcp/portal/frontend/src/state.ts b/internal/cloudcp/portal/frontend/src/state.tsindex ef746e5cdd..a570a2a2f3 100644--- a/internal/cloudcp/portal/frontend/src/state.ts+++ b/internal/cloudcp/portal/frontend/src/state.ts@@ -95,9 +95,11 @@ function clonePortalAccessMembers(members: PortalAccessMember[]): PortalAccessMevar cloned = [] as PortalAccessMember[];for (var i = 0; i < members.length; i += 1) {cloned.push({+ subject_id: members[i].subject_id,email: members[i].email,role: members[i].role,user_id: members[i].user_id,+ state: members[i].state,created_at: members[i].created_at,});}diff --git a/internal/cloudcp/portal/frontend/src/store.test.ts b/internal/cloudcp/portal/frontend/src/store.test.tsindex 50361b9454..0c508f6fbb 100644--- a/internal/cloudcp/portal/frontend/src/store.test.ts+++ b/internal/cloudcp/portal/frontend/src/store.test.ts@@ -124,7 +124,7 @@ describe('portal store', function() {can_manage: true,has_billing: true,members: [- { email: '[email protected]', role: 'owner', user_id: 'u_1', created_at: '2026-03-28T10:00:00Z' },+ { subject_id: 'u_1', email: '[email protected]', role: 'owner', user_id: 'u_1', state: 'active', created_at: '2026-03-28T10:00:00Z' },],workspaces: [],},@@ -135,7 +135,7 @@ describe('portal store', function() {expect(entry.accessQuery.status).toBe('ready');expect(entry.accessQuery.error).toBe('');expect(entry.accessQuery.data).toEqual([- { email: '[email protected]', role: 'owner', user_id: 'u_1', created_at: '2026-03-28T10:00:00Z' },+ { subject_id: 'u_1', email: '[email protected]', role: 'owner', user_id: 'u_1', state: 'active', created_at: '2026-03-28T10:00:00Z' },]);store.setBootstrap({@@ -151,7 +151,7 @@ describe('portal store', function() {can_manage: true,has_billing: true,members: [- { email: '[email protected]', role: 'admin', user_id: 'u_2', created_at: '2026-03-28T11:00:00Z' },+ { subject_id: 'u_2', email: '[email protected]', role: 'admin', user_id: 'u_2', state: 'active', created_at: '2026-03-28T11:00:00Z' },],workspaces: [],},@@ -159,7 +159,7 @@ describe('portal store', function() {});expect(store.getAccountState().byAccountID.acct_1.accessQuery.data).toEqual([- { email: '[email protected]', role: 'admin', user_id: 'u_2', created_at: '2026-03-28T11:00:00Z' },+ { subject_id: 'u_2', email: '[email protected]', role: 'admin', user_id: 'u_2', state: 'active', created_at: '2026-03-28T11:00:00Z' },]);});diff --git a/internal/cloudcp/portal/frontend/src/store.ts b/internal/cloudcp/portal/frontend/src/store.tsindex 941da8c2fb..1d2fcf784e 100644--- a/internal/cloudcp/portal/frontend/src/store.ts+++ b/internal/cloudcp/portal/frontend/src/store.ts@@ -193,6 +193,8 @@ function normalizeMembers(members: PortalAccessMember[]): PortalAccessMember[] {return members.map(function(member) {return {...(member as PortalAccessMember),+ subject_id: member.subject_id || member.user_id || '',+ state: member.state || 'active',};});}diff --git a/internal/cloudcp/portal/frontend/src/types.ts b/internal/cloudcp/portal/frontend/src/types.tsindex 37c1fb24f9..6864efe71c 100644--- a/internal/cloudcp/portal/frontend/src/types.ts+++ b/internal/cloudcp/portal/frontend/src/types.ts@@ -9,9 +9,11 @@ export interface PortalWorkspaceSummary {}export interface PortalAccessMember {+ subject_id?: string;email: string;role: string;- user_id: string;+ user_id?: string;+ state?: 'active' | 'pending';created_at?: string;}diff --git a/internal/cloudcp/portal/page.go b/internal/cloudcp/portal/page.goindex 443f75059b..e546bb6a49 100644--- a/internal/cloudcp/portal/page.go+++ b/internal/cloudcp/portal/page.go@@ -24,9 +24,11 @@ type portalPageWorkspace struct {}type portalPageMember struct {+ SubjectID stringUserID stringEmail stringRole registry.MemberRole+ State registry.AccountAccessStateCreatedAt time.Time}@@ -156,7 +158,7 @@ func loadPortalAccountsForUser(reg *registry.TenantRegistry, userID string) ([]plog.Error().Err(err).Str("account_id", accountID).Msg("cloudcp.portal.page: list tenants")continue}- members, err := loadPortalAccountMembers(reg, accountID)+ members, err := loadPortalAccountMembers(reg, accountID, m.Role)if err != nil {log.Error().Err(err).Str("account_id", accountID).Msg("cloudcp.portal.page: list members")continue@@ -209,32 +211,31 @@ func loadPortalAccountsForUser(reg *registry.TenantRegistry, userID string) ([]preturn accounts, nil}-func loadPortalAccountMembers(reg *registry.TenantRegistry, accountID string) ([]portalPageMember, error) {- memberships, err := reg.ListMembersByAccount(accountID)+func loadPortalAccountMembers(reg *registry.TenantRegistry, accountID string, actorRole registry.MemberRole) ([]portalPageMember, error) {+ subjects, err := reg.ListAccessSubjectsByAccount(accountID)if err != nil {return nil, err}- if memberships == nil {+ if subjects == nil {return []portalPageMember{}, nil}- members := make([]portalPageMember, 0, len(memberships))- for _, membership := range memberships {- if membership == nil {+ canManage := actorRole == registry.MemberRoleOwner || actorRole == registry.MemberRoleAdmin+ members := make([]portalPageMember, 0, len(subjects))+ for _, subject := range subjects {+ if subject == nil {continue}- user, err := reg.GetUser(membership.UserID)- if err != nil {- return nil, err- }- if user == nil {- return nil, errors.New("portal member user not found")+ if subject.State == registry.AccountAccessStatePending && !canManage {+ continue}members = append(members, portalPageMember{- UserID: membership.UserID,- Email: user.Email,- Role: membership.Role,- CreatedAt: membership.CreatedAt,+ SubjectID: subject.SubjectID,+ UserID: subject.UserID,+ Email: subject.Email,+ Role: subject.Role,+ State: subject.State,+ CreatedAt: subject.CreatedAt,})}diff --git a/internal/cloudcp/registry/models.go b/internal/cloudcp/registry/models.goindex d70cb72df1..44ab5381fb 100644--- a/internal/cloudcp/registry/models.go+++ b/internal/cloudcp/registry/models.go@@ -49,6 +49,35 @@ type AccountMembership struct {CreatedAt time.Time `json:"created_at"`}+// AccountInvitation represents a pending account invitation that has not yet+// been accepted through a verified account login.+type AccountInvitation struct {+ ID string `json:"id"`+ AccountID string `json:"account_id"`+ Email string `json:"email"`+ Role MemberRole `json:"role"`+ InvitedBy string `json:"invited_by"`+ InvitedAt time.Time `json:"invited_at"`+}++type AccountAccessState string++const (+ AccountAccessStateActive AccountAccessState = "active"+ AccountAccessStatePending AccountAccessState = "pending"+)++// AccountAccessSubject is the canonical roster shape for Pulse Account access+// surfaces, covering both active members and pending invitations.+type AccountAccessSubject struct {+ SubjectID string `json:"subject_id"`+ UserID string `json:"user_id,omitempty"`+ Email string `json:"email"`+ Role MemberRole `json:"role"`+ State AccountAccessState `json:"state"`+ CreatedAt time.Time `json:"created_at"`+}+// TenantState represents the lifecycle state of a tenant.type TenantState string@@ -198,3 +227,18 @@ func GenerateUserID() (string, error) {}return sb.String(), nil}++// GenerateAccountInvitationID returns an invitation ID of the form "ainv_"+// followed by 10 random Crockford base32 characters (50 bits of entropy).+func GenerateAccountInvitationID() (string, error) {+ b := make([]byte, 10)+ if _, err := rand.Read(b); err != nil {+ return "", fmt.Errorf("generate account invitation id: %w", err)+ }+ var sb strings.Builder+ sb.WriteString("ainv_")+ for _, v := range b {+ sb.WriteByte(crockfordBase32[int(v)%len(crockfordBase32)])+ }+ return sb.String(), nil+}diff --git a/internal/cloudcp/registry/registry.go b/internal/cloudcp/registry/registry.goindex 353ab984e8..8be1b8099d 100644--- a/internal/cloudcp/registry/registry.go+++ b/internal/cloudcp/registry/registry.go@@ -7,6 +7,7 @@ import ("net/url""os""path/filepath"+ "sort""strings""time"@@ -137,6 +138,19 @@ func (r *TenantRegistry) initSchema() error {CREATE INDEX IF NOT EXISTS idx_memberships_user_id_created_at ON account_memberships(user_id, created_at DESC);CREATE INDEX IF NOT EXISTS idx_memberships_account_id_created_at ON account_memberships(account_id, created_at DESC);+ CREATE TABLE IF NOT EXISTS account_invitations (+ id TEXT PRIMARY KEY,+ account_id TEXT NOT NULL,+ email TEXT NOT NULL,+ role TEXT NOT NULL DEFAULT 'tech',+ invited_by TEXT NOT NULL DEFAULT '',+ invited_at INTEGER NOT NULL,+ UNIQUE (account_id, email),+ FOREIGN KEY (account_id) REFERENCES accounts(id)+ );+ CREATE INDEX IF NOT EXISTS idx_account_invitations_account_id_invited_at ON account_invitations(account_id, invited_at DESC);+ CREATE INDEX IF NOT EXISTS idx_account_invitations_email_invited_at ON account_invitations(email, invited_at DESC);+CREATE TABLE IF NOT EXISTS hosted_entitlements (id TEXT PRIMARY KEY,kind TEXT NOT NULL DEFAULT 'paid',@@ -1494,6 +1508,289 @@ func (r *TenantRegistry) ListMembersByAccount(accountID string) ([]*AccountMembereturn scanMemberships(rows)}+// UpsertInvitation creates or updates a pending invitation for an account email.+func (r *TenantRegistry) UpsertInvitation(invitation *AccountInvitation) error {+ if invitation == nil {+ return fmt.Errorf("invitation is nil")+ }+ now := time.Now().UTC()+ if invitation.InvitedAt.IsZero() {+ invitation.InvitedAt = now+ }+ invitation.Email = strings.ToLower(strings.TrimSpace(invitation.Email))+ invitation.InvitedBy = strings.TrimSpace(invitation.InvitedBy)+ if invitation.Email == "" {+ return fmt.Errorf("invitation email is required")+ }+ if invitation.AccountID == "" {+ return fmt.Errorf("invitation account id is required")+ }+ if invitation.ID == "" {+ id, err := GenerateAccountInvitationID()+ if err != nil {+ return fmt.Errorf("generate invitation id: %w", err)+ }+ invitation.ID = id+ }+ role := invitation.Role+ if strings.TrimSpace(string(role)) == "" {+ role = MemberRoleTech+ }+ _, err := r.db.Exec(`+ INSERT INTO account_invitations (+ id, account_id, email, role, invited_by, invited_at+ ) VALUES (?, ?, ?, ?, ?, ?)+ ON CONFLICT(account_id, email) DO UPDATE SET+ role = excluded.role,+ invited_by = excluded.invited_by,+ invited_at = excluded.invited_at+ `, invitation.ID, invitation.AccountID, invitation.Email, string(role), invitation.InvitedBy, invitation.InvitedAt.Unix())+ if err != nil {+ return fmt.Errorf("upsert invitation: %w", err)+ }+ invitation.Role = role+ return nil+}++// GetInvitation returns an invitation by ID.+func (r *TenantRegistry) GetInvitation(invitationID string) (*AccountInvitation, error) {+ row := r.db.QueryRow(`SELECT+ id, account_id, email, role, invited_by, invited_at+ FROM account_invitations+ WHERE id = ?`, strings.TrimSpace(invitationID))+ return scanInvitation(row)+}++// GetInvitationByAccountAndEmail returns a pending invitation for an account/email pair.+func (r *TenantRegistry) GetInvitationByAccountAndEmail(accountID, email string) (*AccountInvitation, error) {+ row := r.db.QueryRow(`SELECT+ id, account_id, email, role, invited_by, invited_at+ FROM account_invitations+ WHERE account_id = ? AND email = ?`, strings.TrimSpace(accountID), strings.ToLower(strings.TrimSpace(email)))+ return scanInvitation(row)+}++// ListInvitationsByAccount returns pending invitations for an account.+func (r *TenantRegistry) ListInvitationsByAccount(accountID string) ([]*AccountInvitation, error) {+ rows, err := r.db.Query(`SELECT+ id, account_id, email, role, invited_by, invited_at+ FROM account_invitations+ WHERE account_id = ?+ ORDER BY invited_at DESC`, strings.TrimSpace(accountID))+ if err != nil {+ return nil, fmt.Errorf("list invitations by account: %w", err)+ }+ defer rows.Close()+ return scanInvitations(rows)+}++// ListInvitationsByEmail returns all pending invitations for an email.+func (r *TenantRegistry) ListInvitationsByEmail(email string) ([]*AccountInvitation, error) {+ rows, err := r.db.Query(`SELECT+ id, account_id, email, role, invited_by, invited_at+ FROM account_invitations+ WHERE email = ?+ ORDER BY invited_at DESC`, strings.ToLower(strings.TrimSpace(email)))+ if err != nil {+ return nil, fmt.Errorf("list invitations by email: %w", err)+ }+ defer rows.Close()+ return scanInvitations(rows)+}++// UpdateInvitationRole updates the role stored on a pending invitation.+func (r *TenantRegistry) UpdateInvitationRole(invitationID string, role MemberRole, invitedBy string) error {+ invitationID = strings.TrimSpace(invitationID)+ if invitationID == "" {+ return fmt.Errorf("invitation id is required")+ }+ roleValue := strings.TrimSpace(string(role))+ if roleValue == "" {+ roleValue = string(MemberRoleTech)+ }+ res, err := r.db.Exec(`+ UPDATE account_invitations+ SET role = ?, invited_by = ?, invited_at = ?+ WHERE id = ?`,+ roleValue,+ strings.TrimSpace(invitedBy),+ time.Now().UTC().Unix(),+ invitationID,+ )+ if err != nil {+ return fmt.Errorf("update invitation role: %w", err)+ }+ affected, err := res.RowsAffected()+ if err != nil {+ return fmt.Errorf("get rows affected: %w", err)+ }+ if affected == 0 {+ return fmt.Errorf("invitation %q not found", invitationID)+ }+ return nil+}++// DeleteInvitation removes a pending invitation by ID.+func (r *TenantRegistry) DeleteInvitation(invitationID string) error {+ res, err := r.db.Exec(`DELETE FROM account_invitations WHERE id = ?`, strings.TrimSpace(invitationID))+ if err != nil {+ return fmt.Errorf("delete invitation: %w", err)+ }+ affected, err := res.RowsAffected()+ if err != nil {+ return fmt.Errorf("get rows affected: %w", err)+ }+ if affected == 0 {+ return fmt.Errorf("invitation %q not found", invitationID)+ }+ return nil+}++// DeleteInvitationByAccountAndEmail removes a pending invitation for an account/email pair.+func (r *TenantRegistry) DeleteInvitationByAccountAndEmail(accountID, email string) error {+ _, err := r.db.Exec(+ `DELETE FROM account_invitations WHERE account_id = ? AND email = ?`,+ strings.TrimSpace(accountID),+ strings.ToLower(strings.TrimSpace(email)),+ )+ if err != nil {+ return fmt.Errorf("delete invitation by account and email: %w", err)+ }+ return nil+}++// AcceptInvitationsForUser promotes any pending account invitations for an email+// into active memberships for the authenticated user and then clears them.+func (r *TenantRegistry) AcceptInvitationsForUser(email, userID string) error {+ email = strings.ToLower(strings.TrimSpace(email))+ userID = strings.TrimSpace(userID)+ if email == "" {+ return fmt.Errorf("email is required")+ }+ if userID == "" {+ return fmt.Errorf("user id is required")+ }++ tx, err := r.db.Begin()+ if err != nil {+ return fmt.Errorf("begin accept invitations tx: %w", err)+ }+ defer func() {+ if tx != nil {+ _ = tx.Rollback()+ }+ }()++ rows, err := tx.Query(`SELECT+ id, account_id, email, role, invited_by, invited_at+ FROM account_invitations+ WHERE email = ?+ ORDER BY invited_at ASC`, email)+ if err != nil {+ return fmt.Errorf("list invitations for acceptance: %w", err)+ }+ invitations, err := scanInvitations(rows)+ _ = rows.Close()+ if err != nil {+ return err+ }++ for _, invitation := range invitations {+ if invitation == nil {+ continue+ }+ var exists int+ if err := tx.QueryRow(+ `SELECT COUNT(1) FROM account_memberships WHERE account_id = ? AND user_id = ?`,+ invitation.AccountID,+ userID,+ ).Scan(&exists); err != nil {+ return fmt.Errorf("check existing membership: %w", err)+ }+ if exists == 0 {+ roleValue := strings.TrimSpace(string(invitation.Role))+ if roleValue == "" {+ roleValue = string(MemberRoleTech)+ }+ if _, err := tx.Exec(`+ INSERT INTO account_memberships (+ account_id, user_id, role, created_at+ ) VALUES (?, ?, ?, ?)`,+ invitation.AccountID,+ userID,+ roleValue,+ time.Now().UTC().Unix(),+ ); err != nil {+ return fmt.Errorf("create membership from invitation: %w", err)+ }+ }+ if _, err := tx.Exec(`DELETE FROM account_invitations WHERE id = ?`, invitation.ID); err != nil {+ return fmt.Errorf("delete accepted invitation: %w", err)+ }+ }++ if err := tx.Commit(); err != nil {+ return fmt.Errorf("commit accept invitations tx: %w", err)+ }+ tx = nil+ return nil+}++// ListAccessSubjectsByAccount returns the canonical roster view for an account,+// combining active members with pending invitations.+func (r *TenantRegistry) ListAccessSubjectsByAccount(accountID string) ([]*AccountAccessSubject, error) {+ memberships, err := r.ListMembersByAccount(accountID)+ if err != nil {+ return nil, err+ }+ invitations, err := r.ListInvitationsByAccount(accountID)+ if err != nil {+ return nil, err+ }++ subjects := make([]*AccountAccessSubject, 0, len(memberships)+len(invitations))+ for _, membership := range memberships {+ if membership == nil {+ continue+ }+ user, err := r.GetUser(membership.UserID)+ if err != nil {+ return nil, fmt.Errorf("load member user: %w", err)+ }+ if user == nil {+ return nil, fmt.Errorf("member user %q not found", membership.UserID)+ }+ subjects = append(subjects, &AccountAccessSubject{+ SubjectID: membership.UserID,+ UserID: membership.UserID,+ Email: user.Email,+ Role: membership.Role,+ State: AccountAccessStateActive,+ CreatedAt: membership.CreatedAt,+ })+ }+ for _, invitation := range invitations {+ if invitation == nil {+ continue+ }+ subjects = append(subjects, &AccountAccessSubject{+ SubjectID: invitation.ID,+ Email: invitation.Email,+ Role: invitation.Role,+ State: AccountAccessStatePending,+ CreatedAt: invitation.InvitedAt,+ })+ }++ sort.SliceStable(subjects, func(i, j int) bool {+ if subjects[i].CreatedAt.Equal(subjects[j].CreatedAt) {+ return subjects[i].State < subjects[j].State+ }+ return subjects[i].CreatedAt.After(subjects[j].CreatedAt)+ })+ return subjects, nil+}+// ListAccountsByUser returns account IDs for all accounts the given user belongs to.func (r *TenantRegistry) ListAccountsByUser(userID string) ([]string, error) {rows, err := r.db.Query(`SELECT account_id FROM account_memberships WHERE user_id = ? ORDER BY created_at DESC`, userID)@@ -1901,6 +2198,41 @@ func scanMemberships(rows *sql.Rows) ([]*AccountMembership, error) {return memberships, rows.Err()}+func scanInvitation(s scanner) (*AccountInvitation, error) {+ var invitation AccountInvitation+ var role string+ var invitedAt int64+ if err := s.Scan(+ &invitation.ID,+ &invitation.AccountID,+ &invitation.Email,+ &role,+ &invitation.InvitedBy,+ &invitedAt,+ ); err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }+ return nil, fmt.Errorf("scan invitation: %w", err)+ }+ invitation.Email = strings.ToLower(strings.TrimSpace(invitation.Email))+ invitation.Role = MemberRole(role)+ invitation.InvitedAt = time.Unix(invitedAt, 0).UTC()+ return &invitation, nil+}++func scanInvitations(rows *sql.Rows) ([]*AccountInvitation, error) {+ var invitations []*AccountInvitation+ for rows.Next() {+ invitation, err := scanInvitation(rows)+ if err != nil {+ return nil, err+ }+ invitations = append(invitations, invitation)+ }+ return invitations, rows.Err()+}+func nullableTimeUnix(t *time.Time) driver.Value {if t == nil {return nildiff --git a/internal/cloudcp/registry/registry_test.go b/internal/cloudcp/registry/registry_test.goindex 7564cbe5cc..756c3e48a4 100644--- a/internal/cloudcp/registry/registry_test.go+++ b/internal/cloudcp/registry/registry_test.go@@ -563,6 +563,149 @@ func TestCreateMembership_RequiresExistingAccountAndUser(t *testing.T) {}}+func TestInvitationCRUDAndAccessSubjects(t *testing.T) {+ reg := newTestRegistry(t)++ accountID, err := GenerateAccountID()+ if err != nil {+ t.Fatal(err)+ }+ userID, err := GenerateUserID()+ if err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateAccount(&Account{ID: accountID, Kind: AccountKindMSP, DisplayName: "Account"}); err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateUser(&User{ID: userID, Email: "[email protected]"}); err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateMembership(&AccountMembership{+ AccountID: accountID,+ UserID: userID,+ Role: MemberRoleOwner,+ }); err != nil {+ t.Fatal(err)+ }++ invitation := &AccountInvitation{+ AccountID: accountID,+ Email: "[email protected]",+ Role: MemberRoleTech,+ InvitedBy: "[email protected]",+ }+ if err := reg.UpsertInvitation(invitation); err != nil {+ t.Fatalf("UpsertInvitation: %v", err)+ }+ if invitation.ID == "" {+ t.Fatal("expected invitation ID to be generated")+ }++ gotInvitation, err := reg.GetInvitationByAccountAndEmail(accountID, "[email protected]")+ if err != nil {+ t.Fatalf("GetInvitationByAccountAndEmail: %v", err)+ }+ if gotInvitation == nil {+ t.Fatal("expected invitation to be stored")+ }+ if gotInvitation.Role != MemberRoleTech {+ t.Fatalf("invitation role = %q, want %q", gotInvitation.Role, MemberRoleTech)+ }++ if err := reg.UpdateInvitationRole(gotInvitation.ID, MemberRoleAdmin, "[email protected]"); err != nil {+ t.Fatalf("UpdateInvitationRole: %v", err)+ }+ gotInvitation, err = reg.GetInvitation(gotInvitation.ID)+ if err != nil {+ t.Fatalf("GetInvitation: %v", err)+ }+ if gotInvitation == nil || gotInvitation.Role != MemberRoleAdmin {+ t.Fatalf("updated invitation = %+v, want role=%q", gotInvitation, MemberRoleAdmin)+ }++ subjects, err := reg.ListAccessSubjectsByAccount(accountID)+ if err != nil {+ t.Fatalf("ListAccessSubjectsByAccount: %v", err)+ }+ if len(subjects) != 2 {+ t.Fatalf("expected 2 access subjects, got %d", len(subjects))+ }++ var sawActive bool+ var sawPending bool+ for _, subject := range subjects {+ if subject == nil {+ continue+ }+ switch subject.State {+ case AccountAccessStateActive:+ sawActive = true+ if subject.UserID != userID {+ t.Fatalf("active subject user_id = %q, want %q", subject.UserID, userID)+ }+ case AccountAccessStatePending:+ sawPending = true+ if subject.SubjectID == "" {+ t.Fatal("pending invitation missing subject ID")+ }+ if subject.Email != "[email protected]" {+ t.Fatalf("pending email = %q, want %q", subject.Email, "[email protected]")+ }+ }+ }+ if !sawActive || !sawPending {+ t.Fatalf("expected both active and pending access subjects, got %+v", subjects)+ }+}++func TestAcceptInvitationsForUser(t *testing.T) {+ reg := newTestRegistry(t)++ accountID, err := GenerateAccountID()+ if err != nil {+ t.Fatal(err)+ }+ userID, err := GenerateUserID()+ if err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateAccount(&Account{ID: accountID, Kind: AccountKindMSP, DisplayName: "Account"}); err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateUser(&User{ID: userID, Email: "[email protected]"}); err != nil {+ t.Fatal(err)+ }+ if err := reg.UpsertInvitation(&AccountInvitation{+ AccountID: accountID,+ Email: "[email protected]",+ Role: MemberRoleAdmin,+ }); err != nil {+ t.Fatalf("UpsertInvitation: %v", err)+ }++ if err := reg.AcceptInvitationsForUser("[email protected]", userID); err != nil {+ t.Fatalf("AcceptInvitationsForUser: %v", err)+ }++ membership, err := reg.GetMembership(accountID, userID)+ if err != nil {+ t.Fatalf("GetMembership: %v", err)+ }+ if membership == nil {+ t.Fatal("expected invitation to become membership")+ }+ if membership.Role != MemberRoleAdmin {+ t.Fatalf("membership.Role = %q, want %q", membership.Role, MemberRoleAdmin)+ }+ invitation, err := reg.GetInvitationByAccountAndEmail(accountID, "[email protected]")+ if err != nil {+ t.Fatalf("GetInvitationByAccountAndEmail: %v", err)+ }+ if invitation != nil {+ t.Fatalf("expected invitation to be deleted after acceptance, got %+v", invitation)+ }+}+func TestList(t *testing.T) {reg := newTestRegistry(t)