diff --git a/internal/cloudcp/account/tenant_handlers.go b/internal/cloudcp/account/tenant_handlers.go index ae34606418..1490d236bb 100644 --- a/internal/cloudcp/account/tenant_handlers.go +++ b/internal/cloudcp/account/tenant_handlers.go @@ -2,11 +2,14 @@ package account import ( "context" + "errors" "fmt" "net/http" "strings" "sync" + "time" + "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/lifecycle" "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry" pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing" ) @@ -366,9 +369,25 @@ func parseTenantState(s string) (registry.TenantState, bool) { } } -// HandleUpdateTenant updates display name and/or state. +// WorkspaceBillingReconciler finishes an existing manual resume without an +// external billing request. It is provided by the control-plane provisioner. +type WorkspaceBillingReconciler interface { + ResumeWorkspaceBilling(context.Context, *registry.Tenant, bool) error +} + +// TenantMutationPolicy comes only from control-plane configuration. Missing +// billing data is not evidence that a Stripe-hosted account is locally billed. +type TenantMutationPolicy struct{ LocalMSPBilling bool } + +// HandleUpdateTenant defaults to Stripe-backed authority. Only configured MSP +// control planes may opt into the existing no-Stripe local billing path. +func HandleUpdateTenant(reg *registry.TenantRegistry, billing ...WorkspaceBillingReconciler) http.HandlerFunc { + return HandleUpdateTenantWithPolicy(reg, TenantMutationPolicy{}, billing...) +} + +// HandleUpdateTenantWithPolicy updates display name and/or state. // Route: PATCH /api/accounts/{account_id}/tenants/{tenant_id} -func HandleUpdateTenant(reg *registry.TenantRegistry) http.HandlerFunc { +func HandleUpdateTenantWithPolicy(reg *registry.TenantRegistry, policy TenantMutationPolicy, billing ...WorkspaceBillingReconciler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPatch { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) @@ -406,99 +425,107 @@ func HandleUpdateTenant(reg *registry.TenantRegistry) http.HandlerFunc { return } - ctx, lease, err := reg.AcquireRuntimeLifecycle(r.Context(), tenantID) + // Preserve the existing not-found/account boundary before consuming a body. + // This is admission only; the transaction reloads its own current snapshot. + present, err := reg.GetTenantForAccount(accountID, tenantID) if err != nil { + auditEvent(r, "cp_tenant_update", "failure").Err(err).Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "tenant_lookup_failed").Msg("Tenant update failed") http.Error(w, "internal error", http.StatusInternalServerError) return } - defer lease.Close() - r = r.WithContext(ctx) - tenant, err := reg.GetTenantForAccount(accountID, tenantID) - if err != nil { - auditEvent(r, "cp_tenant_update", "failure"). - Err(err). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_lookup_failed"). - Msg("Tenant update failed") - http.Error(w, "internal error", http.StatusInternalServerError) - return - } - if tenant == nil { - auditEvent(r, "cp_tenant_update", "failure"). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_not_found"). - Msg("Tenant update failed") + if present == nil { + auditEvent(r, "cp_tenant_update", "failure").Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "tenant_not_found").Msg("Tenant update failed") http.Error(w, "tenant not found", http.StatusNotFound) return } var req updateTenantRequest if err := decodeJSON(w, r, &req); err != nil { - auditEvent(r, "cp_tenant_update", "failure"). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "invalid_json_body"). - Msg("Tenant update failed") + auditEvent(r, "cp_tenant_update", "failure").Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "invalid_json_body").Msg("Tenant update failed") return } - - previousDisplayName := tenant.DisplayName - previousState := tenant.State - if req.DisplayName != nil { name := strings.TrimSpace(*req.DisplayName) if name == "" { - auditEvent(r, "cp_tenant_update", "failure"). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "invalid_display_name"). - Msg("Tenant update failed") + auditEvent(r, "cp_tenant_update", "failure").Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "invalid_display_name").Msg("Tenant update failed") http.Error(w, "invalid display_name", http.StatusBadRequest) return } - tenant.DisplayName = name + req.DisplayName = &name } - + var next *registry.TenantState stateVal := req.Status if stateVal == nil { stateVal = req.State } if stateVal != nil { - st, ok := parseTenantState(*stateVal) + state, ok := parseTenantState(*stateVal) if !ok { - auditEvent(r, "cp_tenant_update", "failure"). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "invalid_state"). - Msg("Tenant update failed") + auditEvent(r, "cp_tenant_update", "failure").Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "invalid_state").Msg("Tenant update failed") http.Error(w, "invalid status", http.StatusBadRequest) return } - tenant.State = st + next = &state } - - if err := reg.Update(tenant); err != nil { - if isNotFoundErr(err) { - auditEvent(r, "cp_tenant_update", "failure"). - Err(err). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_not_found"). - Msg("Tenant update failed") - http.Error(w, "tenant not found", http.StatusNotFound) + // A positive resume is ordered with billing events, not a slow request body. + // Both leases are nonblocking. Withdrawals never wait on a runtime recovery. + ctx := r.Context() + if next != nil && *next == registry.TenantStateActive { + sa, err := reg.GetStripeAccount(accountID) + if err != nil { + http.Error(w, "internal error", http.StatusInternalServerError) return } - auditEvent(r, "cp_tenant_update", "failure"). - Err(err). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_update_failed"). - Msg("Tenant update failed") + if sa != nil { + var authority *lifecycle.Lease + ctx, authority, err = reg.AcquireBillingAuthority(ctx, sa.StripeCustomerID) + if err != nil { + http.Error(w, "Workspace billing is busy. Refresh before trying again.", http.StatusServiceUnavailable) + return + } + defer authority.Close() + } + } + + ctx, lease, err := reg.AcquireRuntimeLifecycle(ctx, tenantID) + if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) return } + defer lease.Close() + r = r.WithContext(ctx) + previous, tenant, err := reg.PatchTenantForAccount(ctx, accountID, tenantID, req.DisplayName, next, policy.LocalMSPBilling) + if err != nil { + status, message, reason := http.StatusInternalServerError, "internal error", "tenant_update_failed" + if errors.Is(err, registry.ErrTenantNotFound) { + status, message, reason = http.StatusNotFound, "tenant not found", "tenant_not_found" + } + if errors.Is(err, registry.ErrTenantStateConflict) { + status, message, reason = http.StatusConflict, "Workspace state changed or its subscription is inactive. Refresh before trying again.", "tenant_state_conflict" + } + auditEvent(r, "cp_tenant_update", "failure").Err(err).Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", reason).Msg("Tenant update failed") + http.Error(w, message, status) + return + } + if previous.State == registry.TenantStateSuspended && tenant.State == registry.TenantStateActive { + var resumeErr error + if len(billing) == 0 || billing[0] == nil { + resumeErr = fmt.Errorf("workspace billing is unavailable") + } else { + resumeErr = billing[0].ResumeWorkspaceBilling(ctx, tenant, policy.LocalMSPBilling) + } + if resumeErr != nil { + // Never roll back a newer withdrawal. A field-scoped re-hold only applies + // while this request still owns an active/suspended lifecycle. + suspended := registry.TenantStateSuspended + _, _, holdErr := reg.PatchTenantForAccount(ctx, accountID, tenantID, nil, &suspended) + auditEvent(r, "cp_tenant_update", "failure").Err(errors.Join(resumeErr, holdErr)).Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "billing_resume_failed").Msg("Tenant resume unconfirmed") + http.Error(w, "Workspace could not be resumed. Refresh before trying again.", http.StatusServiceUnavailable) + return + } + } + + previousDisplayName, previousState := previous.DisplayName, previous.State auditEvent(r, "cp_tenant_update", "success"). Str("account_id", accountID). @@ -561,37 +588,27 @@ func HandleDeleteTenant(reg *registry.TenantRegistry, provisioner WorkspaceProvi } defer lease.Close() r = r.WithContext(ctx) - tenant, err := reg.GetTenantForAccount(accountID, tenantID) + previous, tenant, err := reg.BeginTenantDeletionForAccount(ctx, accountID, tenantID) if err != nil { - auditEvent(r, "cp_tenant_delete", "failure"). - Err(err). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_lookup_failed"). - Msg("Tenant deletion failed") + status, message, reason := http.StatusInternalServerError, "internal error", "tenant_mark_deleting_failed" + if errors.Is(err, registry.ErrTenantNotFound) { + status, message, reason = http.StatusNotFound, "tenant not found", "tenant_not_found" + } + auditEvent(r, "cp_tenant_delete", "failure").Err(err).Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", reason).Msg("Tenant deletion failed") + http.Error(w, message, status) + return + } + previousState := previous.State + // Revocation does not depend on Docker cleanup succeeding. A later billing + // event cannot rotate this token because deleting/deleted stay terminal. + if err := reg.RevokeHostedEntitlement(tenantID, time.Now().UTC()); err != nil { + auditEvent(r, "cp_tenant_delete", "failure").Err(err).Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "tenant_revoke_failed").Msg("Tenant deletion failed") http.Error(w, "internal error", http.StatusInternalServerError) return } - if tenant == nil { - auditEvent(r, "cp_tenant_delete", "failure"). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_not_found"). - Msg("Tenant deletion failed") - http.Error(w, "tenant not found", http.StatusNotFound) - return - } - - previousState := tenant.State - tenant.State = registry.TenantStateDeleting - if err := reg.Update(tenant); err != nil { - auditEvent(r, "cp_tenant_delete", "failure"). - Err(err). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_mark_deleting_failed"). - Msg("Tenant deletion failed") - http.Error(w, "internal error", http.StatusInternalServerError) + if tenant.State == registry.TenantStateDeleted { + auditEvent(r, "cp_tenant_delete", "success").Str("account_id", accountID).Str("tenant_id", tenantID).Str("old_state", string(previousState)).Str("new_state", string(tenant.State)).Msg("Tenant deleted") + w.WriteHeader(http.StatusNoContent) return } @@ -608,15 +625,9 @@ func HandleDeleteTenant(reg *registry.TenantRegistry, provisioner WorkspaceProvi } } - tenant.ContainerID = "" - tenant.State = registry.TenantStateDeleted - if err := reg.Update(tenant); err != nil { - auditEvent(r, "cp_tenant_delete", "failure"). - Err(err). - Str("account_id", accountID). - Str("tenant_id", tenantID). - Str("reason", "tenant_finalize_delete_failed"). - Msg("Tenant deletion failed") + _, tenant, err = reg.FinalizeTenantDeletionForAccount(ctx, accountID, tenantID) + if err != nil { + auditEvent(r, "cp_tenant_delete", "failure").Err(err).Str("account_id", accountID).Str("tenant_id", tenantID).Str("reason", "tenant_finalize_delete_failed").Msg("Tenant deletion failed") http.Error(w, "internal error", http.StatusInternalServerError) return } diff --git a/internal/cloudcp/account/tenant_handlers_test.go b/internal/cloudcp/account/tenant_handlers_test.go index 384a1da956..555af339a6 100644 --- a/internal/cloudcp/account/tenant_handlers_test.go +++ b/internal/cloudcp/account/tenant_handlers_test.go @@ -1,6 +1,12 @@ package account import ( + "errors" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "io" + "reflect" + "bytes" "context" "crypto/ed25519" @@ -57,7 +63,7 @@ func newTestTenantMuxWithWorkspaceLimitPolicy(t *testing.T, reg *registry.Tenant listTenants := HandleListTenants(reg) createTenant := HandleCreateTenantWithWorkspaceLimitPolicy(reg, provisioner, policy) - updateTenant := HandleUpdateTenant(reg) + updateTenant := HandleUpdateTenantWithPolicy(reg, TenantMutationPolicy{LocalMSPBilling: policy.ProviderHostedMSP}, provisioner) deleteTenant := HandleDeleteTenant(reg, provisioner) collection := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -788,3 +794,506 @@ func TestWorkspaceWritesRespectRuntimeLifecycle(t *testing.T) { }) } } + +// The first body read is a deterministic interleaving, not a timing race. Real +// MSP billing withdrawal must remain effective while the caller supplies JSON. +type tenantEditBody struct { + io.Reader + beforeRead func() + once sync.Once +} + +func (b *tenantEditBody) Read(p []byte) (int, error) { + b.once.Do(b.beforeRead) + return b.Reader.Read(p) +} +func (b *tenantEditBody) Close() error { return nil } + +func TestWorkspacePatchPreservesWithdrawalDuringBodyRead(t *testing.T) { + for _, tc := range []struct { + name, body string + status int + display string + }{ + {"rename", `{"display_name":"Renamed"}`, http.StatusOK, "Renamed"}, + {"empty", `{}`, http.StatusOK, "Original"}, + {"suspend", `{"display_name":"Renamed","state":"suspended"}`, http.StatusConflict, "Original"}, + {"resume", `{"status":"active"}`, http.StatusConflict, "Original"}, + } { + t.Run(tc.name, func(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(®istry.Account{ID: "a-withdraw", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + createTestStripeAccount(t, reg, "a-withdraw", "msp_starter") + _, p := newTestTenantMux(t, reg, t.TempDir()) + tenant, err := p.ProvisionWorkspace(context.Background(), "a-withdraw", "Original") + if err != nil { + t.Fatal(err) + } + var audit bytes.Buffer + oldLogger := log.Logger + log.Logger = zerolog.New(&audit) + defer func() { log.Logger = oldLogger }() + req := httptest.NewRequest(http.MethodPatch, "/", nil) + req.SetPathValue("account_id", tenant.AccountID) + req.SetPathValue("tenant_id", tenant.ID) + req.Body = &tenantEditBody{Reader: strings.NewReader(tc.body), beforeRead: func() { + // Older source may defer its billing-file update at the runtime lease; + // authority must already be withdrawn regardless of that deferred result. + _ = p.HandleMSPSubscriptionDeleted(context.Background(), cpstripe.Subscription{ID: "sub_canceled", Customer: "cus_test_a-withdraw"}) + current, err := reg.Get(tenant.ID) + if err != nil || current.State != registry.TenantStateCanceled { + t.Fatalf("withdrawal did not run: %+v %v", current, err) + } + }} + res := httptest.NewRecorder() + HandleUpdateTenant(reg, tenantBillingFunc(func(context.Context, *registry.Tenant, bool) error { return nil }))(res, req) + if res.Code != tc.status { + t.Fatalf("PATCH = %d %s, want %d", res.Code, res.Body.String(), tc.status) + } + current, err := reg.Get(tenant.ID) + if err != nil { + t.Fatal(err) + } + if current.State != registry.TenantStateCanceled || current.DisplayName != tc.display { + t.Fatalf("stale edit undid withdrawal or partially renamed: %+v", current) + } + sa, err := reg.GetStripeAccount(tenant.AccountID) + if err != nil || sa.SubscriptionState != "canceled" { + t.Fatalf("billing changed: %+v %v", sa, err) + } + entitlements, err := reg.ListHostedEntitlements() + if err != nil || len(entitlements) != 1 || entitlements[0].RevokedAt == nil { + t.Fatalf("refresh authority was recreated: %+v %v", entitlements, err) + } + if tc.status == http.StatusOK { + var returned registry.Tenant + if err := json.Unmarshal(res.Body.Bytes(), &returned); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(returned, *current) { + t.Fatalf("response is stale: %+v != %+v", returned, current) + } + found := false + for _, line := range strings.Split(audit.String(), "\n") { + var event map[string]any + if json.Unmarshal([]byte(line), &event) != nil || event["audit_event"] != "cp_tenant_update" { + continue + } + if event["outcome"] == "success" { + found = true + if event["old_state"] != "canceled" || event["new_state"] != "canceled" || event["new_display_name"] != tc.display { + t.Fatalf("stale audit: %s", line) + } + } + } + if !found { + t.Fatalf("missing update success audit: %s", audit.String()) + } + } + }) + } +} + +func TestWorkspacePatchDoesNotHoldRuntimeWhileReadingBody(t *testing.T) { + for _, action := range []string{"delete", "move_account"} { + t.Run(action, func(t *testing.T) { + reg := newTestRegistry(t) + for _, id := range []string{"a-current", "a-other"} { + if err := reg.CreateAccount(®istry.Account{ID: id, Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + } + tenant := ®istry.Tenant{ID: "t-body", AccountID: "a-current", DisplayName: "Original", State: registry.TenantStateActive, ContainerID: "original"} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPatch, "/", nil) + req.SetPathValue("account_id", tenant.AccountID) + req.SetPathValue("tenant_id", tenant.ID) + req.Body = &tenantEditBody{Reader: strings.NewReader(`{"display_name":"Stale","state":"active"}`), beforeRead: func() { + if action == "delete" { + del := httptest.NewRequest(http.MethodDelete, "/", nil) + del.SetPathValue("account_id", tenant.AccountID) + del.SetPathValue("tenant_id", tenant.ID) + response := httptest.NewRecorder() + HandleDeleteTenant(reg, nil)(response, del) + if response.Code != http.StatusNoContent { + t.Fatalf("slow body blocked DELETE: %d %s", response.Code, response.Body.String()) + } + } else { + tenant.AccountID = "a-other" + if err := reg.Update(tenant); err != nil { + t.Fatal(err) + } + } + }} + res := httptest.NewRecorder() + HandleUpdateTenant(reg, tenantBillingFunc(func(context.Context, *registry.Tenant, bool) error { return nil }))(res, req) + want := http.StatusConflict + if action == "move_account" { + want = http.StatusNotFound + } + if res.Code != want { + t.Fatalf("late PATCH = %d %s, want %d", res.Code, res.Body.String(), want) + } + current, err := reg.Get(tenant.ID) + if err != nil { + t.Fatal(err) + } + if current.DisplayName != "Original" { + t.Fatalf("late rename applied: %+v", current) + } + if action == "delete" && (current.State != registry.TenantStateDeleted || current.ContainerID != "") { + t.Fatalf("deleted runtime revived: %+v", current) + } + if action == "move_account" && current.AccountID != "a-other" { + t.Fatalf("old account reclaimed client: %+v", current) + } + }) + } +} + +func TestWorkspacePatchStateAndResumePolicy(t *testing.T) { + for _, initial := range []registry.TenantState{registry.TenantStateProvisioning, registry.TenantStateActive, registry.TenantStateSuspended, registry.TenantStateCanceled, registry.TenantStateDeleting, registry.TenantStateDeleted, registry.TenantStateFailed, "unknown"} { + for _, next := range []string{"active", "suspended"} { + t.Run(string(initial)+"_to_"+next, func(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(®istry.Account{ID: "a-policy", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + createTestStripeAccount(t, reg, "a-policy", "msp_starter") + tenant := ®istry.Tenant{ID: "t-policy", AccountID: "a-policy", State: initial, ManualHold: initial == registry.TenantStateSuspended, DisplayName: "Original", ContainerID: "keep"} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPatch, "/", strings.NewReader(`{"display_name":"Renamed","state":"`+next+`"}`)) + req.SetPathValue("account_id", tenant.AccountID) + req.SetPathValue("tenant_id", tenant.ID) + res := httptest.NewRecorder() + HandleUpdateTenant(reg, tenantBillingFunc(func(context.Context, *registry.Tenant, bool) error { return nil }))(res, req) + allowed := initial == registry.TenantStateActive || initial == registry.TenantStateSuspended + want := http.StatusConflict + if allowed { + want = http.StatusOK + } + if res.Code != want { + t.Fatalf("state transition = %d %s, want %d", res.Code, res.Body.String(), want) + } + current, err := reg.Get(tenant.ID) + if err != nil { + t.Fatal(err) + } + if allowed { + if string(current.State) != next || current.DisplayName != "Renamed" { + t.Fatalf("valid change lost: %+v", current) + } + } else if current.State != initial || current.DisplayName != "Original" { + t.Fatalf("refused patch partly applied: %+v", current) + } + if current.ContainerID != "keep" { + t.Fatalf("runtime overwritten: %+v", current) + } + count, err := reg.CountActiveByAccountID(tenant.AccountID) + if err != nil { + t.Fatal(err) + } + if allowed && count != 1 { + t.Fatalf("manual transition released workspace capacity: %d", count) + } + }) + } + } + for _, stored := range []string{"active", "trial", "past_due", "grace", "canceled", "suspended", "expired", "paused", "unknown"} { + t.Run("billing_"+stored, func(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(®istry.Account{ID: "a-policy", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + if err := reg.CreateStripeAccount(®istry.StripeAccount{AccountID: "a-policy", StripeCustomerID: "cus_policy", SubscriptionState: stored}); err != nil { + t.Fatal(err) + } + tenant := ®istry.Tenant{ID: "t-policy", AccountID: "a-policy", State: registry.TenantStateSuspended, ManualHold: true} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPatch, "/", strings.NewReader(`{"status":"active"}`)) + req.SetPathValue("account_id", tenant.AccountID) + req.SetPathValue("tenant_id", tenant.ID) + res := httptest.NewRecorder() + HandleUpdateTenant(reg, tenantBillingFunc(func(context.Context, *registry.Tenant, bool) error { return nil }))(res, req) + allowed := stored == "active" || stored == "trial" || stored == "past_due" || stored == "grace" + want := http.StatusConflict + if allowed { + want = http.StatusOK + } + if res.Code != want { + t.Fatalf("billing %q resume = %d %s, want %d", stored, res.Code, res.Body.String(), want) + } + current, _ := reg.Get(tenant.ID) + if (current.State == registry.TenantStateActive) != allowed { + t.Fatalf("billing %q state %+v", stored, current) + } + }) + } +} + +type deletionMutationProvisioner struct { + mutate func(*registry.Tenant) error + calls int +} + +func (*deletionMutationProvisioner) ProvisionWorkspace(context.Context, string, string) (*registry.Tenant, error) { + return nil, fmt.Errorf("unexpected creation") +} +func (p *deletionMutationProvisioner) DeprovisionWorkspaceContainer(_ context.Context, tenant *registry.Tenant) error { + p.calls++ + return p.mutate(tenant) +} + +func TestWorkspaceDeletePreservesLatestMetadataAndIsIdempotent(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(®istry.Account{ID: "a-delete", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + tenant := ®istry.Tenant{ID: "t-delete", AccountID: "a-delete", State: registry.TenantStateActive, DisplayName: "Original", ContainerID: "runtime"} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + p := &deletionMutationProvisioner{mutate: func(beingDeleted *registry.Tenant) error { + if beingDeleted.State != registry.TenantStateDeleting { + return fmt.Errorf("deprovision did not receive current deleting row: %+v", beingDeleted) + } + current, err := reg.Get(tenant.ID) + if err != nil { + return err + } + current.DisplayName = "Latest" + current.PlanVersion = "msp_max" + current.StripeSubscriptionID = "sub_latest" + current.CurrentImageDigest = "image_latest" + current.HealthCheckOK = false + return reg.Update(current) + }} + var audit bytes.Buffer + oldLogger := log.Logger + log.Logger = zerolog.New(&audit) + defer func() { log.Logger = oldLogger }() + + for i := 0; i < 2; i++ { + req := httptest.NewRequest(http.MethodDelete, "/", nil) + req.SetPathValue("account_id", tenant.AccountID) + req.SetPathValue("tenant_id", tenant.ID) + res := httptest.NewRecorder() + HandleDeleteTenant(reg, p)(res, req) + if res.Code != http.StatusNoContent { + t.Fatalf("DELETE = %d %s", res.Code, res.Body.String()) + } + current, err := reg.Get(tenant.ID) + if err != nil { + t.Fatal(err) + } + if current.State != registry.TenantStateDeleted || current.ContainerID != "" || current.DisplayName != "Latest" || current.PlanVersion != "msp_max" || current.StripeSubscriptionID != "sub_latest" || current.CurrentImageDigest != "image_latest" { + t.Fatalf("finalization restored stale metadata: %+v", current) + } + } + if p.calls != 1 { + t.Fatalf("completed deletion deprovisioned %d times", p.calls) + } + var events []map[string]any + for _, line := range strings.Split(audit.String(), "\n") { + var event map[string]any + if json.Unmarshal([]byte(line), &event) == nil && event["audit_event"] == "cp_tenant_delete" && event["outcome"] == "success" { + events = append(events, event) + } + } + if len(events) != 2 || events[0]["old_state"] != "active" || events[1]["old_state"] != "deleted" || events[0]["new_state"] != "deleted" || events[1]["new_state"] != "deleted" { + t.Fatalf("missing or stale deletion audits: %+v", events) + } + +} + +type tenantBillingFunc func(context.Context, *registry.Tenant, bool) error + +func (f tenantBillingFunc) ResumeWorkspaceBilling(ctx context.Context, tenant *registry.Tenant, localMSPBilling bool) error { + return f(ctx, tenant, localMSPBilling) +} + +func TestWorkspaceManualResumeReconcilesRevokedBilling(t *testing.T) { + reg := newTestRegistry(t) + dir := t.TempDir() + mux, p := newTestTenantMux(t, reg, dir) + if err := reg.CreateAccount(®istry.Account{ID: "a-resume-real", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + createTestStripeAccount(t, reg, "a-resume-real", "msp_starter") + tenant, err := p.ProvisionWorkspace(context.Background(), "a-resume-real", "Original") + if err != nil { + t.Fatal(err) + } + patch := func(state string) *httptest.ResponseRecorder { + return doRequest(t, mux, httptest.NewRequest(http.MethodPatch, "/api/accounts/"+tenant.AccountID+"/tenants/"+tenant.ID, strings.NewReader(`{"state":"`+state+`"}`))) + } + if res := patch("suspended"); res.Code != http.StatusOK { + t.Fatalf("suspend: %d %s", res.Code, res.Body.String()) + } + sub := cpstripe.Subscription{ID: "sub_resume", Customer: "cus_test_a-resume-real", Status: "active", Metadata: map[string]string{"plan_version": "msp_starter"}} + if err := p.HandleMSPSubscriptionDeleted(context.Background(), sub); err != nil { + t.Fatal(err) + } + if err := p.HandleMSPSubscriptionUpdated(context.Background(), sub); err != nil { + t.Fatal(err) + } + current, err := reg.Get(tenant.ID) + if err != nil || current.State != registry.TenantStateSuspended || !current.ManualHold { + t.Fatalf("renewal cleared manual hold: %+v %v", current, err) + } + billingStore := config.NewFileBillingStore(filepath.Join(dir, tenant.ID)) + held, err := billingStore.GetBillingState("default") + if err != nil { + t.Fatal(err) + } + if held.EntitlementJWT != "" || held.EntitlementRefreshToken != "" || held.SubscriptionState != pkglicensing.SubStateSuspended { + t.Fatal("renewal issued a paid lease while held") + } + rows, err := reg.ListHostedEntitlements() + if err != nil || len(rows) != 1 || rows[0].RevokedAt == nil { + t.Fatalf("held renewal recreated refresh authority: %v", err) + } + if res := patch("active"); res.Code != http.StatusOK { + t.Fatalf("resume: %d %s", res.Code, res.Body.String()) + } + current, err = reg.Get(tenant.ID) + if err != nil || current.State != registry.TenantStateActive || current.ManualHold { + t.Fatalf("resume did not clear hold: %+v %v", current, err) + } + resumed, err := billingStore.GetBillingState("default") + if err != nil { + t.Fatal(err) + } + if resumed.EntitlementJWT == "" || resumed.EntitlementRefreshToken == "" { + t.Fatal("successful resume left the revoked/missing paid lease") + } + row, err := reg.GetHostedEntitlementByRefreshToken(resumed.EntitlementRefreshToken) + if err != nil || row == nil || row.RevokedAt != nil { + t.Fatalf("resume did not issue current refresh authority: %v", err) + } +} + +func TestWorkspaceResumeFailureKeepsHoldAndDoesNotReportSuccess(t *testing.T) { + for _, withdraw := range []bool{false, true} { + t.Run(fmt.Sprint(withdraw), func(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(®istry.Account{ID: "a-resume-fail", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + createTestStripeAccount(t, reg, "a-resume-fail", "msp_starter") + tenant := ®istry.Tenant{ID: "t-resume-fail", AccountID: "a-resume-fail", State: registry.TenantStateSuspended, ManualHold: true} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + reconciler := tenantBillingFunc(func(context.Context, *registry.Tenant, bool) error { + if withdraw { + return errors.Join(reg.SetTenantState(tenant.ID, registry.TenantStateCanceled), fmt.Errorf("billing write failed")) + } + return fmt.Errorf("billing write failed") + }) + req := httptest.NewRequest(http.MethodPatch, "/", strings.NewReader(`{"state":"active"}`)) + req.SetPathValue("account_id", tenant.AccountID) + req.SetPathValue("tenant_id", tenant.ID) + res := httptest.NewRecorder() + HandleUpdateTenant(reg, reconciler)(res, req) + if res.Code != http.StatusServiceUnavailable { + t.Fatalf("false resume success: %d %s", res.Code, res.Body.String()) + } + current, _ := reg.Get(tenant.ID) + want := registry.TenantStateSuspended + if withdraw { + want = registry.TenantStateCanceled + } + if current.State != want || (!withdraw && !current.ManualHold) { + t.Fatalf("compensation lost hold/withdrawal: %+v", current) + } + }) + } +} + +func TestWorkspaceFailedDeleteRetainsTerminalWithdrawal(t *testing.T) { + reg := newTestRegistry(t) + _, billing := newTestTenantMux(t, reg, t.TempDir()) + if err := reg.CreateAccount(®istry.Account{ID: "a-delete-fail", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + createTestStripeAccount(t, reg, "a-delete-fail", "msp_starter") + tenant, err := billing.ProvisionWorkspace(context.Background(), "a-delete-fail", "Original") + if err != nil { + t.Fatal(err) + } + p := &deletionMutationProvisioner{mutate: func(*registry.Tenant) error { + _ = billing.HandleMSPSubscriptionDeleted(context.Background(), cpstripe.Subscription{ID: "sub_deleted", Customer: "cus_test_a-delete-fail"}) + return fmt.Errorf("fixture teardown failed") + }} + req := httptest.NewRequest(http.MethodDelete, "/", nil) + req.SetPathValue("account_id", tenant.AccountID) + req.SetPathValue("tenant_id", tenant.ID) + res := httptest.NewRecorder() + HandleDeleteTenant(reg, p)(res, req) + if res.Code != http.StatusInternalServerError { + t.Fatalf("failed cleanup = %d", res.Code) + } + current, _ := reg.Get(tenant.ID) + if current.State != registry.TenantStateDeleting { + t.Fatalf("withdrawal erased failed-delete marker: %+v", current) + } + rows, err := reg.ListHostedEntitlements() + if err != nil || len(rows) != 1 || rows[0].RevokedAt == nil { + t.Fatalf("failed delete retained refresh authority: %v", err) + } +} + +func TestWorkspacePatchPreservesFailureAuditReasons(t *testing.T) { + for _, tc := range []struct { + name, body, reason string + status int + }{ + {"name", `{"display_name":" "}`, "invalid_display_name", http.StatusBadRequest}, + {"state", `{"state":"invalid"}`, "invalid_state", http.StatusBadRequest}, + {"body", `{`, "invalid_json_body", http.StatusBadRequest}, + {"missing", `{}`, "tenant_not_found", http.StatusNotFound}, + } { + t.Run(tc.name, func(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(®istry.Account{ID: "a-audit", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + tenant := ®istry.Tenant{ID: "t-audit", AccountID: "a-audit", State: registry.TenantStateActive} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPatch, "/", strings.NewReader(tc.body)) + req.SetPathValue("account_id", tenant.AccountID) + id := tenant.ID + if tc.name == "missing" { + id = "t-missing" + } + req.SetPathValue("tenant_id", id) + var output bytes.Buffer + old := log.Logger + log.Logger = zerolog.New(&output) + defer func() { log.Logger = old }() + res := httptest.NewRecorder() + HandleUpdateTenant(reg)(res, req) + if res.Code != tc.status { + t.Fatalf("status %d, want %d", res.Code, tc.status) + } + var event map[string]any + if err := json.Unmarshal(bytes.TrimSpace(output.Bytes()), &event); err != nil { + t.Fatalf("missing/invalid audit: %v", err) + } + if event["audit_event"] != "cp_tenant_update" || event["outcome"] != "failure" || event["reason"] != tc.reason || event["account_id"] != tenant.AccountID || event["tenant_id"] != id { + t.Fatalf("audit lost mutation attribution: %+v", event) + } + }) + } +} diff --git a/internal/cloudcp/registry/lifecycle.go b/internal/cloudcp/registry/lifecycle.go index 298c3963c4..ff6f1f233e 100644 --- a/internal/cloudcp/registry/lifecycle.go +++ b/internal/cloudcp/registry/lifecycle.go @@ -50,7 +50,7 @@ func (r *TenantRegistry) UpdateRuntimeState(t *Tenant) error { } func (r *TenantRegistry) SetTenantState(id string, state TenantState) error { - res, err := r.db.Exec(`UPDATE tenants SET state = ?, updated_at = ? WHERE id = ?`, string(state), time.Now().UTC().Unix(), id) + res, err := r.db.Exec(`UPDATE tenants SET state = CASE WHEN state IN ('deleting', 'deleted') THEN state ELSE ? END, updated_at = CASE WHEN state IN ('deleting', 'deleted') THEN updated_at ELSE ? END WHERE id = ?`, string(state), time.Now().UTC().Unix(), id) if err != nil { return err } diff --git a/internal/cloudcp/registry/models.go b/internal/cloudcp/registry/models.go index a36053200d..31ae933983 100644 --- a/internal/cloudcp/registry/models.go +++ b/internal/cloudcp/registry/models.go @@ -98,6 +98,7 @@ type Tenant struct { Email string `json:"email"` DisplayName string `json:"display_name"` State TenantState `json:"state"` + ManualHold bool `json:"-"` // account suspension, independent of billing withdrawal StripeCustomerID string `json:"stripe_customer_id"` StripeSubscriptionID string `json:"stripe_subscription_id"` StripePriceID string `json:"stripe_price_id"` diff --git a/internal/cloudcp/registry/registry.go b/internal/cloudcp/registry/registry.go index eee2b14638..6e9c034691 100644 --- a/internal/cloudcp/registry/registry.go +++ b/internal/cloudcp/registry/registry.go @@ -343,6 +343,9 @@ func (r *TenantRegistry) initSchema() error { return fmt.Errorf("migrate stripe_accounts: backfill grace_started_at: %w", err) } + if err := r.migrateTenantManualHolds(); err != nil { + return err + } return nil } @@ -630,12 +633,12 @@ func insertTenant(ctx context.Context, execer tenantInsertExecer, t *Tenant) err id, account_id, email, display_name, state, stripe_customer_id, stripe_subscription_id, stripe_price_id, plan_version, container_id, current_image_digest, desired_image_digest, - created_at, updated_at, last_health_check, health_check_ok - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + created_at, updated_at, last_health_check, health_check_ok, manual_hold + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `, t.ID, t.AccountID, t.Email, t.DisplayName, string(t.State), t.StripeCustomerID, t.StripeSubscriptionID, t.StripePriceID, t.PlanVersion, t.ContainerID, t.CurrentImageDigest, t.DesiredImageDigest, - t.CreatedAt.Unix(), t.UpdatedAt.Unix(), nullableTimeUnix(t.LastHealthCheck), boolToInt(t.HealthCheckOK), + t.CreatedAt.Unix(), t.UpdatedAt.Unix(), nullableTimeUnix(t.LastHealthCheck), boolToInt(t.HealthCheckOK), boolToInt(t.ManualHold), ) if err != nil { return err @@ -649,7 +652,7 @@ func (r *TenantRegistry) Get(tenantID string) (*Tenant, error) { id, account_id, email, display_name, state, stripe_customer_id, stripe_subscription_id, stripe_price_id, plan_version, container_id, current_image_digest, desired_image_digest, - created_at, updated_at, last_health_check, health_check_ok + created_at, updated_at, last_health_check, health_check_ok, manual_hold FROM tenants WHERE id = ?`, tenantID) return scanTenant(row) } @@ -660,7 +663,7 @@ func (r *TenantRegistry) GetByStripeCustomerID(customerID string) (*Tenant, erro id, account_id, email, display_name, state, stripe_customer_id, stripe_subscription_id, stripe_price_id, plan_version, container_id, current_image_digest, desired_image_digest, - created_at, updated_at, last_health_check, health_check_ok + created_at, updated_at, last_health_check, health_check_ok, manual_hold FROM tenants WHERE stripe_customer_id = ?`, customerID) return scanTenant(row) } @@ -724,7 +727,7 @@ func (r *TenantRegistry) List() ([]*Tenant, error) { id, account_id, email, display_name, state, stripe_customer_id, stripe_subscription_id, stripe_price_id, plan_version, container_id, current_image_digest, desired_image_digest, - created_at, updated_at, last_health_check, health_check_ok + created_at, updated_at, last_health_check, health_check_ok, manual_hold FROM tenants ORDER BY created_at DESC`) if err != nil { return nil, fmt.Errorf("list tenants: %w", err) @@ -739,7 +742,7 @@ func (r *TenantRegistry) ListByState(state TenantState) ([]*Tenant, error) { id, account_id, email, display_name, state, stripe_customer_id, stripe_subscription_id, stripe_price_id, plan_version, container_id, current_image_digest, desired_image_digest, - created_at, updated_at, last_health_check, health_check_ok + created_at, updated_at, last_health_check, health_check_ok, manual_hold FROM tenants WHERE state = ? ORDER BY created_at DESC`, string(state)) if err != nil { return nil, fmt.Errorf("list tenants by state: %w", err) @@ -754,7 +757,7 @@ func (r *TenantRegistry) ListByAccountID(accountID string) ([]*Tenant, error) { id, account_id, email, display_name, state, stripe_customer_id, stripe_subscription_id, stripe_price_id, plan_version, container_id, current_image_digest, desired_image_digest, - created_at, updated_at, last_health_check, health_check_ok + created_at, updated_at, last_health_check, health_check_ok, manual_hold FROM tenants WHERE account_id = ? ORDER BY created_at DESC`, accountID) if err != nil { return nil, fmt.Errorf("list tenants by account id: %w", err) @@ -839,13 +842,13 @@ func scanTenant(s scanner) (*Tenant, error) { var state string var createdAt, updatedAt int64 var lastHealthCheck sql.NullInt64 - var healthOK int + var healthOK, manualHold int err := s.Scan( &t.ID, &t.AccountID, &t.Email, &t.DisplayName, &state, &t.StripeCustomerID, &t.StripeSubscriptionID, &t.StripePriceID, &t.PlanVersion, &t.ContainerID, &t.CurrentImageDigest, &t.DesiredImageDigest, - &createdAt, &updatedAt, &lastHealthCheck, &healthOK, + &createdAt, &updatedAt, &lastHealthCheck, &healthOK, &manualHold, ) if err != nil { if err == sql.ErrNoRows { @@ -863,6 +866,7 @@ func scanTenant(s scanner) (*Tenant, error) { t.LastHealthCheck = &ts } t.HealthCheckOK = healthOK != 0 + t.ManualHold = manualHold != 0 return &t, nil } diff --git a/internal/cloudcp/registry/registry_test.go b/internal/cloudcp/registry/registry_test.go index 1b77f9d8cc..305a6c43c4 100644 --- a/internal/cloudcp/registry/registry_test.go +++ b/internal/cloudcp/registry/registry_test.go @@ -1,6 +1,10 @@ package registry import ( + "context" + "encoding/json" + "reflect" + "database/sql" "errors" "fmt" @@ -1596,3 +1600,203 @@ func TestRuntimeStatePatchPreservesWithdrawnAuthority(t *testing.T) { t.Fatal("missing runtime silently accepted") } } + +func TestTenantFieldPatchScopesAndPreservesUneditableFields(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(&Account{ID: "a-fields", Kind: AccountKindMSP}); err != nil { + t.Fatal(err) + } + when := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + tenant := &Tenant{ID: "t-fields", AccountID: "a-fields", DisplayName: "Original", State: TenantStateActive, Email: "owner@example.test", PlanVersion: "msp_max", StripeCustomerID: "cus_fields", StripeSubscriptionID: "sub_fields", StripePriceID: "price_fields", ContainerID: "runtime", CurrentImageDigest: "current", DesiredImageDigest: "desired", HealthCheckOK: true, LastHealthCheck: &when} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + name := "Renamed" + previous, current, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, &name, nil) + if err != nil { + t.Fatal(err) + } + if previous.DisplayName != "Original" || current.DisplayName != "Renamed" { + t.Fatalf("wrong snapshots: %+v %+v", previous, current) + } + old := *previous + old.DisplayName = current.DisplayName + old.UpdatedAt = current.UpdatedAt + if !reflect.DeepEqual(old, *current) { + t.Fatalf("editable field patch changed protected fields: %+v %+v", old, current) + } + if _, _, err := reg.PatchTenantForAccount(context.Background(), "a-other", tenant.ID, &name, nil); !errors.Is(err, ErrTenantNotFound) { + t.Fatalf("cross-account patch = %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, _, err := reg.PatchTenantForAccount(ctx, tenant.AccountID, tenant.ID, &name, nil); err == nil { + t.Fatal("canceled request committed") + } + if err := reg.SetTenantState(tenant.ID, TenantStateDeleted); err != nil { + t.Fatal(err) + } + if err := reg.SetTenantState(tenant.ID, TenantStateCanceled); err != nil { + t.Fatal(err) + } + current, _ = reg.Get(tenant.ID) + if current.State != TenantStateDeleted { + t.Fatalf("withdrawal erased deletion: %+v", current) + } +} + +func TestTenantManualHoldResumeUsesCurrentBillingAndKnownCause(t *testing.T) { + for _, tc := range []struct { + name string + kind AccountKind + customer string + accountCustomer string + billing string + hold bool + allowed bool + }{ + {"local_provider", AccountKindMSP, "", "", "", true, true}, + {"unconfigured_msp_missing", AccountKindMSP, "", "", "", true, false}, + {"individual_missing", AccountKindIndividual, "", "", "", true, false}, + {"billed_missing", AccountKindMSP, "cus_missing", "", "", true, false}, + {"mismatched_customer", AccountKindMSP, "cus_wrong", "cus_current", "active", true, false}, + {"current_paid", AccountKindMSP, "cus_current", "cus_current", "active", true, true}, + {"same_state_withdrawal", AccountKindMSP, "cus_current", "cus_current", "suspended", true, false}, + {"unknown_legacy", AccountKindMSP, "cus_current", "cus_current", "past_due", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(&Account{ID: "a-resume", Kind: tc.kind}); err != nil { + t.Fatal(err) + } + if tc.accountCustomer != "" { + if err := reg.CreateStripeAccount(&StripeAccount{AccountID: "a-resume", StripeCustomerID: tc.accountCustomer, SubscriptionState: tc.billing}); err != nil { + t.Fatal(err) + } + } + tenant := &Tenant{ID: "t-resume", AccountID: "a-resume", State: TenantStateSuspended, StripeCustomerID: tc.customer, ManualHold: tc.hold} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + suspend := TenantStateSuspended + if _, _, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, nil, &suspend); err != nil { + t.Fatal(err) + } + active := TenantStateActive + _, current, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, nil, &active, tc.name != "unconfigured_msp_missing") + if tc.allowed { + if err != nil || current.State != TenantStateActive || current.ManualHold { + t.Fatalf("manual resume failed: %+v %v", current, err) + } + } else if !errors.Is(err, ErrTenantStateConflict) { + t.Fatalf("unknown/nonpayable authority resumed: %+v %v", current, err) + } + }) + } +} + +func TestTenantManualHoldMigrationIsConservativeAndDurable(t *testing.T) { + dir := t.TempDir() + reg, err := NewTenantRegistry(dir) + if err != nil { + t.Fatal(err) + } + for _, kind := range []AccountKind{AccountKindMSP, AccountKindIndividual} { + if err := reg.CreateAccount(&Account{ID: string(kind), Kind: kind}); err != nil { + t.Fatal(err) + } + } + if err := reg.CreateAccount(&Account{ID: "paid", Kind: AccountKindMSP}); err != nil { + t.Fatal(err) + } + if err := reg.CreateStripeAccount(&StripeAccount{AccountID: "paid", StripeCustomerID: "cus_paid", SubscriptionState: "past_due"}); err != nil { + t.Fatal(err) + } + for _, tc := range []struct{ id, account, customer string }{{"local", "msp", ""}, {"individual", "individual", ""}, {"billed_without_record", "msp", "cus_missing"}, {"ambiguous_paid", "paid", "cus_paid"}} { + if err := reg.Create(&Tenant{ID: tc.id, AccountID: tc.account, StripeCustomerID: tc.customer, DisplayName: tc.id, State: TenantStateSuspended, ContainerID: "preserved", PlanVersion: "msp_starter"}); err != nil { + t.Fatal(err) + } + } + // Recreate exactly the pre-change application schema, retaining every other + // value. This is a bounded migration fixture, not a driver/crash experiment. + if _, err := reg.db.Exec(`ALTER TABLE tenants DROP COLUMN manual_hold`); err != nil { + t.Fatal(err) + } + if err := reg.Close(); err != nil { + t.Fatal(err) + } + for reopen := 0; reopen < 2; reopen++ { + reg, err = NewTenantRegistry(dir) + if err != nil { + t.Fatal(err) + } + for _, id := range []string{"local", "individual", "billed_without_record", "ambiguous_paid"} { + row, err := reg.Get(id) + if err != nil { + t.Fatal(err) + } + if row.ManualHold != (id == "local") || row.State != TenantStateSuspended || row.ContainerID != "preserved" || row.DisplayName != id { + t.Fatalf("migration inferred/replaced authority: %+v", row) + } + body, err := json.Marshal(row) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(body), "manual_hold") || strings.Contains(string(body), "ManualHold") { + t.Fatalf("private authority leaked to tenant JSON: %s", body) + } + } + if err := reg.Close(); err != nil { + t.Fatal(err) + } + } +} + +func TestTenantBillingGrantUsesCurrentHoldAndFieldOwnership(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(&Account{ID: "a-grant", Kind: AccountKindMSP}); err != nil { + t.Fatal(err) + } + tenant := &Tenant{ID: "t-grant", AccountID: "a-grant", State: TenantStateActive, DisplayName: "Original", ContainerID: "runtime", CurrentImageDigest: "image"} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + // Keep the old event snapshot while a current account edit changes both + // fields. The grant must consult persisted hold, not the old object's state. + old := *tenant + suspended := TenantStateSuspended + name := "Latest" + if _, _, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, &name, &suspended); err != nil { + t.Fatal(err) + } + current, applied, err := reg.ApplyTenantBillingGrant(context.Background(), old.AccountID, old.ID, "sub_new", "price_new", "msp_max") + if err != nil || !applied || current.State != TenantStateSuspended || !current.ManualHold || current.DisplayName != "Latest" || current.ContainerID != "runtime" || current.CurrentImageDigest != "image" || current.PlanVersion != "msp_max" { + t.Fatalf("stale billing grant replaced held/current fields: %+v %v %v", current, applied, err) + } +} + +func TestTenantManualResumeRefusesEmptyStoredBilling(t *testing.T) { + reg := newTestRegistry(t) + if err := reg.CreateAccount(&Account{ID: "a-empty", Kind: AccountKindMSP}); err != nil { + t.Fatal(err) + } + if err := reg.CreateStripeAccount(&StripeAccount{AccountID: "a-empty", StripeCustomerID: "cus_empty", SubscriptionState: "active"}); err != nil { + t.Fatal(err) + } + if err := reg.Create(&Tenant{ID: "t-empty", AccountID: "a-empty", State: TenantStateSuspended, ManualHold: true}); err != nil { + t.Fatal(err) + } + // Constructors intentionally default a new empty state to trial. This is + // an actually empty legacy saved value, not construction of a new trial. + if _, err := reg.db.Exec(`UPDATE stripe_accounts SET subscription_state = '' WHERE account_id = ?`, "a-empty"); err != nil { + t.Fatal(err) + } + active := TenantStateActive + if _, _, err := reg.PatchTenantForAccount(context.Background(), "a-empty", "t-empty", nil, &active); !errors.Is(err, ErrTenantStateConflict) { + t.Fatalf("empty saved billing recreated authority: %v", err) + } + row, _ := reg.Get("t-empty") + if row.State != TenantStateSuspended || !row.ManualHold { + t.Fatalf("empty billing changed hold: %+v", row) + } +} diff --git a/internal/cloudcp/registry/tenant_fields.go b/internal/cloudcp/registry/tenant_fields.go new file mode 100644 index 0000000000..82047f76e1 --- /dev/null +++ b/internal/cloudcp/registry/tenant_fields.go @@ -0,0 +1,217 @@ +package registry + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing" +) + +var ( + ErrTenantNotFound = errors.New("tenant not found") + ErrTenantStateConflict = errors.New("tenant state does not allow this change") +) + +// IsTenantDeletionState identifies rows whose runtime must not be reactivated +// by account edits or later billing events. Billing/account metadata may remain. +func IsTenantDeletionState(state TenantState) bool { + return state == TenantStateDeleting || state == TenantStateDeleted +} + +const accountTenantSelect = `SELECT id, account_id, email, display_name, state, + stripe_customer_id, stripe_subscription_id, stripe_price_id, plan_version, + container_id, current_image_digest, desired_image_digest, created_at, updated_at, + last_health_check, health_check_ok, manual_hold FROM tenants WHERE account_id = ? AND id = ?` + +// mutateAccountTenant takes the same short write transaction used by workspace +// creation. It snapshots current fields for the response/audit, never a request's +// pre-body snapshot. The runtime lease remains the caller's responsibility; a +// billing withdrawal need not take that lease and is ordered by this write. +func (r *TenantRegistry) mutateAccountTenant(ctx context.Context, accountID, tenantID string, mutate func(*sql.Conn, *Tenant) error) (*Tenant, *Tenant, error) { + conn, err := r.db.Conn(ctx) + if err != nil { + return nil, nil, err + } + defer conn.Close() + if _, err := conn.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil { + return nil, nil, err + } + committed := false + defer func() { + if !committed { + _, _ = conn.ExecContext(context.Background(), "ROLLBACK") + } + }() + previous, err := scanTenant(conn.QueryRowContext(ctx, accountTenantSelect, accountID, tenantID)) + if err != nil { + return nil, nil, err + } + if previous == nil { + return nil, nil, ErrTenantNotFound + } + if err := mutate(conn, previous); err != nil { + return nil, nil, err + } + current, err := scanTenant(conn.QueryRowContext(ctx, accountTenantSelect, accountID, tenantID)) + if err != nil { + return nil, nil, err + } + if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil { + return nil, nil, err + } + committed = true + return previous, current, nil +} + +// PatchTenantForAccount changes only account-editable fields. The entire patch +// is rejected if its state transition is no longer valid; a rename alone can +// never rewrite billing, health, runtime identity or a concurrent withdrawal. +func (r *TenantRegistry) PatchTenantForAccount(ctx context.Context, accountID, tenantID string, displayName *string, state *TenantState, localMSPBilling ...bool) (*Tenant, *Tenant, error) { + return r.mutateAccountTenant(ctx, accountID, tenantID, func(conn *sql.Conn, current *Tenant) error { + if IsTenantDeletionState(current.State) { + return ErrTenantStateConflict + } + name, next, hold := current.DisplayName, current.State, current.ManualHold + if displayName != nil { + name = strings.TrimSpace(*displayName) + if name == "" { + return fmt.Errorf("invalid display name") + } + } + if state != nil { + if (*state != TenantStateActive && *state != TenantStateSuspended) || (current.State != TenantStateActive && current.State != TenantStateSuspended) { + return ErrTenantStateConflict + } + next = *state + if next == TenantStateSuspended { + hold = current.ManualHold || current.State == TenantStateActive + } else { + hold = false + } + if current.State == TenantStateSuspended && next == TenantStateActive { + if !current.ManualHold { + return ErrTenantStateConflict + } + allowed, err := canResumeAccountTenant(ctx, conn, current, len(localMSPBilling) > 0 && localMSPBilling[0]) + if err != nil { + return err + } + if !allowed { + return ErrTenantStateConflict + } + } + } + _, err := conn.ExecContext(ctx, `UPDATE tenants SET display_name = ?, state = ?, manual_hold = ?, updated_at = ? WHERE account_id = ? AND id = ?`, name, string(next), boolToInt(hold), time.Now().UTC().Unix(), accountID, tenantID) + return err + }) +} + +func canResumeAccountTenant(ctx context.Context, conn *sql.Conn, tenant *Tenant, localMSPBilling bool) (bool, error) { + var customer, storedState string + err := conn.QueryRowContext(ctx, `SELECT stripe_customer_id, subscription_state FROM stripe_accounts WHERE account_id = ?`, tenant.AccountID).Scan(&customer, &storedState) + if errors.Is(err, sql.ErrNoRows) { + if !localMSPBilling { + return false, nil + } + // Configured MSP control planes have no Stripe identity. Missing billing for + // a billed tenant is unknown authority, not permission to resume it. + if tenant.StripeCustomerID != "" || tenant.StripeSubscriptionID != "" || tenant.StripePriceID != "" { + return false, nil + } + var kind AccountKind + if err := conn.QueryRowContext(ctx, `SELECT kind FROM accounts WHERE id = ?`, tenant.AccountID).Scan(&kind); err != nil { + return false, err + } + return kind == AccountKindMSP, nil + } + if err != nil { + return false, err + } + if tenant.StripeCustomerID != "" && tenant.StripeCustomerID != customer { + return false, nil + } + return pkglicensing.ShouldGrantPaidCapabilities(pkglicensing.ParseStoredSubscriptionState(storedState)), nil +} + +// BeginTenantDeletionForAccount withdraws the current row without rewriting any +// of its other fields. Retrying an interrupted deletion is allowed; completed +// deletion is idempotent and never becomes deleting again. +func (r *TenantRegistry) BeginTenantDeletionForAccount(ctx context.Context, accountID, tenantID string) (*Tenant, *Tenant, error) { + return r.mutateAccountTenant(ctx, accountID, tenantID, func(conn *sql.Conn, current *Tenant) error { + if IsTenantDeletionState(current.State) { + return nil + } + _, err := conn.ExecContext(ctx, `UPDATE tenants SET state = ?, updated_at = ? WHERE account_id = ? AND id = ?`, string(TenantStateDeleting), time.Now().UTC().Unix(), accountID, tenantID) + return err + }) +} + +// FinalizeTenantDeletionForAccount clears only the runtime being deprovisioned. +// In particular it cannot restore old billing/display/health metadata captured +// before a slow container operation. +func (r *TenantRegistry) FinalizeTenantDeletionForAccount(ctx context.Context, accountID, tenantID string) (*Tenant, *Tenant, error) { + return r.mutateAccountTenant(ctx, accountID, tenantID, func(conn *sql.Conn, current *Tenant) error { + if current.State == TenantStateDeleted { + return nil + } + if current.State != TenantStateDeleting { + return ErrTenantStateConflict + } + _, err := conn.ExecContext(ctx, `UPDATE tenants SET state = ?, container_id = '', updated_at = ? WHERE account_id = ? AND id = ?`, string(TenantStateDeleted), time.Now().UTC().Unix(), accountID, tenantID) + return err + }) +} + +// This additive migration only infers a legacy manual hold for local MSP +// clients with no billing identity. Old stored past_due conflated grace with +// paused/unknown billing, so a paid legacy suspension has unknown cause: do not +// manufacture resume authority from it. A fresh granting billing event can +// reconcile it; subsequent deliberate suspensions carry their own hold. +func (r *TenantRegistry) migrateTenantManualHolds() error { + has, err := r.tenantsHasColumn("manual_hold") + if err != nil || has { + return err + } + tx, err := r.db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.Exec(`ALTER TABLE tenants ADD COLUMN manual_hold INTEGER NOT NULL DEFAULT 0`); err != nil { + return err + } + if _, err := tx.Exec(`UPDATE tenants SET manual_hold = 1 + WHERE state = 'suspended' AND stripe_customer_id = '' AND stripe_subscription_id = '' AND stripe_price_id = '' + AND NOT EXISTS (SELECT 1 FROM stripe_accounts sa WHERE sa.account_id = tenants.account_id) + AND EXISTS (SELECT 1 FROM accounts a WHERE a.id = tenants.account_id AND a.kind = 'msp')`); err != nil { + return err + } + return tx.Commit() +} + +// ApplyTenantBillingGrant writes only billing-owned fields and derives the +// effective lifecycle from the current manual hold. Its caller must hold the +// billing-authority and runtime leases; it cannot recover incomplete/deleted +// runtimes or restore a stale display/runtime snapshot. +func (r *TenantRegistry) ApplyTenantBillingGrant(ctx context.Context, accountID, tenantID, subscriptionID, priceID, planVersion string) (*Tenant, bool, error) { + applied := false + _, current, err := r.mutateAccountTenant(ctx, accountID, tenantID, func(conn *sql.Conn, current *Tenant) error { + switch current.State { + case TenantStateActive, TenantStateSuspended, TenantStateCanceled: + default: + return nil + } + next := TenantStateActive + if current.ManualHold { + next = TenantStateSuspended + } + _, err := conn.ExecContext(ctx, `UPDATE tenants SET state = ?, stripe_subscription_id = ?, stripe_price_id = ?, plan_version = ?, updated_at = ? WHERE account_id = ? AND id = ?`, string(next), subscriptionID, priceID, canonicalizeRegistryPlanVersion(planVersion), time.Now().UTC().Unix(), accountID, tenantID) + applied = err == nil + return err + }) + return current, applied, err +} diff --git a/internal/cloudcp/routes.go b/internal/cloudcp/routes.go index bec2de8175..8dcea85fa0 100644 --- a/internal/cloudcp/routes.go +++ b/internal/cloudcp/routes.go @@ -256,7 +256,7 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) { workspaceLimitPolicy.ProviderMSPLicenseLapsed = func() bool { return deps.Config.ProviderMSPLicenseLapsed(time.Now()) } } createTenant := account.HandleCreateTenantWithWorkspaceLimitPolicy(deps.Registry, provisioner, workspaceLimitPolicy) - updateTenant := account.HandleUpdateTenant(deps.Registry) + updateTenant := account.HandleUpdateTenantWithPolicy(deps.Registry, account.TenantMutationPolicy{LocalMSPBilling: deps.Config.IsMSPControlPlane()}, provisioner) deleteTenant := account.HandleDeleteTenant(deps.Registry, provisioner) tenantsCollection := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/cloudcp/routes_test.go b/internal/cloudcp/routes_test.go index 30bb63e099..753fce48dc 100644 --- a/internal/cloudcp/routes_test.go +++ b/internal/cloudcp/routes_test.go @@ -1,11 +1,18 @@ package cloudcp import ( + "crypto/ed25519" + "crypto/rand" + "encoding/base64" "encoding/json" + cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth" + "github.com/rcourtman/pulse-go-rewrite/internal/config" "net/http" "net/http/httptest" + "path/filepath" "strings" "testing" + "time" "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry" ) @@ -517,3 +524,143 @@ func TestNewHostedEntitlementsService_MarksProviderHosting(t *testing.T) { t.Fatal("Pulse-hosted control plane must not be marked provider-hosted") } } + +func TestRegisterRoutesManualResumeReconcilesBillingAndKeepsAccountRoles(t *testing.T) { + dir := t.TempDir() + reg, err := registry.NewTenantRegistry(dir) + if err != nil { + t.Fatal(err) + } + defer reg.Close() + if err := reg.CreateAccount(®istry.Account{ID: "a-route-resume", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + for _, role := range []registry.MemberRole{registry.MemberRoleOwner, registry.MemberRoleReadOnly} { + if err := reg.CreateUser(®istry.User{ID: string(role), Email: string(role) + "@example.test"}); err != nil { + t.Fatal(err) + } + if err := reg.CreateMembership(®istry.AccountMembership{AccountID: "a-route-resume", UserID: string(role), Role: role}); err != nil { + t.Fatal(err) + } + } + if err := reg.CreateStripeAccount(®istry.StripeAccount{AccountID: "a-route-resume", StripeCustomerID: "cus_route", SubscriptionState: "active", PlanVersion: "msp_starter"}); err != nil { + t.Fatal(err) + } + tenant := ®istry.Tenant{ID: "t-route-resume", AccountID: "a-route-resume", State: registry.TenantStateSuspended, ManualHold: true, PlanVersion: "msp_starter"} + if err := reg.Create(tenant); err != nil { + t.Fatal(err) + } + _, private, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + session, err := cpauth.NewService(dir) + if err != nil { + t.Fatal(err) + } + defer session.Close() + cfg := &CPConfig{DataDir: dir, BaseURL: "https://cloud.example.com", AdminKey: "fixture-only", TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(private)} + mux := http.NewServeMux() + RegisterRoutes(mux, &Deps{Config: cfg, Registry: reg, MagicLinks: session}) + for _, role := range []registry.MemberRole{registry.MemberRoleReadOnly, registry.MemberRoleOwner} { + token, err := session.GenerateSessionToken(string(role), string(role)+"@example.test", time.Hour) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPatch, "https://cloud.example.com/api/accounts/"+tenant.AccountID+"/tenants/"+tenant.ID, strings.NewReader(`{"state":"active"}`)) + req.AddCookie(&http.Cookie{Name: cpauth.SessionCookieName, Value: token}) + res := httptest.NewRecorder() + mux.ServeHTTP(res, req) + if role == registry.MemberRoleReadOnly { + if res.Code != http.StatusForbidden { + t.Fatalf("reader reached resume: %d %s", res.Code, res.Body.String()) + } + continue + } + if res.Code != http.StatusOK { + t.Fatalf("registered resume: %d %s", res.Code, res.Body.String()) + } + } + state, err := config.NewFileBillingStore(filepath.Join(cfg.TenantsDir(), tenant.ID)).GetBillingState("default") + if err != nil { + t.Fatal(err) + } + if state == nil || state.EntitlementJWT == "" || state.EntitlementRefreshToken == "" { + t.Fatal("registered resume reported success without current billing lease") + } +} + +func TestRegisterRoutesResumeUsesConfiguredBillingMode(t *testing.T) { + for _, mode := range []ControlPlaneMode{ControlPlaneModePulseHosted, ControlPlaneModePulseHostedMSP, ControlPlaneModeProviderHostedMSP} { + t.Run(string(mode), func(t *testing.T) { + dir := t.TempDir() + reg, err := registry.NewTenantRegistry(dir) + if err != nil { + t.Fatal(err) + } + defer reg.Close() + if err := reg.CreateAccount(®istry.Account{ID: "a-mode", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + if err := reg.CreateUser(®istry.User{ID: "u-mode", Email: "owner@example.test"}); err != nil { + t.Fatal(err) + } + if err := reg.CreateMembership(®istry.AccountMembership{AccountID: "a-mode", UserID: "u-mode", Role: registry.MemberRoleOwner}); err != nil { + t.Fatal(err) + } + if err := reg.Create(®istry.Tenant{ID: "t-mode", AccountID: "a-mode", State: registry.TenantStateSuspended, ManualHold: true, PlanVersion: "msp_starter"}); err != nil { + t.Fatal(err) + } + _, private, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + session, err := cpauth.NewService(dir) + if err != nil { + t.Fatal(err) + } + defer session.Close() + cfg := &CPConfig{DataDir: dir, BaseURL: "https://cloud.example.com", AdminKey: "fixture-only", ControlPlaneMode: mode, TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(private)} + mux := http.NewServeMux() + RegisterRoutes(mux, &Deps{Config: cfg, Registry: reg, MagicLinks: session}) + token, err := session.GenerateSessionToken("u-mode", "owner@example.test", time.Hour) + if err != nil { + t.Fatal(err) + } + patch := func(body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPatch, "https://cloud.example.com/api/accounts/a-mode/tenants/t-mode", strings.NewReader(body)) + req.AddCookie(&http.Cookie{Name: cpauth.SessionCookieName, Value: token}) + res := httptest.NewRecorder() + mux.ServeHTTP(res, req) + return res + } + res := patch(`{"state":"active"}`) + want := http.StatusConflict + if cfg.IsMSPControlPlane() { + want = http.StatusOK + } + if res.Code != want { + t.Fatalf("mode %s resume = %d %s, want %d", mode, res.Code, res.Body.String(), want) + } + row, err := reg.Get("t-mode") + if err != nil { + t.Fatal(err) + } + if cfg.IsMSPControlPlane() { + if row.State != registry.TenantStateActive || row.ManualHold { + t.Fatalf("configured local resume lost: %+v", row) + } + if _, err := config.NewFileBillingStore(filepath.Join(cfg.TenantsDir(), row.ID)).GetBillingState("default"); err != nil { + t.Fatal(err) + } + } else { + if row.State != registry.TenantStateSuspended || !row.ManualHold { + t.Fatalf("missing hosted billing recreated authority: %+v", row) + } + if again := patch(`{"state":"active","local_msp_billing":true}`); again.Code == http.StatusOK { + t.Fatal("request field configured local billing authority") + } + } + }) + } +} diff --git a/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go b/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go index bd14cab977..8751368b59 100644 --- a/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go +++ b/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go @@ -1,6 +1,9 @@ package stripe import ( + "fmt" + "reflect" + "bytes" "context" "errors" @@ -754,3 +757,122 @@ func TestCloudLifecycle_WorkspaceLimitEnforcement(t *testing.T) { t.Fatalf("workspace count after blocked creation = %d, want 1", countAfter) } } + +func TestSubscriptionEventsPreserveDeletionAndManualSuspension(t *testing.T) { + for _, state := range []registry.TenantState{registry.TenantStateActive, registry.TenantStateSuspended, registry.TenantStateCanceled, registry.TenantStateDeleting, registry.TenantStateDeleted, registry.TenantStateFailed, registry.TenantStateProvisioning} { + t.Run(string(state), func(t *testing.T) { + reg := newStripeTestRegistry(t) + dir := t.TempDir() + p := newTestProvisioner(t, reg, dir, nil, true) + if err := reg.CreateAccount(®istry.Account{ID: "a-single", Kind: registry.AccountKindIndividual}); err != nil { + t.Fatal(err) + } + if err := reg.CreateStripeAccount(®istry.StripeAccount{AccountID: "a-single", StripeCustomerID: "cus_single", PlanVersion: "cloud_starter", SubscriptionState: "active"}); err != nil { + t.Fatal(err) + } + tenant, err := p.ProvisionWorkspace(context.Background(), "a-single", "Original") + if err != nil { + t.Fatal(err) + } + tenant.StripeCustomerID = "cus_single" + if err := reg.Update(tenant); err != nil { + t.Fatal(err) + } + if state == registry.TenantStateSuspended { + s := state + if _, _, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, nil, &s); err != nil { + t.Fatal(err) + } + } else if err := reg.SetTenantState(tenant.ID, state); err != nil { + t.Fatal(err) + } + if err := reg.RevokeHostedEntitlement(tenant.ID, time.Now().UTC()); err != nil { + t.Fatal(err) + } + old, err := reg.ListHostedEntitlements() + if err != nil { + t.Fatal(err) + } + sub := Subscription{ID: "sub_new", Customer: "cus_single", Status: "active", Metadata: map[string]string{"plan_version": "cloud_power"}} + if err := p.HandleSubscriptionUpdated(context.Background(), sub); err != nil { + t.Fatal(err) + } + current, err := reg.Get(tenant.ID) + if err != nil { + t.Fatal(err) + } + want := state + if state == registry.TenantStateCanceled { + want = registry.TenantStateActive + } + if current.State != want { + t.Fatalf("billing changed protected state: %+v want %s", current, want) + } + if state == registry.TenantStateDeleting || state == registry.TenantStateDeleted || state == registry.TenantStateFailed || state == registry.TenantStateProvisioning { + rows, err := reg.ListHostedEntitlements() + if err != nil || !reflect.DeepEqual(old, rows) { + t.Fatalf("billing recreated authority: %+v %+v %v", old, rows, err) + } + } + if registry.IsTenantDeletionState(state) { + if err := p.HandleSubscriptionDeleted(context.Background(), sub); err != nil { + t.Fatal(err) + } + current, _ = reg.Get(tenant.ID) + if current.State != state { + t.Fatalf("withdrawal erased deletion: %+v", current) + } + } + }) + } +} + +func TestPausedSubscriptionCannotBeManuallyResumed(t *testing.T) { + for _, msp := range []bool{false, true} { + t.Run(fmt.Sprint(msp), func(t *testing.T) { + reg := newStripeTestRegistry(t) + p := newTestProvisioner(t, reg, t.TempDir(), nil, true) + kind := registry.AccountKindIndividual + if msp { + kind = registry.AccountKindMSP + } + if err := reg.CreateAccount(®istry.Account{ID: "a-pause", Kind: kind}); err != nil { + t.Fatal(err) + } + if err := reg.CreateStripeAccount(®istry.StripeAccount{AccountID: "a-pause", StripeCustomerID: "cus_pause", PlanVersion: "msp_starter", SubscriptionState: "active"}); err != nil { + t.Fatal(err) + } + tenant, err := p.ProvisionWorkspace(context.Background(), "a-pause", "Original") + if err != nil { + t.Fatal(err) + } + if !msp { + tenant.StripeCustomerID = "cus_pause" + if err := reg.Update(tenant); err != nil { + t.Fatal(err) + } + } + suspended := registry.TenantStateSuspended + if _, _, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, nil, &suspended); err != nil { + t.Fatal(err) + } + sub := Subscription{ID: "sub_pause", Customer: "cus_pause", Status: "paused"} + if msp { + err = p.HandleMSPSubscriptionUpdated(context.Background(), sub) + } else { + err = p.HandleSubscriptionUpdated(context.Background(), sub) + } + if err != nil { + t.Fatal(err) + } + sa, err := reg.GetStripeAccount(tenant.AccountID) + if err != nil || sa.SubscriptionState != "suspended" { + t.Fatalf("pause stored as payable: %+v %v", sa, err) + } + active := registry.TenantStateActive + if _, _, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, nil, &active); !errors.Is(err, registry.ErrTenantStateConflict) { + t.Fatalf("same-state withdrawal was resumed: %v", err) + } + }) + } +} diff --git a/internal/cloudcp/stripe/helpers_test.go b/internal/cloudcp/stripe/helpers_test.go index 81b958f0cb..73f6822b95 100644 --- a/internal/cloudcp/stripe/helpers_test.go +++ b/internal/cloudcp/stripe/helpers_test.go @@ -1,6 +1,8 @@ package stripe import ( + pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing" + "context" "net/url" "strings" @@ -283,3 +285,17 @@ func TestGenerateAndLogPortalMagicLinkIssuesPortalTargetedToken(t *testing.T) { t.Fatalf("token email=%q, want %q", validated.Email, "owner@example.com") } } + +func TestStoredSubscriptionNormalizationNeverWidensAuthority(t *testing.T) { + for _, raw := range []string{"active", "trialing", "past_due", "unpaid", "canceled", "paused", "incomplete", "incomplete_expired", "unknown_status", "", " ACTIVE "} { + stored := normalizeStripeAccountSubscriptionState(raw) + parsed := pkglicensing.ParseStoredSubscriptionState(stored) + want := MapSubscriptionStatus(raw) + if parsed != want { + t.Fatalf("%q stored as %q = %q, want %q", raw, stored, parsed, want) + } + if ShouldGrantCapabilities(parsed) != ShouldGrantCapabilities(want) { + t.Fatalf("%q widened billing authority", raw) + } + } +} diff --git a/internal/cloudcp/stripe/msp_lifecycle_integration_test.go b/internal/cloudcp/stripe/msp_lifecycle_integration_test.go index 868bce8363..dfd00cba64 100644 --- a/internal/cloudcp/stripe/msp_lifecycle_integration_test.go +++ b/internal/cloudcp/stripe/msp_lifecycle_integration_test.go @@ -1,6 +1,11 @@ package stripe import ( + "errors" + "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/entitlements" + "reflect" + "time" + "bytes" "context" "encoding/json" @@ -973,3 +978,111 @@ func loadRawBillingState(t *testing.T, tenantDataDir string) pkglicensing.Billin } return state } + +func TestMSPBillingEventsPreserveDeletedAndManuallyHeldClients(t *testing.T) { + for _, tc := range []struct { + name string + state registry.TenantState + hold bool + grant bool + }{ + {"active", registry.TenantStateActive, false, true}, + {"billing_suspended", registry.TenantStateSuspended, false, true}, + {"manual_suspended", registry.TenantStateSuspended, true, true}, + {"canceled", registry.TenantStateCanceled, false, true}, + {"manual_and_canceled", registry.TenantStateCanceled, true, true}, + {"deleting", registry.TenantStateDeleting, false, false}, + {"deleted", registry.TenantStateDeleted, false, false}, + {"failed", registry.TenantStateFailed, false, false}, + {"provisioning", registry.TenantStateProvisioning, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + reg := newStripeTestRegistry(t) + dir := t.TempDir() + p := newTestProvisioner(t, reg, dir, nil, true) + if err := reg.CreateAccount(®istry.Account{ID: "a-events", Kind: registry.AccountKindMSP}); err != nil { + t.Fatal(err) + } + if err := reg.CreateStripeAccount(®istry.StripeAccount{AccountID: "a-events", StripeCustomerID: "cus_events", PlanVersion: "msp_starter", SubscriptionState: "active"}); err != nil { + t.Fatal(err) + } + tenant, err := p.ProvisionWorkspace(context.Background(), "a-events", "Original") + if err != nil { + t.Fatal(err) + } + if tc.hold { + state := registry.TenantStateSuspended + if _, _, err := reg.PatchTenantForAccount(context.Background(), tenant.AccountID, tenant.ID, nil, &state); err != nil { + t.Fatal(err) + } + } + if err := reg.SetTenantState(tenant.ID, tc.state); err != nil { + t.Fatal(err) + } + if err := reg.RevokeHostedEntitlement(tenant.ID, time.Now().UTC()); err != nil { + t.Fatal(err) + } + oldRows, err := reg.ListHostedEntitlements() + if err != nil { + t.Fatal(err) + } + oldBilling, err := os.ReadFile(filepath.Join(dir, tenant.ID, "billing.json")) + if err != nil { + t.Fatal(err) + } + sub := Subscription{ID: "sub_renewed", Customer: "cus_events", Status: "active", Metadata: map[string]string{"plan_version": "msp_max"}} + if err := p.HandleMSPSubscriptionUpdated(context.Background(), sub); err != nil { + t.Fatal(err) + } + current, err := reg.Get(tenant.ID) + if err != nil { + t.Fatal(err) + } + want := tc.state + if tc.grant { + want = registry.TenantStateActive + if tc.hold { + want = registry.TenantStateSuspended + } + } + if current.State != want || current.ManualHold != tc.hold { + t.Fatalf("billing overrode runtime lifecycle: %+v want %s hold %v", current, want, tc.hold) + } + if !tc.grant { + newRows, err := reg.ListHostedEntitlements() + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(oldRows, newRows) { + t.Fatalf("renewal recreated excluded authority: %+v %+v", oldRows, newRows) + } + billing, err := os.ReadFile(filepath.Join(dir, tenant.ID, "billing.json")) + if err != nil || !bytes.Equal(oldBilling, billing) { + t.Fatalf("renewal rewrote excluded runtime billing: %v", err) + } + } + if tc.hold { + rows, err := reg.ListHostedEntitlements() + if err != nil { + t.Fatal(err) + } + if _, err := p.hostedEntitlements.RefreshEntitlement(rows[0].RefreshToken, "fixture.invalid"); !errors.Is(err, entitlements.ErrHostedEntitlementInactive) { + t.Fatalf("manually held row refreshed: %v", err) + } + } + sa, err := reg.GetStripeAccount(tenant.AccountID) + if err != nil || sa.PlanVersion != "msp_max" || sa.SubscriptionState != "active" { + t.Fatalf("terminal client blocked account billing continuity: %+v %v", sa, err) + } + if registry.IsTenantDeletionState(tc.state) { + if err := p.HandleMSPSubscriptionDeleted(context.Background(), sub); err != nil { + t.Fatal(err) + } + current, _ = reg.Get(tenant.ID) + if current.State != tc.state { + t.Fatalf("withdrawal erased deletion: %+v", current) + } + } + }) + } +} diff --git a/internal/cloudcp/stripe/provisioner.go b/internal/cloudcp/stripe/provisioner.go index 99793f8d86..8e3e5e4b26 100644 --- a/internal/cloudcp/stripe/provisioner.go +++ b/internal/cloudcp/stripe/provisioner.go @@ -865,18 +865,11 @@ func (p *Provisioner) HandleCheckout(ctx context.Context, session CheckoutSessio } func normalizeStripeAccountSubscriptionState(status string) string { - switch strings.ToLower(strings.TrimSpace(status)) { - case "active": - return "active" - case "trialing": - return "trial" - case "canceled": - return "canceled" - case "past_due", "unpaid", "paused", "incomplete", "incomplete_expired": - return "past_due" - default: + state := MapSubscriptionStatus(status) + if state == pkglicensing.SubStateGrace { return "past_due" } + return string(state) } func applyStripeAccountGraceWindow(sa *registry.StripeAccount, subState pkglicensing.SubscriptionState, now time.Time) { @@ -1104,19 +1097,9 @@ func (p *Provisioner) HandleSubscriptionUpdated(ctx context.Context, sub Subscri } planVersion = canonicalizeProvisionedPlanVersion(planVersion) - // Update registry - tenant.StripeSubscriptionID = strings.TrimSpace(sub.ID) - tenant.StripePriceID = priceID - tenant.PlanVersion = planVersion - if subState == pkglicensing.SubStateSuspended { - tenant.State = registry.TenantStateSuspended - } else if subState == pkglicensing.SubStateActive || subState == pkglicensing.SubStateTrial || subState == pkglicensing.SubStateGrace { - tenant.State = registry.TenantStateActive - } else if subState == pkglicensing.SubStateCanceled || subState == pkglicensing.SubStateExpired { - tenant.State = registry.TenantStateCanceled - } - if err := p.registry.Update(tenant); err != nil { - return fmt.Errorf("update tenant record: %w", err) + tenant, canGrant, err := p.registry.ApplyTenantBillingGrant(ctx, tenant.AccountID, tenant.ID, strings.TrimSpace(sub.ID), priceID, planVersion) + if err != nil { + return fmt.Errorf("update tenant billing: %w", err) } if sa, saErr := p.registry.GetStripeAccountByCustomerID(customerID); saErr == nil && sa != nil { @@ -1132,6 +1115,12 @@ func (p *Provisioner) HandleSubscriptionUpdated(ctx context.Context, sub Subscri Msg("Failed to update stripe account mapping after subscription update") } } + if !canGrant { + return nil + } + if tenant.ManualHold { + subState = pkglicensing.SubStateSuspended + } if err := p.writeHostedEntitlementLeaseState(tenant, subState, planVersion, customerID, strings.TrimSpace(sub.ID), priceID); err != nil { return fmt.Errorf("write hosted entitlement state for tenant %s: %w", tenant.ID, err) } @@ -1171,12 +1160,6 @@ func (p *Provisioner) withdrawSubscription(ctx context.Context, sub Subscription if tenant == nil { return nil } - if err := p.registry.SetTenantState(tenant.ID, withdrawnTenantState(state)); err != nil { - return err - } - if err := p.hostedEntitlements.RevokeTenantEntitlement(tenant.ID, time.Now().UTC()); err != nil { - return err - } if sa, err := p.registry.GetStripeAccountByCustomerID(customerID); err != nil { return err } else if sa != nil { @@ -1187,11 +1170,20 @@ func (p *Provisioner) withdrawSubscription(ctx context.Context, sub Subscription return err } } + if err := p.registry.SetTenantState(tenant.ID, withdrawnTenantState(state)); err != nil { + return err + } + if err := p.hostedEntitlements.RevokeTenantEntitlement(tenant.ID, time.Now().UTC()); err != nil { + return err + } ctx, lease, tenant, err := p.lockTenant(ctx, tenant.ID) if err != nil { return fmt.Errorf("authority withdrawn; billing file deferred: %w", err) } defer lease.Close() + if registry.IsTenantDeletionState(tenant.State) { + return nil + } return p.writeHostedEntitlementLeaseState(tenant, state, tenant.PlanVersion, customerID, strings.TrimSpace(sub.ID), "") } @@ -1290,19 +1282,20 @@ func (p *Provisioner) HandleMSPSubscriptionUpdated(ctx context.Context, sub Subs if tenant == nil { continue } - tenant.PlanVersion = planVersion - switch subState { - case pkglicensing.SubStateSuspended: - tenant.State = registry.TenantStateSuspended - case pkglicensing.SubStateCanceled, pkglicensing.SubStateExpired: - tenant.State = registry.TenantStateCanceled - default: - tenant.State = registry.TenantStateActive + current, canGrant, err := p.registry.ApplyTenantBillingGrant(ctx, tenant.AccountID, tenant.ID, tenant.StripeSubscriptionID, tenant.StripePriceID, planVersion) + if err != nil { + return fmt.Errorf("update tenant billing: %w", err) } - if err := p.registry.Update(tenant); err != nil { - return fmt.Errorf("update tenant record: %w", err) + if !canGrant { + continue } - if err := p.writeHostedEntitlementLeaseState(tenant, subState, planVersion, customerID, strings.TrimSpace(sub.ID), priceID); err != nil { + tenant = current + effective := subState + if tenant.ManualHold { + effective = pkglicensing.SubStateSuspended + } + + if err := p.writeHostedEntitlementLeaseState(tenant, effective, planVersion, customerID, strings.TrimSpace(sub.ID), priceID); err != nil { return fmt.Errorf("write hosted entitlement state for tenant %s: %w", tenant.ID, err) } } @@ -1385,6 +1378,9 @@ func (p *Provisioner) withdrawMSPSubscription(ctx context.Context, sub Subscript return fmt.Errorf("authority withdrawn; billing file deferred: %w", err) } defer lease.Close() + if registry.IsTenantDeletionState(current.State) { + return nil + } return p.writeHostedEntitlementLeaseState(current, state, current.PlanVersion, customerID, strings.TrimSpace(sub.ID), "") }(); err != nil { problems = append(problems, err) @@ -1442,3 +1438,52 @@ func (p *Provisioner) lockAccountTenants(ctx context.Context, accountID string) } return current, release, nil } + +// ResumeWorkspaceBilling completes an explicit manual resume with the same +// current billing authority as refresh. The account handler holds both leases +// through its field patch and this local file/token reconciliation. The local +// billing policy is the same server-owned configuration passed to the registry, +// never a request field or an inference from missing billing. It performs +// no external call and cannot restore a nonpayable or terminal tenant. +func (p *Provisioner) ResumeWorkspaceBilling(ctx context.Context, tenant *registry.Tenant, localMSPBilling bool) error { + if p == nil || tenant == nil { + return fmt.Errorf("workspace billing is unavailable") + } + ctx, lease, current, err := p.lockTenant(ctx, tenant.ID) + if err != nil { + return err + } + defer lease.Close() + if current.AccountID != tenant.AccountID || current.State != registry.TenantStateActive || current.ManualHold { + return fmt.Errorf("workspace is not resumable") + } + sa, err := p.registry.GetStripeAccount(current.AccountID) + if err != nil { + return err + } + state := pkglicensing.SubStateActive + customer, subscription, price := current.StripeCustomerID, current.StripeSubscriptionID, current.StripePriceID + if sa != nil { + state = pkglicensing.ParseStoredSubscriptionState(sa.SubscriptionState) + customer, subscription = sa.StripeCustomerID, sa.StripeSubscriptionID + } + if sa == nil { + if !localMSPBilling { + return fmt.Errorf("workspace billing authority is unavailable") + } + account, err := p.registry.GetAccount(current.AccountID) + if err != nil { + return err + } + if account == nil || account.Kind != registry.AccountKindMSP || current.StripeCustomerID != "" || current.StripeSubscriptionID != "" || current.StripePriceID != "" { + return fmt.Errorf("workspace billing authority is unavailable") + } + } else if current.StripeCustomerID != "" && current.StripeCustomerID != sa.StripeCustomerID { + return fmt.Errorf("workspace billing identity changed") + } + + if !ShouldGrantCapabilities(state) { + return fmt.Errorf("workspace subscription is inactive") + } + return p.writeHostedEntitlementLeaseState(current, state, current.PlanVersion, customer, subscription, price) +}