From efb5d3ad0ed0d005ab4f3ead05962111d7a4c1e6 Mon Sep 17 00:00:00 2001 From: Yasith Jayawardana Date: Fri, 20 Nov 2026 12:48:34 -0500 Subject: [PATCH] Derive access from status --- api/core.openapi.yaml | 68 ++++++++++++++++- .../handler/request_person_merge.go | 15 ++-- .../request_person_merge_integration_test.go | 24 +++++- .../COmanage/Identity-Provisioner/README.md | 2 + .../internal/operations/compose.go | 25 +++++++ .../internal/operations/mocks_test.go | 2 + .../operations/remove_posix_account.go | 56 ++++++++++++-- .../operations/remove_posix_account_test.go | 42 +++++++++++ .../internal/subscribers/cluster_user.go | 69 +++++++++++++++-- .../internal/subscribers/cluster_user_test.go | 57 ++++++++++++++ .../notify/notifier_integration_test.go | 2 +- docs/Allocation-Data-Models.md | 2 +- docs/storage.md | 5 +- internal/db/migrations/000001_identity.up.sql | 3 +- internal/server/allocation.go | 28 +++++++ internal/server/allocation_membership.go | 1 + internal/server/compute_cluster.go | 1 + internal/server/server.go | 1 + internal/store/compute_cluster_user_store.go | 23 +++--- internal/store/store.go | 9 ++- internal/store/user_store.go | 6 +- pkg/events/compute_cluster_user_subscribe.go | 6 ++ pkg/events/types.go | 1 + pkg/models/project.go | 9 +-- pkg/service/compute_allocation.go | 33 +++++++++ pkg/service/compute_allocation_membership.go | 3 + ...ation_resource_mapping_integration_test.go | 33 +++++++++ pkg/service/compute_cluster_user.go | 3 + .../compute_cluster_user_integration_test.go | 49 ++++++++++++ pkg/service/identity_resolver.go | 2 +- .../identity_resolver_integration_test.go | 14 +++- pkg/service/storage_integration_test.go | 31 ++++++-- pkg/service/user.go | 66 ++++++++++++----- pkg/service/user_merge.go | 49 ++++++++---- pkg/service/user_merge_integration_test.go | 74 ++++++++++++++++--- pkg/service/user_onboard_integration_test.go | 2 +- .../__tests__/AllocationMembersTab.test.tsx | 10 +-- .../core/allocations/__tests__/api.test.ts | 12 +-- web/src/features/core/allocations/api.ts | 10 ++- .../components/AllocationDetail.tsx | 46 ++++++++---- .../components/AllocationMembersTab.tsx | 19 +++-- web/src/features/core/allocations/queries.ts | 21 ++++-- .../__tests__/ProjectMembersTab.test.tsx | 17 ++++- .../projects/components/ProjectMembersTab.tsx | 10 ++- .../core/users/components/UserStatusBadge.tsx | 1 - web/src/mocks/handlers/allocations.ts | 19 +++++ 46 files changed, 830 insertions(+), 151 deletions(-) diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml index ca814148e..af40db2a6 100644 --- a/api/core.openapi.yaml +++ b/api/core.openapi.yaml @@ -1134,14 +1134,12 @@ definitions: - PENDING - ACTIVE - INACTIVE - - SUSPENDED - MERGED type: string x-enum-varnames: - UserPending - UserActive - UserInactive - - UserSuspended - UserMerged UserType: enum: @@ -2603,6 +2601,13 @@ paths: error: type: string type: object + "409": + description: Conflict + schema: + properties: + error: + type: string + type: object security: - BearerAuth: [] summary: Delete a compute allocation membership @@ -3292,6 +3297,13 @@ paths: error: type: string type: object + "409": + description: Conflict + schema: + properties: + error: + type: string + type: object security: - BearerAuth: [] summary: Delete a compute allocation @@ -3649,6 +3661,51 @@ paths: summary: Update a compute allocation -> resource mapping tags: - Compute Allocation Resources + /compute-allocations/{id}/status: + put: + consumes: + - application/json + parameters: + - description: Compute allocation ID + in: path + name: id + required: true + type: string + - description: Status patch + in: body + name: request + required: true + schema: + properties: + status: + $ref: '#/definitions/AllocationStatus' + type: object + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/ComputeAllocation' + "400": + description: Bad Request + schema: + properties: + error: + type: string + type: object + "404": + description: Not Found + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Update a compute allocation's status + tags: + - Compute Allocations /compute-allocations/{id}/usages: get: description: Callers without the allocations read privilege must hold a membership @@ -3851,6 +3908,13 @@ paths: error: type: string type: object + "409": + description: Conflict + schema: + properties: + error: + type: string + type: object security: - BearerAuth: [] summary: Delete a compute cluster user diff --git a/connectors/ACCESS/AMIE-Processor/handler/request_person_merge.go b/connectors/ACCESS/AMIE-Processor/handler/request_person_merge.go index 149b92875..cc5e34cc1 100644 --- a/connectors/ACCESS/AMIE-Processor/handler/request_person_merge.go +++ b/connectors/ACCESS/AMIE-Processor/handler/request_person_merge.go @@ -128,17 +128,20 @@ func (h *RequestPersonMergeHandler) Handle(ctx context.Context, tx *sql.Tx, pack if err != nil { return fmt.Errorf("request_person_merge: list retiring cluster accounts: %w", err) } - // The retiring person can have a request_account_create packet whose reply - // is held until their cluster account is approved. The merge moves that - // account to the survivor, or deletes it when the survivor already has one - // on the cluster. If it is deleted, the held reply waits on an account that - // no longer exists, so it would never be sent. + survivorAccounts, err := h.svc.ListComputeClusterUsersByUser(ctx, survivor.ID) + if err != nil { + return fmt.Errorf("request_person_merge: list survivor cluster accounts: %w", err) + } + // Either person can have a request_account_create packet whose reply is held + // until their cluster account is approved. On a cluster where both have an + // account, the merge deletes the unprovisioned one. If it is deleted, the + // held reply waits on an account that no longer exists, so it would never be sent. // // So those packets are processed again after the merge. The merge moves the // retiring person's ACCESS identity to the survivor, so the handler finds the // survivor's account. It replies at once if that account is approved, or // holds the reply on it until an admin reviews it. - for _, account := range retiringAccounts { + for _, account := range append(retiringAccounts, survivorAccounts...) { if err := h.eventStore.ReprocessPacketsHeldFor(ctx, tx, account.ID); err != nil { return fmt.Errorf("request_person_merge: reprocess packets held for %s: %w", account.ID, err) } diff --git a/connectors/ACCESS/AMIE-Processor/handler/request_person_merge_integration_test.go b/connectors/ACCESS/AMIE-Processor/handler/request_person_merge_integration_test.go index d8559dc19..c1c831351 100644 --- a/connectors/ACCESS/AMIE-Processor/handler/request_person_merge_integration_test.go +++ b/connectors/ACCESS/AMIE-Processor/handler/request_person_merge_integration_test.go @@ -551,16 +551,32 @@ func TestRequestPersonMerge_ReplyFailurePropagates(t *testing.T) { // to be processed again, since the merge deletes that account when the // survivor already has one on the same cluster. func TestRequestPersonMerge_ReprocessesPacketsHeldOnRetiringAccount(t *testing.T) { + testReprocessesPacketsHeldOnDroppedAccount(t, false) +} + +// Make sure the survivor's held packet is processed again when the merge drops its account for the retiring one, which is provisioned. +func TestRequestPersonMerge_ReprocessesPacketsHeldOnSurvivorAccount(t *testing.T) { + testReprocessesPacketsHeldOnDroppedAccount(t, true) +} + +func testReprocessesPacketsHeldOnDroppedAccount(t *testing.T, retiringProvisioned bool) { database := setupTestDB(t) seed := seedMergeUsers(t, database) - var retiringAccount string - if err := database.Get(&retiringAccount, "SELECT id FROM compute_cluster_users WHERE user_id = $1", seed.retiringID); err != nil { - t.Fatalf("read retiring cluster account: %v", err) + droppedOwner := seed.retiringID + if retiringProvisioned { + droppedOwner = seed.survivingID + if _, err := database.Exec("UPDATE compute_cluster_users SET provisioned_at = now() WHERE user_id = $1", seed.retiringID); err != nil { + t.Fatalf("provision retiring cluster account: %v", err) + } + } + var droppedAccount string + if err := database.Get(&droppedAccount, "SELECT id FROM compute_cluster_users WHERE user_id = $1", droppedOwner); err != nil { + t.Fatalf("read dropped cluster account: %v", err) } held := insertPacket(t, database, "request_account_create", baseRACBody()) if _, err := database.Exec("UPDATE amie_packets SET status = $1, held_reply = '{}', held_for = $2 WHERE id = $3", - model.PacketStatusWaitingApproval, retiringAccount, held.ID); err != nil { + model.PacketStatusWaitingApproval, droppedAccount, held.ID); err != nil { t.Fatalf("hold packet: %v", err) } eventID := uuid.NewString() diff --git a/connectors/COmanage/Identity-Provisioner/README.md b/connectors/COmanage/Identity-Provisioner/README.md index e9ee6f071..ae858f951 100644 --- a/connectors/COmanage/Identity-Provisioner/README.md +++ b/connectors/COmanage/Identity-Provisioner/README.md @@ -33,6 +33,7 @@ The connector subscribes to core events for one cluster, `provisioning.custos_cl |---|---| | `compute_cluster_user::approve` | Provision the account, join the admin group for an `ADMIN` account, then sync the user's allocation groups | | `user::onboarded` | Provision again once the user has signed in, so the registry gets their OIDC `sub` | +| `compute_cluster_user::update` | Provision the account while its user is `ACTIVE`; otherwise update its status in the registry, leave the admin group, then sync the user's allocation groups | | `compute_cluster_user::delete` | Remove an approved account from the registry, then sync the user's allocation groups | | `compute_allocation::create` and `::update`; `compute_allocation_membership::create`, `::update` and `::delete` | Sync the allocation's group | | `compute_allocation::delete` | Delete the allocation's group | @@ -118,6 +119,7 @@ Each audit row the connector writes goes to the core `audit_events` table with ` | `ComanageOIDCLinkageCreated` | Step 4 added the `oidcsub` identifier. | | `ComanageClusterAccountAttached` | Step 10 finished. `details` is `comanage_id= username= uid=`. | | `ComanageClusterAdminGroupJoined` | An `ADMIN` account joined the admin group. | +| `ComanageClusterAccountUpdated` | The account's status was updated in the registry after its user left `ACTIVE`. `details` is `comanage_id= username= status=S`. | | `ComanageClusterAccountRemoved` | A deleted account was removed from the registry. | | `ComanageAllocationGroupCreated` | An active allocation's CoGroup was created. | | `ComanageAllocationGroupMemberAdded` | A provisioned, active member was added to an allocation's CoGroup. | diff --git a/connectors/COmanage/Identity-Provisioner/internal/operations/compose.go b/connectors/COmanage/Identity-Provisioner/internal/operations/compose.go index 8458ddee6..9a95873eb 100644 --- a/connectors/COmanage/Identity-Provisioner/internal/operations/compose.go +++ b/connectors/COmanage/Identity-Provisioner/internal/operations/compose.go @@ -18,6 +18,7 @@ package operations import ( + "cmp" "encoding/json" "fmt" ) @@ -91,6 +92,30 @@ func removeLogin(composite json.RawMessage, username string) ([]byte, bool, erro return out, account || ident, nil } +// deactivateUnixClusterAccount sets this username's UnixClusterAccount status to "S" and reports whether it changed. +func deactivateUnixClusterAccount(composite json.RawMessage, username string) ([]byte, bool, error) { + var top map[string]json.RawMessage + var person struct{ UnixClusterAccount []map[string]json.RawMessage } + if err := cmp.Or(json.Unmarshal(composite, &top), json.Unmarshal(composite, &person)); err != nil { + return nil, false, fmt.Errorf("decode composite: %w", err) + } + changed := false + for _, a := range person.UnixClusterAccount { + var name, current string + _ = json.Unmarshal(a["username"], &name) + _ = json.Unmarshal(a["status"], ¤t) + if name == username && current != "S" { + a["status"], changed = json.RawMessage(`"S"`), true + } + } + if !changed { + return nil, false, nil + } + top["UnixClusterAccount"], _ = json.Marshal(person.UnixClusterAccount) + out, err := json.Marshal(top) + return out, err == nil, err +} + // dropEntries removes the matching entries of one composite array and reports // whether any matched. func dropEntries(top map[string]json.RawMessage, key string, match func(map[string]json.RawMessage) bool) (bool, error) { diff --git a/connectors/COmanage/Identity-Provisioner/internal/operations/mocks_test.go b/connectors/COmanage/Identity-Provisioner/internal/operations/mocks_test.go index 7b2b62449..303efd97e 100644 --- a/connectors/COmanage/Identity-Provisioner/internal/operations/mocks_test.go +++ b/connectors/COmanage/Identity-Provisioner/internal/operations/mocks_test.go @@ -158,6 +158,8 @@ func mockComanageServer(t *testing.T, reg *mockRegistry) *httptest.Server { _, _ = io.WriteString(w, `{"ResponseType":"CoGroups","Version":"1.0","CoGroups":[`+strings.Join(groups, ",")+`]}`) case r.Method == http.MethodPost && strings.HasSuffix(path, "/co_groups.json"): _, _ = io.WriteString(w, `{"ResponseType":"NewObject","Version":"1.0","ObjectType":"CoGroup","Id":"55"}`) + case r.Method == http.MethodGet && strings.HasSuffix(path, "/identifiers.json") && r.URL.Query().Has("copersonid"): + _, _ = io.WriteString(w, `{"ResponseType":"Identifiers","Version":"1.0","Identifiers":[{"Identifier":"Person100099","Type":"comanage_id"}]}`) case r.Method == http.MethodGet && strings.HasSuffix(path, "/identifiers.json"): _, _ = io.WriteString(w, `{"ResponseType":"Identifiers","Version":"1.0","Identifiers":[]}`) case r.Method == http.MethodPost && strings.HasSuffix(path, "/identifiers.json"): diff --git a/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account.go b/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account.go index 22582efd6..24fa80a76 100644 --- a/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account.go +++ b/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account.go @@ -19,6 +19,7 @@ package operations import ( "context" + "encoding/json" "errors" "fmt" @@ -54,7 +55,7 @@ func (o *Orchestrator) RemoveClusterAccount(ctx context.Context, cu *models.Comp return err } if personID != "" { - if err := o.removeAccountFromPerson(ctx, cu, personID, composite); err != nil { + if err := o.removeAccountFromPerson(ctx, cu, personID, composite, removeLogin); err != nil { return err } } @@ -74,10 +75,11 @@ func (o *Orchestrator) RemoveClusterAccount(ctx context.Context, cu *models.Comp return nil } -// removeAccountFromPerson takes the cluster account, its login name and the -// admin group membership off the person. The person record itself stays. -func (o *Orchestrator) removeAccountFromPerson(ctx context.Context, cu *models.ComputeClusterUser, personID string, composite []byte) error { - body, changed, err := removeLogin(composite, cu.LocalUsername) +// removeAccountFromPerson applies edit to the person's cluster account and +// takes the admin group membership off the person. The person record itself stays. +func (o *Orchestrator) removeAccountFromPerson(ctx context.Context, cu *models.ComputeClusterUser, personID string, composite []byte, + edit func(json.RawMessage, string) ([]byte, bool, error)) error { + body, changed, err := edit(composite, cu.LocalUsername) if err != nil { return err } @@ -116,6 +118,50 @@ func (o *Orchestrator) removeAccountFromPerson(ctx context.Context, cu *models.C return nil } +// DeactivateClusterAccount sets the person's cluster account status to "S" and takes them out of the admin group; the account stays. +func (o *Orchestrator) DeactivateClusterAccount(ctx context.Context, cu *models.ComputeClusterUser) error { + personID, composite, err := o.findAccountCoPerson(ctx, cu) + if err != nil || personID == "" { + return err + } + if err := o.removeAccountFromPerson(ctx, cu, personID, composite, deactivateUnixClusterAccount); err != nil { + return err + } + o.audit(ctx, cu, "ComanageClusterAccountUpdated", fmt.Sprintf("comanage_id=%s username=%s status=S", personID, cu.LocalUsername)) + return nil +} + +// findAccountCoPerson returns the person holding the account, "" if none. +// A merge moves the stored person id off the retiring user, so the member of the account's primary group comes first. +func (o *Orchestrator) findAccountCoPerson(ctx context.Context, cu *models.ComputeClusterUser) (string, []byte, error) { + groupID, err := o.c.FindCoGroupByName(cu.LocalUsername) + if err != nil { + return "", nil, fmt.Errorf("find primary group: %w", err) + } + if groupID != 0 { + // A primary group has one member unless provisioning was retried against another person. + members, err := o.c.ListCoGroupMembers(groupID) + if err != nil { + return "", nil, err + } + if len(members) > 0 { + personID, err := o.c.FindIdentifierValueOnPerson(members[0].Person.Id, o.c.Config().PersonIDType) + if err != nil { + return "", nil, err + } + if personID != "" { + composite, err := o.c.GetPersonComposite(personID) + return personID, composite, err + } + } + } + user, err := o.core.GetUser(ctx, cu.UserID) + if err != nil { + return "", nil, fmt.Errorf("get Custos user: %w", err) + } + return o.findCoPerson(ctx, user) +} + // ignoreNotFound treats a delete of something already deleted as done. func ignoreNotFound(err error) error { if errors.Is(err, client.ErrNotFound) { diff --git a/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account_test.go b/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account_test.go index 49359bad9..399a1cb8b 100644 --- a/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account_test.go +++ b/connectors/COmanage/Identity-Provisioner/internal/operations/remove_posix_account_test.go @@ -23,6 +23,7 @@ import ( "strings" "testing" + "github.com/apache/airavata-custos/connectors/COmanage/Identity-Provisioner/internal/client" "github.com/apache/airavata-custos/pkg/models" ) @@ -81,3 +82,44 @@ func TestRemoveClusterAccount_SecondRunChangesNothing(t *testing.T) { t.Errorf("expected no writes, got %d updates and deletes %v", len(reg.put), reg.deleted) } } + +// Make sure deactivating suspends the account, keeps it and its group, and takes an admin out of the admin group. +func TestDeactivateClusterAccount_SuspendsTheAccount(t *testing.T) { + reg := &mockRegistry{account: "jdoe", userGroup: 55, adminGroup: adminGroupID, adminMember: true} + srv := mockComanageServer(t, reg) + defer srv.Close() + core := adminCore() + + cu := &models.ComputeClusterUser{ID: "ccu-1", UserID: "user-1", LocalUsername: "jdoe", AccessLevel: models.ClusterAccessAdmin} + if err := newOrchestratorForTest(t, srv, core, adminGroupName).DeactivateClusterAccount(context.Background(), cu); err != nil { + t.Fatalf("DeactivateClusterAccount: %v", err) + } + + if len(reg.put) != 1 || !strings.Contains(string(reg.put[0]), `"username":"jdoe"`) || !strings.Contains(string(reg.put[0]), `"status":"S"`) { + t.Errorf("expected one person update suspending jdoe, got %d: %s", len(reg.put), reg.put) + } + if want := []string{"/co_group_members/9.json"}; !slices.Equal(reg.deleted, want) { + t.Errorf("deleted = %v, want %v", reg.deleted, want) + } + if !hasAudit(core, "ComanageClusterAccountUpdated") { + t.Error("no ComanageClusterAccountUpdated audit event") + } +} + +// Make sure the person is found through the account's primary group when the +// user holds no stored person id, as the retiring user of a merge does. +func TestDeactivateClusterAccount_FindsThePersonThroughThePrimaryGroup(t *testing.T) { + reg := &mockRegistry{account: "jdoe", userGroup: 55, members: []client.CoGroupMemberListOne{{CoGroupId: 55, Person: client.IdentifierParent{Id: 42}}}} + srv := mockComanageServer(t, reg) + defer srv.Close() + core := &fakeCore{user: &models.User{ID: "user-1"}} + + cu := &models.ComputeClusterUser{ID: "ccu-1", UserID: "user-1", LocalUsername: "jdoe"} + if err := newOrchestratorForTest(t, srv, core, adminGroupName).DeactivateClusterAccount(context.Background(), cu); err != nil { + t.Fatalf("DeactivateClusterAccount: %v", err) + } + + if len(reg.put) != 1 || !strings.Contains(string(reg.put[0]), `"status":"S"`) { + t.Errorf("expected one person update suspending jdoe, got %d: %s", len(reg.put), reg.put) + } +} diff --git a/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go b/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go index 023bde2b5..1ad242375 100644 --- a/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go +++ b/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go @@ -34,9 +34,9 @@ import ( "github.com/apache/airavata-custos/pkg/service" ) -// Subscriber drives the orchestrator from three events, -// ComputeClusterUserApproveEvent, ComputeClusterUserDeleteEvent, and UserOnboardedEvent. -// Both are ignored if the user doesn't have a cluster account on `CustosClusterID`. +// Subscriber drives the orchestrator from four events, ComputeClusterUserApproveEvent, +// ComputeClusterUserUpdateEvent, ComputeClusterUserDeleteEvent, and UserOnboardedEvent. +// Each is ignored if the user doesn't have a cluster account on `CustosClusterID`. type Subscriber struct { ops provisioner bus *events.Bus @@ -48,6 +48,7 @@ type Subscriber struct { type provisioner interface { EnsureClusterAccount(ctx context.Context, cu *models.ComputeClusterUser) error RemoveClusterAccount(ctx context.Context, cu *models.ComputeClusterUser) error + DeactivateClusterAccount(ctx context.Context, cu *models.ComputeClusterUser) error EnsureClusterAdminMembership(ctx context.Context, cu *models.ComputeClusterUser) error EnsureAllocationGroup(ctx context.Context, a *models.ComputeAllocation) error RemoveAllocationGroup(ctx context.Context, a *models.ComputeAllocation) error @@ -68,6 +69,7 @@ func (s *Subscriber) RegisterSubscribers(subscriber string) { // Whichever of the `approve event` and the `onboarded event` comes second starts it. s.bus.SubscribeComputeClusterUserApproved(subscriber, s.handleClusterUserApproved) s.bus.SubscribeComputeClusterUserDeleted(subscriber, s.handleClusterUserDeleted) + s.bus.SubscribeComputeClusterUserUpdated(subscriber, s.handleClusterUserUpdated) s.bus.SubscribeUserOnboarded(subscriber, s.handleUserOnboarded) s.bus.SubscribeComputeAllocationCreated(subscriber, s.handleComputeAllocationChanged) @@ -78,6 +80,54 @@ func (s *Subscriber) RegisterSubscribers(subscriber string) { s.bus.SubscribeComputeAllocationMembershipDeleted(subscriber, s.handleMembershipChanged) } +// handleClusterUserUpdated provisions the account of an ACTIVE user, and otherwise updates its status and leaves its allocation groups. +func (s *Subscriber) handleClusterUserUpdated(ctx context.Context, req models.ComputeClusterUser) error { + if req.ComputeClusterID != s.custosClusterID { + return nil + } + cu, err := s.core.GetComputeClusterUser(ctx, req.ID) + if errors.Is(err, service.ErrNotFound) { + return nil + } + if err != nil { + return err + } + active, err := s.isUserActive(ctx, cu.UserID) + if err != nil { + return err + } + if active { + return s.handleClusterUserApproved(ctx, *cu) + } + ctx = audit.WithSource(ctx, "comanage") + ctx, span := tracing.Start(ctx, "comanage.cluster_user_updated") + defer span.End() + if err := s.ops.DeactivateClusterAccount(ctx, cu); err != nil { + return err + } + return s.syncUserAllocations(ctx, cu.UserID) +} + +// ensureClusterAccount provisions the account, then suspends it if its user left ACTIVE meanwhile. +func (s *Subscriber) ensureClusterAccount(ctx context.Context, cu *models.ComputeClusterUser) error { + if err := s.ops.EnsureClusterAccount(ctx, cu); err != nil { + return err + } + if active, err := s.isUserActive(ctx, cu.UserID); err != nil || active { + return err + } + return s.ops.DeactivateClusterAccount(ctx, cu) +} + +// isUserActive re-reads the user, so a retried event sees a status change made since it was published. +func (s *Subscriber) isUserActive(ctx context.Context, userID string) (bool, error) { + u, err := s.core.GetUser(ctx, userID) + if errors.Is(err, service.ErrNotFound) { + return false, nil + } + return err == nil && u.Status == models.UserActive, err +} + // handleClusterUserDeleted removes the account from the registry. // An account that was never approved was never sent there, so it is skipped. func (s *Subscriber) handleClusterUserDeleted(ctx context.Context, cu models.ComputeClusterUser) error { @@ -113,7 +163,10 @@ func (s *Subscriber) handleUserOnboarded(ctx context.Context, user models.User) slog.ErrorContext(ctx, "comanage subscriber: cluster user lookup failed", "user_id", user.ID, "err", err) return err } - if err := s.ops.EnsureClusterAccount(ctx, cu); err != nil { + if active, err := s.isUserActive(ctx, user.ID); err != nil || !active { + return err + } + if err := s.ensureClusterAccount(ctx, cu); err != nil { span.RecordError(err) span.SetStatus(codes.Error, err.Error()) slog.ErrorContext(ctx, "comanage subscriber: EnsurePOSIXAccount failed after onboarding", "compute_cluster_user_id", cu.ID, "user_id", user.ID, "err", err) @@ -137,6 +190,12 @@ func (s *Subscriber) handleClusterUserApproved(ctx context.Context, cu models.Co if cu.ComputeClusterID != s.custosClusterID { return nil } + // A retry of a suspend that failed after provisioning lands here too. + if active, err := s.isUserActive(ctx, cu.UserID); err != nil { + return err + } else if !active { + return s.ops.DeactivateClusterAccount(ctx, &cu) + } span.SetAttributes( attribute.String("comanage.cluster_user_id", cu.ID), attribute.String("comanage.user_id", cu.UserID), @@ -165,7 +224,7 @@ func (s *Subscriber) handleClusterUserApproved(ctx context.Context, cu models.Co }) // TODO: move to a transactional scope. In-process delivery loses events // if the process crashes between the core commit and subscriber pickup. - if err := s.ops.EnsureClusterAccount(ctx, &cu); err != nil { + if err := s.ensureClusterAccount(ctx, &cu); err != nil { span.RecordError(err) span.SetStatus(codes.Error, err.Error()) slog.ErrorContext(ctx, "comanage subscriber: EnsurePOSIXAccount failed", "compute_cluster_user_id", cu.ID, "user_id", cu.UserID, "err", err) diff --git a/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user_test.go b/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user_test.go index 9f0c82560..d6c83c90c 100644 --- a/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user_test.go +++ b/connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user_test.go @@ -30,6 +30,7 @@ import ( type fakeOps struct { provisioned []string admins []string + deactivated []string } func (f *fakeOps) EnsureClusterAccount(_ context.Context, cu *models.ComputeClusterUser) error { @@ -37,6 +38,10 @@ func (f *fakeOps) EnsureClusterAccount(_ context.Context, cu *models.ComputeClus return nil } func (f *fakeOps) RemoveClusterAccount(context.Context, *models.ComputeClusterUser) error { return nil } +func (f *fakeOps) DeactivateClusterAccount(_ context.Context, cu *models.ComputeClusterUser) error { + f.deactivated = append(f.deactivated, cu.ID) + return nil +} func (f *fakeOps) EnsureClusterAdminMembership(_ context.Context, cu *models.ComputeClusterUser) error { f.admins = append(f.admins, cu.ID) return nil @@ -48,6 +53,10 @@ func (f *fakeOps) RemoveAllocationGroup(context.Context, *models.ComputeAllocati return nil } +func activeUser(_ context.Context, id string) (*models.User, error) { + return &models.User{ID: id, Status: models.UserActive}, nil +} + func approveWith(t *testing.T, oidc *models.UserIdentity) (*fakeOps, []models.AuditEvent) { t.Helper() var audits []models.AuditEvent @@ -58,6 +67,7 @@ func approveWith(t *testing.T, oidc *models.UserIdentity) (*fakeOps, []models.Au return e, nil }, ListAllocationsForUserFunc: func(context.Context, string) ([]models.ComputeAllocationMembership, error) { return nil, nil }, + GetUserFunc: activeUser, } ops := &fakeOps{} s := &Subscriber{ops: ops, core: core, custosClusterID: "c1"} @@ -98,6 +108,7 @@ func TestUserOnboarded_JoinsAdminGroupOnlyForApprovedAdminAccounts(t *testing.T) return &models.ComputeClusterUser{ID: "cu1", UserID: "u1", ComputeClusterID: "c1", AccessLevel: level, ApprovalStatus: approval}, nil }, ListAllocationsForUserFunc: func(context.Context, string) ([]models.ComputeAllocationMembership, error) { return nil, nil }, + GetUserFunc: activeUser, } ops := &fakeOps{} s := &Subscriber{ops: ops, core: core, custosClusterID: "c1"} @@ -120,3 +131,49 @@ func TestUserOnboarded_JoinsAdminGroupOnlyForApprovedAdminAccounts(t *testing.T) t.Fatalf("pending admin account: admin group calls = %v, want none", ops.admins) } } + +// Make sure an account provisioned while its user left ACTIVE is suspended again. +func TestClusterUserApproved_SuspendsWhenUserLeftActiveDuringProvisioning(t *testing.T) { + reads := 0 + core := &service.CoreServiceMock{ + GetOIDCIdentityFunc: func(context.Context, string) (*models.UserIdentity, error) { + return &models.UserIdentity{OIDCSub: "sub-1"}, nil + }, + CreateAuditEventFunc: func(_ context.Context, e *models.AuditEvent) (*models.AuditEvent, error) { return e, nil }, + ListAllocationsForUserFunc: func(context.Context, string) ([]models.ComputeAllocationMembership, error) { return nil, nil }, + GetUserFunc: func(_ context.Context, id string) (*models.User, error) { + reads++ + if reads > 1 { + return &models.User{ID: id, Status: models.UserInactive}, nil + } + return activeUser(context.Background(), id) + }, + } + ops := &fakeOps{} + s := &Subscriber{ops: ops, core: core, custosClusterID: "c1"} + cu := models.ComputeClusterUser{ID: "cu1", UserID: "u1", ComputeClusterID: "c1", ApprovalStatus: models.ClusterAccountApproved} + if err := s.handleClusterUserApproved(context.Background(), cu); err != nil { + t.Fatal(err) + } + if len(ops.provisioned) != 1 || len(ops.deactivated) != 1 { + t.Fatalf("provisioned = %v, deactivated = %v, want one of each", ops.provisioned, ops.deactivated) + } +} + +// Make sure an approve event for a user who is not ACTIVE suspends the account, so a retry finishes a failed suspend. +func TestClusterUserApproved_SuspendsWhenUserIsNotActive(t *testing.T) { + core := &service.CoreServiceMock{ + GetUserFunc: func(_ context.Context, id string) (*models.User, error) { + return &models.User{ID: id, Status: models.UserInactive}, nil + }, + } + ops := &fakeOps{} + s := &Subscriber{ops: ops, core: core, custosClusterID: "c1"} + cu := models.ComputeClusterUser{ID: "cu1", UserID: "u1", ComputeClusterID: "c1", ApprovalStatus: models.ClusterAccountApproved} + if err := s.handleClusterUserApproved(context.Background(), cu); err != nil { + t.Fatal(err) + } + if len(ops.provisioned) != 0 || len(ops.deactivated) != 1 { + t.Fatalf("provisioned = %v, deactivated = %v, want only a suspend", ops.provisioned, ops.deactivated) + } +} diff --git a/connectors/Notification/Email/internal/notify/notifier_integration_test.go b/connectors/Notification/Email/internal/notify/notifier_integration_test.go index bb328019a..7429c3e1e 100644 --- a/connectors/Notification/Email/internal/notify/notifier_integration_test.go +++ b/connectors/Notification/Email/internal/notify/notifier_integration_test.go @@ -83,7 +83,7 @@ func TestNotifier_SendsOneEmailPerAccountEvent(t *testing.T) { t.Fatal(err) } newUser := func(first, username string) string { - user, err := svc.CreateUser(ctx, &models.User{OrganizationID: org.ID, FirstName: first, LastName: "Doe", Email: username + "@example.edu"}) + user, err := svc.CreateUser(ctx, &models.User{OrganizationID: org.ID, FirstName: first, LastName: "Doe", Email: username + "@example.edu", Status: models.UserActive}) if err != nil { t.Fatal(err) } diff --git a/docs/Allocation-Data-Models.md b/docs/Allocation-Data-Models.md index 75d2f2a0b..69affc4af 100644 --- a/docs/Allocation-Data-Models.md +++ b/docs/Allocation-Data-Models.md @@ -35,7 +35,7 @@ as a diff. ## Users, organizations and projects A **User** belongs to an **Organization** and is identified by name and email. A user's `status` is `PENDING`, -`ACTIVE`, `INACTIVE`, `SUSPENDED` or `MERGED`. +`ACTIVE`, `INACTIVE` or `MERGED`. A **Project** groups one or more compute allocations (and, in the future, storage allocations) under a single umbrella. Projects carry an `Origination` field indicating the source system (ACCESS, NAIRR, XRAS, etc.) and a corresponding `OriginatedID` for cross-referencing. A project's `status` is `ACTIVE`, `INACTIVE` or `DELETED`. diff --git a/docs/storage.md b/docs/storage.md index 0a59a0f4d..29d9469b6 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -57,9 +57,10 @@ Core makes or changes storages and publishes `storage::create` for each, a paren | When | Then | |---|---| +| A user leaves `ACTIVE` | Retires their accounts' `{user}` and member storages | | An allocation or membership is set `INACTIVE` | Retires the storages it gave | -| An account is deleted | Retires its `{user}` and member storages | -| An allocation is deleted | Retires its `{allocation}` and member storages | +| An unprovisioned account, or an `INACTIVE` allocation, is deleted | Its retired storages stay `pending_deletion`, unlinked | +| An `INACTIVE` membership is deleted | Its retired storages stay `pending_deletion` | | A user is deleted, or a connector stops holding them | Retires their `{name}` storages | Making storages also retires those of the same holders the targets no longer give, so a sweep retires every storage diff --git a/internal/db/migrations/000001_identity.up.sql b/internal/db/migrations/000001_identity.up.sql index 4730a28c0..59b29c605 100644 --- a/internal/db/migrations/000001_identity.up.sql +++ b/internal/db/migrations/000001_identity.up.sql @@ -42,7 +42,8 @@ CREATE TABLE IF NOT EXISTS users updated_at TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), PRIMARY KEY (id), CONSTRAINT uq_users_email UNIQUE (email), - CONSTRAINT fk_users_organization FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE RESTRICT + CONSTRAINT fk_users_organization FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT chk_users_status CHECK (status IN ('PENDING', 'ACTIVE', 'INACTIVE', 'MERGED')) ); CREATE INDEX IF NOT EXISTS idx_users_organization_id ON users (organization_id); CREATE INDEX IF NOT EXISTS idx_users_status ON users (status); diff --git a/internal/server/allocation.go b/internal/server/allocation.go index 83fc9f4f7..4c6647281 100644 --- a/internal/server/allocation.go +++ b/internal/server/allocation.go @@ -76,6 +76,7 @@ func (s *Server) getComputeAllocation(w http.ResponseWriter, r *http.Request) { // @Param id path string true "Compute allocation ID" // @Success 204 "No Content" // @Failure 404 {object} object{error=string} +// @Failure 409 {object} object{error=string} // @Router /compute-allocations/{id} [delete] func (s *Server) deleteComputeAllocation(w http.ResponseWriter, r *http.Request) { if err := s.svc.DeleteComputeAllocation(r.Context(), r.PathValue("id")); err != nil { @@ -85,6 +86,33 @@ func (s *Server) deleteComputeAllocation(w http.ResponseWriter, r *http.Request) w.WriteHeader(http.StatusNoContent) } +// @Summary Update a compute allocation's status +// @Tags Compute Allocations +// @Security BearerAuth +// @Accept json +// @Produce json +// @Param id path string true "Compute allocation ID" +// @Param request body object{status=models.AllocationStatus} true "Status patch" +// @Success 200 {object} models.ComputeAllocation +// @Failure 400 {object} object{error=string} +// @Failure 404 {object} object{error=string} +// @Router /compute-allocations/{id}/status [put] +func (s *Server) updateComputeAllocationStatus(w http.ResponseWriter, r *http.Request) { + var body struct { + Status models.AllocationStatus `json:"status"` + } + if err := common.DecodeJSON(r, &body); err != nil { + common.WriteError(w, http.StatusBadRequest, err) + return + } + updated, err := s.svc.UpdateComputeAllocationStatus(r.Context(), r.PathValue("id"), body.Status) + if err != nil { + common.WriteServiceError(w, err) + return + } + common.WriteJSON(w, http.StatusOK, updated) +} + // @Summary Create a compute allocation diff // @Description Records a discrete change against a compute allocation (e.g. USAGE_UPDATE or ALLOCATION_STATUS_CHANGE). // @Tags Compute Allocation Diffs diff --git a/internal/server/allocation_membership.go b/internal/server/allocation_membership.go index 994dd4bf4..f3a860a2a 100644 --- a/internal/server/allocation_membership.go +++ b/internal/server/allocation_membership.go @@ -123,6 +123,7 @@ func (s *Server) updateMembershipStatus(w http.ResponseWriter, r *http.Request) // @Param id path string true "Membership ID" // @Success 204 "No Content" // @Failure 404 {object} object{error=string} +// @Failure 409 {object} object{error=string} // @Router /compute-allocation-memberships/{id} [delete] func (s *Server) deleteComputeAllocationMembership(w http.ResponseWriter, r *http.Request) { if err := s.svc.DeleteComputeAllocationMembership(r.Context(), r.PathValue("id")); err != nil { diff --git a/internal/server/compute_cluster.go b/internal/server/compute_cluster.go index 4d0762c88..6a3c7d556 100644 --- a/internal/server/compute_cluster.go +++ b/internal/server/compute_cluster.go @@ -180,6 +180,7 @@ func (s *Server) updateComputeClusterUser(w http.ResponseWriter, r *http.Request // @Param id path string true "Compute cluster user ID" // @Success 204 "No Content" // @Failure 404 {object} object{error=string} +// @Failure 409 {object} object{error=string} // @Router /compute-cluster-users/{id} [delete] func (s *Server) deleteComputeClusterUser(w http.ResponseWriter, r *http.Request) { if err := s.svc.DeleteComputeClusterUser(r.Context(), r.PathValue("id")); err != nil { diff --git a/internal/server/server.go b/internal/server/server.go index 3851a8b4f..e4e274fe4 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -97,6 +97,7 @@ func (s *Server) routes() { s.router.RequirePrivilege("POST /compute-allocations", models.AllocationsWrite, s.createComputeAllocation) s.router.RequireScoped("GET /compute-allocations/{id}", s.canReadAllocation, s.getComputeAllocation) s.router.RequirePrivilege("DELETE /compute-allocations/{id}", models.AllocationsWrite, s.deleteComputeAllocation) + s.router.RequirePrivilege("PUT /compute-allocations/{id}/status", models.AllocationsWrite, s.updateComputeAllocationStatus) s.router.RequirePrivilege("POST /compute-allocation-resources", models.AllocationsWrite, s.createComputeAllocationResource) s.router.RequirePrivilege("GET /compute-allocation-resources", models.AllocationsRead, s.listComputeAllocationResources) diff --git a/internal/store/compute_cluster_user_store.go b/internal/store/compute_cluster_user_store.go index 131d7b35f..c103a61fe 100644 --- a/internal/store/compute_cluster_user_store.go +++ b/internal/store/compute_cluster_user_store.go @@ -220,24 +220,21 @@ func (s *pgComputeClusterUserStore) Update(ctx context.Context, tx *sql.Tx, c *m return err } +// MarkProvisioned locks the user FOR SHARE, so a concurrent user status update cannot miss the stamp. func (s *pgComputeClusterUserStore) MarkProvisioned(ctx context.Context, tx *sql.Tx, id string, at time.Time) (bool, error) { - return execOnce(ctx, tx, `UPDATE compute_cluster_users SET provisioned_at = $1 WHERE id = $2 AND provisioned_at IS NULL`, at, id) + return execOnce(ctx, tx, `UPDATE compute_cluster_users cu SET provisioned_at = $1 WHERE id = $2 AND provisioned_at IS NULL + AND EXISTS (SELECT 1 FROM users u WHERE u.id = cu.user_id AND u.status = 'ACTIVE' FOR SHARE)`, at, id) +} + +func (s *pgComputeClusterUserStore) ClearProvisioned(ctx context.Context, tx *sql.Tx, id string) error { + _, err := tx.ExecContext(ctx, `UPDATE compute_cluster_users SET provisioned_at = NULL WHERE id = $1`, id) + return err } func (s *pgComputeClusterUserStore) ReassignUser(ctx context.Context, tx *sql.Tx, fromUserID, toUserID string) error { - if _, err := tx.ExecContext(ctx, - `DELETE FROM compute_cluster_users - WHERE user_id = $1 - AND compute_cluster_id IN ( - SELECT compute_cluster_id FROM ( - SELECT compute_cluster_id FROM compute_cluster_users WHERE user_id = $2 - ) AS s - )`, - fromUserID, toUserID); err != nil { - return err - } _, err := tx.ExecContext(ctx, - `UPDATE compute_cluster_users SET user_id = $1 WHERE user_id = $2`, + `UPDATE compute_cluster_users SET user_id = $1 WHERE user_id = $2 + AND compute_cluster_id NOT IN (SELECT compute_cluster_id FROM compute_cluster_users WHERE user_id = $1)`, toUserID, fromUserID) return err } diff --git a/internal/store/store.go b/internal/store/store.go index 811d3a37c..b28e24f9c 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -49,7 +49,7 @@ type UserStore interface { FindByOrganization(ctx context.Context, organizationID string) ([]models.User, error) // Create inserts a new user within the provided transaction. Create(ctx context.Context, tx *sql.Tx, u *models.User) error - // Update replaces mutable fields of an existing user within the provided transaction. + // Update replaces an existing user's fields other than status. Update(ctx context.Context, tx *sql.Tx, u *models.User) error // UpdateStatus sets the lifecycle status of an existing user within the provided transaction. UpdateStatus(ctx context.Context, tx *sql.Tx, id string, status models.UserStatus) error @@ -114,10 +114,11 @@ type ComputeClusterUserStore interface { Review(ctx context.Context, tx *sql.Tx, id string, status models.ClusterAccountApproval, reviewedBy, note string, at time.Time) error // Update replaces mutable fields of an existing mapping within the provided transaction. Update(ctx context.Context, tx *sql.Tx, c *models.ComputeClusterUser) error - // MarkProvisioned stamps provisioned_at on the mapping within the provided transaction and returns true if it is successful and false if it already exists. + // MarkProvisioned stamps provisioned_at on the mapping within the provided transaction while the user is ACTIVE and returns true if it is successful and false if it already exists. MarkProvisioned(ctx context.Context, tx *sql.Tx, id string, at time.Time) (bool, error) - // ReassignUser moves every mapping owned by fromUserID over to toUserID, - // dropping fromUserID's rows on clusters where toUserID already has one. + // ClearProvisioned unsets provisioned_at, so MarkProvisioned can stamp it again. + ClearProvisioned(ctx context.Context, tx *sql.Tx, id string) error + // ReassignUser moves fromUserID's mappings to toUserID on clusters where toUserID has none. ReassignUser(ctx context.Context, tx *sql.Tx, fromUserID, toUserID string) error // Delete removes a mapping by ID within the provided transaction. Delete(ctx context.Context, tx *sql.Tx, id string) error diff --git a/internal/store/user_store.go b/internal/store/user_store.go index b5a3459c4..1a4dd7732 100644 --- a/internal/store/user_store.go +++ b/internal/store/user_store.go @@ -160,9 +160,9 @@ func (s *pgUserStore) Create(ctx context.Context, tx *sql.Tx, u *models.User) er func (s *pgUserStore) Update(ctx context.Context, tx *sql.Tx, u *models.User) error { _, err := tx.ExecContext(ctx, - `UPDATE users SET organization_id = $1, first_name = $2, last_name = $3, middle_name = $4, email = $5, status = $6, type = $7 - WHERE id = $8`, - u.OrganizationID, u.FirstName, u.LastName, u.MiddleName, u.Email, u.Status, u.Type, u.ID) + `UPDATE users SET organization_id = $1, first_name = $2, last_name = $3, middle_name = $4, email = $5, type = $6 + WHERE id = $7`, + u.OrganizationID, u.FirstName, u.LastName, u.MiddleName, u.Email, u.Type, u.ID) return err } diff --git a/pkg/events/compute_cluster_user_subscribe.go b/pkg/events/compute_cluster_user_subscribe.go index 1e981f0e3..dd031c42a 100644 --- a/pkg/events/compute_cluster_user_subscribe.go +++ b/pkg/events/compute_cluster_user_subscribe.go @@ -59,3 +59,9 @@ func (b *Bus) SubscribeComputeClusterUserProvisioned(subscriber string, handler func (b *Bus) SubscribeComputeClusterUserDeleted(subscriber string, handler ComputeClusterUserHandler) { subscribeTyped(b, subscriber, ComputeClusterUserDeleteEvent, handler) } + +// SubscribeComputeClusterUserUpdated registers a typed handler invoked +// whenever a compute_cluster_user::update event is published. +func (b *Bus) SubscribeComputeClusterUserUpdated(subscriber string, handler ComputeClusterUserHandler) { + subscribeTyped(b, subscriber, ComputeClusterUserUpdateEvent, handler) +} diff --git a/pkg/events/types.go b/pkg/events/types.go index e6af26f89..758dc67d6 100644 --- a/pkg/events/types.go +++ b/pkg/events/types.go @@ -63,6 +63,7 @@ const ( // ComputeClusterUser lifecycle message types. const ( ComputeClusterUserCreateEvent EventType = "compute_cluster_user::create" + ComputeClusterUserUpdateEvent EventType = "compute_cluster_user::update" ComputeClusterUserDeleteEvent EventType = "compute_cluster_user::delete" ComputeClusterUserApproveEvent EventType = "compute_cluster_user::approve" ComputeClusterUserDenyEvent EventType = "compute_cluster_user::deny" diff --git a/pkg/models/project.go b/pkg/models/project.go index c50799af1..ed51779de 100644 --- a/pkg/models/project.go +++ b/pkg/models/project.go @@ -23,11 +23,10 @@ import "time" type UserStatus string const ( - UserPending UserStatus = "PENDING" - UserActive UserStatus = "ACTIVE" - UserInactive UserStatus = "INACTIVE" - UserSuspended UserStatus = "SUSPENDED" - UserMerged UserStatus = "MERGED" + UserPending UserStatus = "PENDING" + UserActive UserStatus = "ACTIVE" + UserInactive UserStatus = "INACTIVE" + UserMerged UserStatus = "MERGED" ) // ProjectStatus enumerates the lifecycle states a Project may occupy. diff --git a/pkg/service/compute_allocation.go b/pkg/service/compute_allocation.go index eceeb011f..ddcdb60c1 100644 --- a/pkg/service/compute_allocation.go +++ b/pkg/service/compute_allocation.go @@ -223,6 +223,9 @@ func (s *Service) DeleteComputeAllocation(ctx context.Context, id string) error if alloc == nil { return ErrNotFound } + if alloc.Status == models.ACTIVE { + return fmt.Errorf("%w: compute allocation %q is active, set it INACTIVE first", ErrInUse, id) + } if err := s.inTx(ctx, func(tx *sql.Tx) error { if err := s.allocs.Delete(ctx, tx, id); err != nil { return err @@ -236,3 +239,33 @@ func (s *Service) DeleteComputeAllocation(ctx context.Context, id string) error } return nil } + +// UpdateComputeAllocationStatus sets an allocation's status and records a diff; INACTIVE ends its members' access. +func (s *Service) UpdateComputeAllocationStatus(ctx context.Context, id string, status models.AllocationStatus) (alloc *models.ComputeAllocation, err error) { + if status != models.ACTIVE && status != models.INACTIVE { + return nil, fmt.Errorf("%w: status must be ACTIVE or INACTIVE", ErrInvalidInput) + } + err = s.inTx(ctx, func(tx *sql.Tx) (err error) { + if alloc, err = s.allocs.FindByIDTx(ctx, tx, id, store.UpdateLock); err != nil { + return err + } + if alloc == nil { + return ErrNotFound + } + if alloc.Status == status { + return nil + } + alloc.Status = status + if err = s.UpdateComputeAllocationTx(ctx, tx, alloc); err != nil { + return err + } + _, err = s.CreateComputeAllocationDiffTx(ctx, tx, &models.ComputeAllocationDiff{ + ComputeAllocationID: id, + DiffType: "ALLOCATION_STATUS_CHANGE", + Status: status, + Description: "Set by an admin", + }) + return err + }) + return +} diff --git a/pkg/service/compute_allocation_membership.go b/pkg/service/compute_allocation_membership.go index e42a56681..d81325713 100644 --- a/pkg/service/compute_allocation_membership.go +++ b/pkg/service/compute_allocation_membership.go @@ -227,6 +227,9 @@ func (s *Service) DeleteComputeAllocationMembership(ctx context.Context, id stri if existing == nil { return ErrNotFound } + if existing.MembershipStatus == models.ACTIVE { + return fmt.Errorf("%w: compute allocation membership %q is active, set it INACTIVE first", ErrInUse, id) + } if err := s.inTx(ctx, func(tx *sql.Tx) error { if err := s.memberships.Delete(ctx, tx, id); err != nil { return err diff --git a/pkg/service/compute_allocation_resource_mapping_integration_test.go b/pkg/service/compute_allocation_resource_mapping_integration_test.go index 0bf64369b..813c5c741 100644 --- a/pkg/service/compute_allocation_resource_mapping_integration_test.go +++ b/pkg/service/compute_allocation_resource_mapping_integration_test.go @@ -69,3 +69,36 @@ func TestSetAllocationResources_ReplacesTheSet(t *testing.T) { t.Errorf("attached: got %v, want %s and %s", got, b, c) } } + +// Make sure deleting an active membership or allocation is refused until it is INACTIVE. +func TestDeleteAllocationAndMembership_RefusedWhileActive(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + _, allocID := newClusterAllocation(t, svc, seedUser(t, database, uuid.NewString()+"@example.edu")) + m, _ := svc.CreateComputeAllocationMembership(ctx(), &models.ComputeAllocationMembership{ComputeAllocationID: allocID, UserID: seedUser(t, database, uuid.NewString()+"@example.edu"), MembershipStatus: models.ACTIVE}) + if err := svc.DeleteComputeAllocationMembership(ctx(), m.ID); !errors.Is(err, ErrInUse) { + t.Fatalf("delete active membership: %v, want ErrInUse", err) + } + if err := svc.DeleteComputeAllocation(ctx(), allocID); !errors.Is(err, ErrInUse) { + t.Fatalf("delete active allocation: %v, want ErrInUse", err) + } +} + +// Make sure an admin status change records one diff, and setting the same status records none. +func TestUpdateComputeAllocationStatus_RecordsDiff(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + _, allocID := newClusterAllocation(t, svc, seedUser(t, database, uuid.NewString()+"@example.edu")) + for range 2 { + if _, err := svc.UpdateComputeAllocationStatus(ctx(), allocID, models.INACTIVE); err != nil { + t.Fatalf("update status: %v", err) + } + } + diffs, err := svc.ListDiffsForAllocation(ctx(), allocID) + if err != nil || len(diffs) != 1 || diffs[0].DiffType != "ALLOCATION_STATUS_CHANGE" || diffs[0].Status != models.INACTIVE { + t.Fatalf("diffs: %+v, %v; want one INACTIVE ALLOCATION_STATUS_CHANGE", diffs, err) + } + if _, err := svc.UpdateComputeAllocationStatus(ctx(), allocID, models.DELETED); !errors.Is(err, ErrInvalidInput) { + t.Fatalf("status DELETED: %v, want ErrInvalidInput", err) + } +} diff --git a/pkg/service/compute_cluster_user.go b/pkg/service/compute_cluster_user.go index a979120b6..678e970b5 100644 --- a/pkg/service/compute_cluster_user.go +++ b/pkg/service/compute_cluster_user.go @@ -395,6 +395,9 @@ func (s *Service) DeleteComputeClusterUser(ctx context.Context, id string) error if cu == nil { return ErrNotFound } + if cu.ProvisionedAt != nil { + return fmt.Errorf("%w: compute cluster user %q is provisioned, set its user INACTIVE first", ErrInUse, id) + } if err := s.inTx(ctx, func(tx *sql.Tx) error { if err := s.clusterUsers.Delete(ctx, tx, id); err != nil { return err diff --git a/pkg/service/compute_cluster_user_integration_test.go b/pkg/service/compute_cluster_user_integration_test.go index 469da8fc7..9db77c5d3 100644 --- a/pkg/service/compute_cluster_user_integration_test.go +++ b/pkg/service/compute_cluster_user_integration_test.go @@ -57,6 +57,7 @@ func TestMarkComputeClusterUserProvisioned_RoundTrip(t *testing.T) { FirstName: "Prov", LastName: "Target", Email: fmt.Sprintf("prov-%s@example.invalid", uuid.NewString()), + Status: models.UserActive, }) if err != nil { t.Fatalf("create user: %v", err) @@ -481,3 +482,51 @@ func TestDenyComputeClusterUser_ConcurrentDenialsRecordOnce(t *testing.T) { t.Fatalf("denial audits: got %d, want 1", n) } } + +// Make sure an INACTIVE user's approved account loses provisioned_at, cannot regain it, and is updated again once the user is ACTIVE. +func TestUpdateUserStatus_DerivesClusterAccess(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + svc.EventBus().SubscribeComputeClusterUserUpdated("test-subscriber", func(context.Context, models.ComputeClusterUser) error { return nil }) + cu := newClusterUser(t, svc, database) + if _, err := svc.ApproveComputeClusterUser(ctx(), cu.ID, seedUser(t, database, fmt.Sprintf("admin-%s@example.edu", uuid.NewString()))); err != nil { + t.Fatalf("approve: %v", err) + } + if err := svc.MarkComputeClusterUserProvisioned(ctx(), cu.ID); err != nil { + t.Fatalf("mark provisioned: %v", err) + } + provisioned := func() bool { + return countRows(t, database, "SELECT COUNT(*) FROM compute_cluster_users WHERE id = $1 AND provisioned_at IS NOT NULL", cu.ID) == 1 + } + published := func(event string) int { + return countRows(t, database, "SELECT COUNT(*) FROM events WHERE event_type = $1 AND payload->>'id' = $2", event, cu.ID) + } + + for range 2 { + if _, err := svc.UpdateUserStatus(ctx(), cu.UserID, models.UserInactive); err != nil { + t.Fatalf("set user INACTIVE: %v", err) + } + } + if provisioned() || published("compute_cluster_user::update") != 1 { + t.Fatalf("provisioned=%v updates=%d, want false and 1", provisioned(), published("compute_cluster_user::update")) + } + if err := svc.MarkComputeClusterUserProvisioned(ctx(), cu.ID); err != nil || provisioned() { + t.Fatalf("mark provisioned while inactive: err=%v provisioned=%v, want refused", err, provisioned()) + } + if _, err := svc.UpdateUserStatus(ctx(), cu.UserID, models.UserActive); err != nil { + t.Fatalf("set user ACTIVE: %v", err) + } + if n := published("compute_cluster_user::update"); n != 2 { + t.Fatalf("updates = %d, want 2", n) + } +} + +// Make sure the status endpoint refuses MERGED, which only a merge sets. +func TestUpdateUserStatus_RefusesMerged(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + user := seedUser(t, database, uuid.NewString()+"@example.edu") + if _, err := svc.UpdateUserStatus(ctx(), user, models.UserMerged); !errors.Is(err, ErrInvalidInput) { + t.Fatalf("set MERGED: %v, want ErrInvalidInput", err) + } +} diff --git a/pkg/service/identity_resolver.go b/pkg/service/identity_resolver.go index fd170de76..f1e31c8a3 100644 --- a/pkg/service/identity_resolver.go +++ b/pkg/service/identity_resolver.go @@ -154,7 +154,7 @@ func (s *Service) ResolveCaller(ctx context.Context, claims *identity.Claims) (* func refuseDisabled(user *models.User) error { switch user.Status { - case models.UserSuspended, models.UserInactive, models.UserMerged: + case models.UserInactive, models.UserMerged: return fmt.Errorf("%w: status=%s", identity.ErrUserDisabled, user.Status) } return nil diff --git a/pkg/service/identity_resolver_integration_test.go b/pkg/service/identity_resolver_integration_test.go index 9537bc319..3fa39c68a 100644 --- a/pkg/service/identity_resolver_integration_test.go +++ b/pkg/service/identity_resolver_integration_test.go @@ -110,8 +110,8 @@ func TestResolveCaller_PendingUserSignInLinksNoSub(t *testing.T) { t.Errorf("audit IDENTITY_LINKED: got %d, want 0", got) } - if _, err := database.Exec("UPDATE users SET status = $1 WHERE id = $2", models.UserSuspended, user); err != nil { - t.Fatalf("suspend: %v", err) + if _, err := database.Exec("UPDATE users SET status = $1 WHERE id = $2", models.UserInactive, user); err != nil { + t.Fatalf("deactivate: %v", err) } if _, _, err := svc.ResolveCaller(ctx(), claims); !errors.Is(err, identity.ErrUserDisabled) { t.Errorf("second resolve: got %v, want ErrUserDisabled", err) @@ -308,9 +308,15 @@ func TestResolveCaller_RefusesDisabledUser(t *testing.T) { } unbound := seedPendingUserWithEmail(t, database, "unbound@example.edu") - for _, status := range []models.UserStatus{models.UserSuspended, models.UserInactive, models.UserMerged} { + for _, status := range []models.UserStatus{models.UserInactive, models.UserMerged} { for _, id := range []string{bound, unbound} { - if _, err := svc.UpdateUserStatus(ctx(), id, status); err != nil { + // MERGED is set only by a merge, so the test writes it directly. + if status == models.UserMerged { + _, err := database.Exec(`UPDATE users SET status = $1 WHERE id = $2`, status, id) + if err != nil { + t.Fatalf("set %s: %v", status, err) + } + } else if _, err := svc.UpdateUserStatus(ctx(), id, status); err != nil { t.Fatalf("set %s: %v", status, err) } } diff --git a/pkg/service/storage_integration_test.go b/pkg/service/storage_integration_test.go index 810fb6bba..19feb725c 100644 --- a/pkg/service/storage_integration_test.go +++ b/pkg/service/storage_integration_test.go @@ -79,7 +79,7 @@ func newStorageAllocation(t *testing.T, svc *Service, database *sqlx.DB, cluster } // Make sure a storage is made from its target for its owner, a retired owner's is active again once ensured, a storage -// is deleted only once everything under it is pending, and deleting an owner retires and unlinks its storages. +// is deleted only once everything under it is pending, and deleting an owner unlinks its retired storages. func TestStorageLifecycle(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) @@ -102,7 +102,8 @@ func TestStorageLifecycle(t *testing.T) { } return countRows(t, database, storageCreates) - before } - cu, err := svc.CreateComputeClusterUser(ctx(), &models.ComputeClusterUser{ComputeClusterID: cluster.ID, UserID: seedUser(t, database, uuid.NewString()+"@example.edu"), LocalUsername: "jdoe"}) + user := seedUser(t, database, uuid.NewString()+"@example.edu") + cu, err := svc.CreateComputeClusterUser(ctx(), &models.ComputeClusterUser{ComputeClusterID: cluster.ID, UserID: user, LocalUsername: "jdoe", ApprovalStatus: models.ClusterAccountApproved, ReviewedBy: &user}) if err == nil { err = svc.MarkComputeClusterUserProvisioned(ctx(), cu.ID) } @@ -164,6 +165,14 @@ func TestStorageLifecycle(t *testing.T) { if err := svc.UpdateStorage(ctx(), byPath()[siblingPath].ID, 1, &until, "", "admin"); !errors.Is(err, ErrNotFound) { t.Errorf("quota on a storage without one of its own: got %v, want ErrNotFound", err) } + if err := svc.DeleteComputeClusterUser(ctx(), cu.ID); !errors.Is(err, ErrInUse) { + t.Fatalf("deleting a provisioned account: got %v, want ErrInUse", err) + } + _, err = svc.UpdateUserStatus(ctx(), user, models.UserInactive) + if _, e := svc.UpdateComputeAllocationStatus(ctx(), sibling.ID, models.INACTIVE); errors.Join(err, e) != nil || + byPath()["/home/jdoe"].Status != "pending_deletion" || byPath()[siblingPath].Status != "pending_deletion" { + t.Fatalf("suspending the user and deactivating the allocation: err=%v left=%+v, want theirs retired", errors.Join(err, e), byPath()) + } err = errors.Join(svc.DeleteComputeClusterUser(ctx(), cu.ID), svc.DeleteComputeAllocation(ctx(), sibling.ID)) if got := byPath(); err != nil || got["/home/jdoe"].Status != "pending_deletion" || got[siblingPath].Status != "pending_deletion" || got["/home/jdoe"].ComputeClusterUserID != nil || got[siblingPath].AllocationID != nil { @@ -172,7 +181,7 @@ func TestStorageLifecycle(t *testing.T) { } // Make sure core creates a storage only once its holder is on the cluster: the account, the active allocation's group, -// or both. +// or both, and that a member's is retired with its membership. func TestStoragesFollowProvisioning(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) @@ -185,10 +194,12 @@ func TestStoragesFollowProvisioning(t *testing.T) { } return cu } - join := func(cu *models.ComputeClusterUser) { - if _, err := svc.CreateComputeAllocationMembership(ctx(), &models.ComputeAllocationMembership{ComputeAllocationID: alloc.ID, UserID: cu.UserID}); err != nil { + join := func(cu *models.ComputeClusterUser) *models.ComputeAllocationMembership { + m, err := svc.CreateComputeAllocationMembership(ctx(), &models.ComputeAllocationMembership{ComputeAllocationID: alloc.ID, UserID: cu.UserID}) + if err != nil { t.Fatalf("create membership: %v", err) } + return m } check := func(step string, err error, want ...string) { var got []string @@ -208,11 +219,19 @@ func TestStoragesFollowProvisioning(t *testing.T) { err := svc.UpdateComputeAllocation(ctx(), alloc) check("the allocation becoming active", err, "/home/early", projectPath, projectPath+"/early") err = svc.MarkComputeClusterUserProvisioned(ctx(), late.ID) - join(late) + member := join(late) check("a provisioned account joining", err, "/home/early", "/home/late", projectPath, projectPath+"/early", projectPath+"/late") if desired, err := svc.EnsureStorages(ctx(), cluster.ID); err != nil || len(desired) != 5 || countRows(t, database, storageCreates) != 5 { t.Fatalf("ensuring again: err=%v desired=%d, want the five storages and nothing made or changed", err, len(desired)) } + var retired []string + _, err = svc.UpdateMembershipStatus(ctx(), member.ID, models.INACTIVE) + if err == nil { + err = database.Select(&retired, `SELECT path FROM storages WHERE status = 'pending_deletion'`) + } + if err != nil || !slices.Equal(retired, []string{projectPath + "/late"}) { + t.Fatalf("the membership leaving: err=%v retired=%v, want only the member's", err, retired) + } } // Make sure an account provisioned while its member storage's other owner is being made still gets that storage. diff --git a/pkg/service/user.go b/pkg/service/user.go index 6619e794c..2300e57e3 100644 --- a/pkg/service/user.go +++ b/pkg/service/user.go @@ -145,8 +145,7 @@ func (s *Service) ListUsersByOrganization(ctx context.Context, organizationID st return users, nil } -// UpdateUser persists changes to an existing user. Fields left blank/zero on -// the supplied record fall back to the stored value. +// UpdateUser saves an existing user's fields other than status; a blank field keeps the stored value. func (s *Service) UpdateUser(ctx context.Context, user *models.User) error { if user == nil || user.ID == "" { return fmt.Errorf("%w: user id is required", ErrInvalidInput) @@ -182,9 +181,7 @@ func (s *Service) UpdateUser(ctx context.Context, user *models.User) error { if user.Email == "" { user.Email = existing.Email } - if user.Status == "" { - user.Status = existing.Status - } + user.Status = existing.Status if user.Type == "" { user.Type = existing.Type } @@ -207,22 +204,34 @@ func (s *Service) UpdateUserStatus(ctx context.Context, id string, status models if id == "" { return nil, fmt.Errorf("%w: user id is required", ErrInvalidInput) } - if status == "" { - return nil, fmt.Errorf("%w: status is required", ErrInvalidInput) - } - existing, err := s.users.FindByID(ctx, id) - if err != nil { - return nil, fmt.Errorf("lookup user: %w", err) - } - if existing == nil { - return nil, ErrNotFound + switch status { + case models.UserPending, models.UserActive, models.UserInactive: + default: + return nil, fmt.Errorf("%w: status must be PENDING, ACTIVE or INACTIVE", ErrInvalidInput) } - existing.Status = status - if err := s.inTx(ctx, func(tx *sql.Tx) error { + var existing *models.User + if err := s.inTx(ctx, func(tx *sql.Tx) (err error) { + if existing, err = s.users.FindByIDTx(ctx, tx, id, store.NoKeyUpdateLock); err != nil { + return fmt.Errorf("lookup user: %w", err) + } + if existing == nil { + return ErrNotFound + } + if existing.Status == models.UserMerged { + return fmt.Errorf("%w: user %q is merged", ErrInvalidInput, id) + } + wasActive := existing.Status == models.UserActive + existing.Status = status if err := s.users.UpdateStatus(ctx, tx, id, status); err != nil { return err } - return s.publishUserTx(ctx, tx, events.UserUpdateEvent, existing) + if err := s.publishUserTx(ctx, tx, events.UserUpdateEvent, existing); err != nil { + return err + } + if nowActive := status == models.UserActive; nowActive != wasActive { + return s.setUserAccountsActiveTx(ctx, tx, id, nowActive) + } + return nil }); err != nil { return nil, fmt.Errorf("update user status: %w", err) } @@ -230,6 +239,29 @@ func (s *Service) UpdateUserStatus(ctx context.Context, id string, status models return existing, nil } +// setUserAccountsActiveTx republishes the user's approved accounts, unprovisioned unless active, and ensures their storages. +func (s *Service) setUserAccountsActiveTx(ctx context.Context, tx *sql.Tx, userID string, active bool) error { + accounts, err := s.clusterUsers.FindByUserTx(ctx, tx, userID) + if err != nil { + return err + } + for _, cu := range accounts { + if cu.ApprovalStatus != models.ClusterAccountApproved { + continue + } + if !active { + if err := s.clusterUsers.ClearProvisioned(ctx, tx, cu.ID); err != nil { + return err + } + cu.ProvisionedAt = nil + } + if err := s.eventBus.Publish(ctx, tx, events.ComputeClusterUserUpdateEvent, cu); err != nil { + return err + } + } + return s.ensureStoragesTx(ctx, tx, store.StorageScope{UserID: userID}) +} + const ( userAuditEmailChangeRequested = "USER_EMAIL_CHANGE_REQUESTED" userAuditEmailChanged = "USER_EMAIL_CHANGED" diff --git a/pkg/service/user_merge.go b/pkg/service/user_merge.go index 0720bfb81..ee8be5065 100644 --- a/pkg/service/user_merge.go +++ b/pkg/service/user_merge.go @@ -29,12 +29,12 @@ import ( // MergeUsers consolidates the retiring user into the surviving user. All // identity-forward state moves to the survivor; historical truth stays in -// place. The retiring user is flipped to status=MERGED. All work happens in a -// single transaction. +// place. The retiring user is flipped to status=MERGED, and a PENDING survivor +// of an ACTIVE user becomes ACTIVE. All work happens in a single transaction. // -// Moved to survivor (duplicates on the retiring user are dropped first): +// Moved to survivor (the unprovisioned duplicate is dropped first): // - user_identities -// - compute_cluster_users +// - compute_cluster_users (on a shared cluster the provisioned one wins; if both are, the retiring one stays, deprovisioned) // - projects.project_pi_id // - compute_allocation_memberships // @@ -90,8 +90,6 @@ func (s *Service) MergeUsersTx(ctx context.Context, tx *sql.Tx, survivingID, ret ErrInvalidInput, retiringID, retiring.Status) } - // The reassigning below deletes the retiring user's cluster account on every - // cluster where the survivor already has one. Those need a delete event. retiringAccounts, err := s.clusterUsers.FindByUserTx(ctx, tx, retiringID) if err != nil { return nil, fmt.Errorf("list retiring cluster users: %w", err) @@ -100,21 +98,26 @@ func (s *Service) MergeUsersTx(ctx context.Context, tx *sql.Tx, survivingID, ret if err != nil { return nil, fmt.Errorf("list surviving cluster users: %w", err) } - survivorClusters := make(map[string]bool, len(survivorAccounts)) + survivorAccountByCluster := make(map[string]models.ComputeClusterUser, len(survivorAccounts)) for _, cu := range survivorAccounts { - survivorClusters[cu.ComputeClusterID] = true + survivorAccountByCluster[cu.ComputeClusterID] = cu + } + var deletedAccounts []models.ComputeClusterUser + for _, cu := range retiringAccounts { + if survivorAccount, sameCluster := survivorAccountByCluster[cu.ComputeClusterID]; sameCluster && cu.ProvisionedAt == nil { + deletedAccounts = append(deletedAccounts, cu) + } else if sameCluster && survivorAccount.ProvisionedAt == nil { + deletedAccounts = append(deletedAccounts, survivorAccount) + } } if err := func() error { if err := s.userIdentities.ReassignUser(ctx, tx, retiringID, survivingID); err != nil { return fmt.Errorf("reassign user identities: %w", err) } - if err := s.clusterUsers.ReassignUser(ctx, tx, retiringID, survivingID); err != nil { - return fmt.Errorf("reassign compute cluster users: %w", err) - } - for _, cu := range retiringAccounts { - if !survivorClusters[cu.ComputeClusterID] { - continue + for _, cu := range deletedAccounts { + if err := s.clusterUsers.Delete(ctx, tx, cu.ID); err != nil { + return err } if err := s.ensureStoragesTx(ctx, tx, store.StorageScope{ClusterID: cu.ComputeClusterID}); err != nil { return err @@ -123,6 +126,9 @@ func (s *Service) MergeUsersTx(ctx context.Context, tx *sql.Tx, survivingID, ret return err } } + if err := s.clusterUsers.ReassignUser(ctx, tx, retiringID, survivingID); err != nil { + return fmt.Errorf("reassign compute cluster users: %w", err) + } if err := s.projs.ReassignPI(ctx, tx, retiringID, survivingID); err != nil { return fmt.Errorf("reassign project PI: %w", err) } @@ -132,6 +138,13 @@ func (s *Service) MergeUsersTx(ctx context.Context, tx *sql.Tx, survivingID, ret if err := s.projMemberships.ReassignUser(ctx, tx, retiringID, survivingID); err != nil { return fmt.Errorf("reassign project memberships: %w", err) } + // The survivor takes the retiring user's sign-in identity, so it is ACTIVE if either was. + if retiring.Status == models.UserActive && survivor.Status != models.UserActive { + if err := s.users.UpdateStatus(ctx, tx, survivingID, models.UserActive); err != nil { + return err + } + survivor.Status = models.UserActive + } if err := s.users.UpdateStatus(ctx, tx, retiringID, models.UserMerged); err != nil { return err } @@ -139,6 +152,12 @@ func (s *Service) MergeUsersTx(ctx context.Context, tx *sql.Tx, survivingID, ret if err := s.publishUserTx(ctx, tx, events.UserUpdateEvent, retiring); err != nil { return err } + if err := s.setUserAccountsActiveTx(ctx, tx, retiringID, false); err != nil { + return err + } + if err := s.setUserAccountsActiveTx(ctx, tx, survivingID, survivor.Status == models.UserActive); err != nil { + return err + } return s.publishUserTx(ctx, tx, events.UserUpdateEvent, survivor) }(); err != nil { return nil, fmt.Errorf("merge users: %w", err) @@ -149,7 +168,7 @@ func (s *Service) MergeUsersTx(ctx context.Context, tx *sql.Tx, survivingID, ret // canBeMerged returns true for the user statuses eligible for merging: // ACTIVE (already linked) or PENDING (provisioned upstream, not yet linked). -// INACTIVE, SUSPENDED, and MERGED are intentionally excluded. +// INACTIVE and MERGED are intentionally excluded. func canBeMerged(s models.UserStatus) bool { return s == models.UserActive || s == models.UserPending } diff --git a/pkg/service/user_merge_integration_test.go b/pkg/service/user_merge_integration_test.go index 46687120d..a2452b1c9 100644 --- a/pkg/service/user_merge_integration_test.go +++ b/pkg/service/user_merge_integration_test.go @@ -37,7 +37,8 @@ import ( // Make sure a merge publishes the delete event only for the retiring user's // cluster account that it drops, which is the one on a cluster where the // survivor already has an account. An account that moves to the survivor is -// not deleted, so it gets no event. +// not deleted, so it gets no delete event. A lone provisioned account wins; if +// both are, both stay and the retiring one is deprovisioned. func TestMergeUsers_PublishesDeleteForTheDroppedClusterAccount(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) @@ -50,6 +51,8 @@ func TestMergeUsers_PublishesDeleteForTheDroppedClusterAccount(t *testing.T) { ComputeClusterID: cluster.ID, UserID: userID, LocalUsername: "merge-" + uuid.NewString()[:8], + ApprovalStatus: models.ClusterAccountApproved, + ReviewedBy: &userID, }) if err != nil { t.Fatalf("create compute cluster user: %v", err) @@ -63,10 +66,18 @@ func TestMergeUsers_PublishesDeleteForTheDroppedClusterAccount(t *testing.T) { } return c } - shared, onlyRetiring := cluster(), cluster() + shared, onlyRetiring, retiringProvisioned, bothProvisioned := cluster(), cluster(), cluster(), cluster() account(survivor, shared) dropped := account(retiring, shared) moved := account(retiring, onlyRetiring) + droppedSurvivor := account(survivor, retiringProvisioned) + kept := account(retiring, retiringProvisioned) + keptDeprovisioned := account(retiring, bothProvisioned) + for _, cu := range []*models.ComputeClusterUser{kept, keptDeprovisioned, account(survivor, bothProvisioned)} { + if err := svc.MarkComputeClusterUserProvisioned(ctx(), cu.ID); err != nil { + t.Fatalf("mark provisioned: %v", err) + } + } if _, err := svc.MergeUsers(ctx(), survivor, retiring); err != nil { t.Fatalf("merge: %v", err) @@ -76,15 +87,16 @@ func TestMergeUsers_PublishesDeleteForTheDroppedClusterAccount(t *testing.T) { if err != nil { t.Fatalf("list deliveries: %v", err) } - if len(deliveries) != 1 || deliveries[0].Event.EventType != string(events.ComputeClusterUserDeleteEvent) { - t.Fatalf("expected one delivery of the delete event, got %+v", deliveries) + want := map[string]string{dropped.ID: dropped.LocalUsername, droppedSurvivor.ID: droppedSurvivor.LocalUsername} + if len(deliveries) != len(want) { + t.Fatalf("expected %d deliveries of the delete event, got %+v", len(want), deliveries) } - var got models.ComputeClusterUser - if err := json.Unmarshal(deliveries[0].Event.Payload, &got); err != nil { - t.Fatalf("decode payload: %v", err) - } - if got.ID != dropped.ID || got.LocalUsername != dropped.LocalUsername { - t.Errorf("delete event is for %s (%s), want the dropped account %s (%s)", got.ID, got.LocalUsername, dropped.ID, dropped.LocalUsername) + for _, d := range deliveries { + var got models.ComputeClusterUser + if err := json.Unmarshal(d.Event.Payload, &got); err != nil || d.Event.EventType != string(events.ComputeClusterUserDeleteEvent) || want[got.ID] != got.LocalUsername { + t.Errorf("%s is for %s (%s), %v, want a delete event for a dropped account %v", d.Event.EventType, got.ID, got.LocalUsername, err, want) + } + delete(want, got.ID) } after, err := svc.GetComputeClusterUser(ctx(), moved.ID) @@ -94,6 +106,12 @@ func TestMergeUsers_PublishesDeleteForTheDroppedClusterAccount(t *testing.T) { if after.UserID != survivor { t.Errorf("moved account belongs to %s, want the survivor %s", after.UserID, survivor) } + for id, owner := range map[string]string{kept.ID: survivor, keptDeprovisioned.ID: retiring} { + after, err := svc.GetComputeClusterUser(ctx(), id) + if err != nil || after.UserID != owner || (after.ProvisionedAt == nil) != (owner == retiring) { + t.Errorf("provisioned account %s: got %+v, %v, want owner %s, provisioned only if kept by the survivor", id, after, err, owner) + } + } } // Make sure a merge keeps the higher tag per project and that the survivor @@ -205,3 +223,39 @@ func TestDeleteUser_RefusesAUserStillReferenced(t *testing.T) { t.Fatalf("delete a project PI: %v, want ErrInUse", err) } } + +// Make sure a PENDING survivor of an ACTIVE user becomes ACTIVE and keeps the moved account provisioned, and a merged user's status stays MERGED. +func TestMergeUsers_ActivatesPendingSurvivorOfActiveUser(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + survivor := seedUser(t, database, fmt.Sprintf("survivor-%s@example.edu", uuid.NewString())) + retiring := seedUser(t, database, fmt.Sprintf("retiring-%s@example.edu", uuid.NewString())) + if _, err := database.Exec(`UPDATE users SET status = $1 WHERE id = $2`, models.UserPending, survivor); err != nil { + t.Fatalf("set survivor PENDING: %v", err) + } + cluster, err := svc.CreateComputeCluster(ctx(), &models.ComputeCluster{Name: "merge-" + uuid.NewString()[:8]}) + if err != nil { + t.Fatalf("create cluster: %v", err) + } + moved, err := svc.CreateComputeClusterUser(ctx(), &models.ComputeClusterUser{ComputeClusterID: cluster.ID, UserID: retiring, + LocalUsername: "merge-" + uuid.NewString()[:8], ApprovalStatus: models.ClusterAccountApproved, ReviewedBy: &retiring}) + if err != nil { + t.Fatalf("create account: %v", err) + } + if err := svc.MarkComputeClusterUserProvisioned(ctx(), moved.ID); err != nil { + t.Fatalf("mark provisioned: %v", err) + } + + if _, err := svc.MergeUsers(ctx(), survivor, retiring); err != nil { + t.Fatalf("merge: %v", err) + } + if after, err := svc.GetUser(ctx(), survivor); err != nil || after.Status != models.UserActive { + t.Errorf("survivor: got %+v, %v, want ACTIVE", after, err) + } + if after, err := svc.GetComputeClusterUser(ctx(), moved.ID); err != nil || after.UserID != survivor || after.ProvisionedAt == nil { + t.Errorf("moved account: got %+v, %v, want the survivor's and provisioned", after, err) + } + if _, err := svc.UpdateUserStatus(ctx(), retiring, models.UserActive); !errors.Is(err, ErrInvalidInput) { + t.Errorf("reactivating the merged user: got %v, want ErrInvalidInput", err) + } +} diff --git a/pkg/service/user_onboard_integration_test.go b/pkg/service/user_onboard_integration_test.go index 1e65442a2..f57bae213 100644 --- a/pkg/service/user_onboard_integration_test.go +++ b/pkg/service/user_onboard_integration_test.go @@ -501,7 +501,7 @@ func TestCompleteOnboarding_RegisteredUserKeepsUsername(t *testing.T) { func TestSetupSteps_FollowProvisioning(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) - user := seedPendingUserWithEmail(t, database, "jdoe-"+uuid.NewString()[:8]+"@example.edu") + user := seedUser(t, database, "jdoe-"+uuid.NewString()[:8]+"@example.edu") cu := newClusterAccount(t, svc, user, "jdoe") cluster, err := svc.GetComputeCluster(ctx(), cu.ComputeClusterID) if err != nil { diff --git a/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx b/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx index debe5e918..c9b7cd7b5 100644 --- a/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx +++ b/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx @@ -56,7 +56,7 @@ vi.mock("@/features/core/users/components/UserDetailsDrawer", () => ({ vi.mock("../queries", () => ({ useAllocationMembers: () => ({ data: members, isLoading: false, error: null, refetch: vi.fn() }), useAddMember: () => mutation, - useRemoveMember: () => mutation, + useSetMemberActive: () => mutation, })); vi.mock("@/features/core/projects/queries", () => ({ useUpdateProjectMember: () => mutation, @@ -81,16 +81,16 @@ const allocation: ComputeAllocation = { }; describe("", () => { - it("offers no Edit or Remove for PI or Co-PI members", () => { + it("offers no Edit or Deactivate for PI or Co-PI members", () => { render( , ); for (const name of ["Paula Ivey", "Carl Osei"]) { expect(screen.queryByRole("button", { name: `Edit ${name}` })).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: `Remove ${name}` })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: `Deactivate ${name}` })).not.toBeInTheDocument(); } expect(screen.getByRole("button", { name: "Edit Mina Frey" })).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Remove Mina Frey" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Deactivate Mina Frey" })).toBeInTheDocument(); }); it("disables each action whose privilege is missing", () => { @@ -102,7 +102,7 @@ describe("", () => { canSearchUsers />, ); - expect(screen.getByRole("button", { name: "Remove Mina Frey" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Deactivate Mina Frey" })).toBeDisabled(); expect(screen.getByRole("button", { name: "Edit Mina Frey" })).toBeEnabled(); expect(screen.getByRole("button", { name: "+ Add member" })).toBeDisabled(); }); diff --git a/web/src/features/core/allocations/__tests__/api.test.ts b/web/src/features/core/allocations/__tests__/api.test.ts index be97e2036..6c3395cd5 100644 --- a/web/src/features/core/allocations/__tests__/api.test.ts +++ b/web/src/features/core/allocations/__tests__/api.test.ts @@ -28,7 +28,7 @@ import { listChangeRequestEvents, listChangeRequests, rejectChangeRequest, - removeMember, + setMemberActive, submitChangeRequest, } from "../api"; @@ -177,11 +177,13 @@ describe("addMember", () => { }); }); -describe("removeMember", () => { - it("DELETEs the membership", async () => { +describe("setMemberActive", () => { + it("PUTs INACTIVE to deactivate the membership", async () => { fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })); - await removeMember("mem-001"); - expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("DELETE"); + await setMemberActive("mem-001", false); + const [url, init] = fetchMock.mock.calls[0] ?? []; + expect(String(url)).toMatch(/\/compute-allocation-memberships\/mem-001\/status$/); + expect(init).toMatchObject({ method: "PUT", body: '{"membership_status":"INACTIVE"}' }); }); }); diff --git a/web/src/features/core/allocations/api.ts b/web/src/features/core/allocations/api.ts index 4589ddc5c..5a42e3cb9 100644 --- a/web/src/features/core/allocations/api.ts +++ b/web/src/features/core/allocations/api.ts @@ -125,8 +125,14 @@ export async function addMember( return zPostComputeAllocationMembershipsResponse.parse(raw); } -export async function removeMember(id: string): Promise { - await apiFetch(`/compute-allocation-memberships/${id}`, { method: "DELETE" }); +export async function setAllocationActive(id: string, active: boolean) { + const body = { status: active ? "ACTIVE" : "INACTIVE" }; + await apiFetch(`/compute-allocations/${id}/status`, { method: "PUT", body }); +} + +export async function setMemberActive(id: string, active: boolean) { + const body = { membership_status: active ? "ACTIVE" : "INACTIVE" }; + await apiFetch(`/compute-allocation-memberships/${id}/status`, { method: "PUT", body }); } export async function listChangeRequests( diff --git a/web/src/features/core/allocations/components/AllocationDetail.tsx b/web/src/features/core/allocations/components/AllocationDetail.tsx index 22c90d2e9..fa7ac9871 100644 --- a/web/src/features/core/allocations/components/AllocationDetail.tsx +++ b/web/src/features/core/allocations/components/AllocationDetail.tsx @@ -22,10 +22,16 @@ import { requires, usePermissions } from "@/shared/casl/permissions"; import { useBreadcrumbLabel } from "@/shared/layout/BreadcrumbLabelsProvider"; import { DeleteButton } from "@/shared/ui/ConfirmDialog"; import { ErrorState } from "@/shared/ui/ErrorState"; +import { GuardedButton } from "@/shared/ui/GuardedButton"; import { CardSkeleton } from "@/shared/ui/Loading"; import { TabsRouter } from "@/shared/ui/TabsRouter"; import { useSession } from "next-auth/react"; -import { useAllocation, useAllocationMembers, useDeleteAllocation } from "../queries"; +import { + useAllocation, + useAllocationMembers, + useDeleteAllocation, + useSetAllocationActive, +} from "../queries"; import { AllocationChangeRequestsTab } from "./AllocationChangeRequestsTab"; import { AllocationDetailHeader } from "./AllocationDetailHeader"; import { AllocationHistoryTab } from "./AllocationHistoryTab"; @@ -43,6 +49,7 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) { const allocationQuery = useAllocation(allocationId); const membersQuery = useAllocationMembers(allocationId); const remove = useDeleteAllocation(); + const statusMutation = useSetAllocationActive(allocationId); useBreadcrumbLabel(allocationId, allocationQuery.data?.name); const projectId = allocationQuery.data?.project_id; useBreadcrumbLabel(projectId, useProject(projectId).data?.title); @@ -58,24 +65,37 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) { } const allocation = allocationQuery.data; if (!allocation) return null; + const active = allocation.status === "ACTIVE"; - const memberCount = membersQuery.data?.length ?? 0; + const memberCount = + membersQuery.data?.filter((m) => m.membership_status === "ACTIVE").length ?? 0; return (
- - Its members, resources and usage records are deleted with it. This cannot be undone. - +
+ statusMutation.mutate(!active)} + disabled={statusMutation.isPending} + > + {active ? "Deactivate" : "Reactivate"} + + + Its members, resources and usage records are deleted with it. This cannot be undone. + +
= { MEMBER: "Member", }; +const isActive = (m: AllocationMembership) => m.membership_status === "ACTIVE"; + function initialsFrom(name: string): string { const parts = name.trim().split(/\s+/); if (parts.length >= 2) return `${parts[0]?.[0] ?? ""}${parts[1]?.[0] ?? ""}`.toUpperCase(); @@ -67,7 +69,7 @@ export function AllocationMembersTab({ const query = useAllocationMembers(allocation.id); const addMutation = useAddMember(allocation.id); const roleMutation = useUpdateProjectMember(allocation.project_id); - const removeMutation = useRemoveMember(allocation.id); + const statusMutation = useSetMemberActive(allocation.id); const [editing, setEditing] = React.useState(null); const [viewing, setViewing] = React.useState(null); const [adding, setAdding] = React.useState(false); @@ -171,17 +173,20 @@ export function AllocationMembersTab({ Edit - removeMutation.mutate(row.id, { onError: (err) => toast.error(err.message) }) + statusMutation.mutate( + { id: row.id, active: !isActive(row) }, + { onError: (err) => toast.error(err.message) }, + ) } - aria-label={`Remove ${row.display_name ?? row.user_id}`} - disabled={removeMutation.isPending} + aria-label={`${isActive(row) ? "Deactivate" : "Reactivate"} ${row.display_name ?? row.user_id}`} + disabled={statusMutation.isPending} > - Remove + {isActive(row) ? "Deactivate" : "Reactivate"} ) : null, diff --git a/web/src/features/core/allocations/queries.ts b/web/src/features/core/allocations/queries.ts index 6745aff99..c1d4e18a1 100644 --- a/web/src/features/core/allocations/queries.ts +++ b/web/src/features/core/allocations/queries.ts @@ -44,8 +44,9 @@ import { listChangeRequests, listUserMemberships, rejectChangeRequest, - removeMember, + setAllocationActive, setAllocationResources, + setMemberActive, submitChangeRequest, } from "./api"; import type { @@ -135,6 +136,15 @@ export function useDeleteAllocation() { }); } +export function useSetAllocationActive(allocationId: string) { + const client = useQueryClient(); + return useMutation({ + mutationFn: (active: boolean) => setAllocationActive(allocationId, active), + onError: (err) => toast.error(err.message), + onSuccess: () => client.invalidateQueries({ queryKey: allocationKeys.all }), + }); +} + export function useSetAllocationResources(allocationId: string) { const client = useQueryClient(); return useMutation({ @@ -199,10 +209,11 @@ export function useAddMember(allocationId: string) { }); } -export function useRemoveMember(allocationId: string) { +export function useSetMemberActive(allocationId: string) { const client = useQueryClient(); return useMutation({ - mutationFn: (id: string) => removeMember(id), + mutationFn: ({ id, active }: { id: string; active: boolean }) => + setMemberActive(id, active), onSuccess: () => invalidateMembers(client, allocationId), }); } @@ -224,7 +235,7 @@ export function useMembershipsByAllocation(allocationIds: string[]) { }); } -// Revokes access by deleting the membership, or grants it for the allocation's remaining term. +// Reactivates or deactivates an existing membership, or adds one for the allocation's remaining term. export function useToggleAllocationAccess() { const client = useQueryClient(); return useMutation({ @@ -238,7 +249,7 @@ export function useToggleAllocationAccess() { membership: AllocationMembership | undefined; }) => membership - ? removeMember(membership.id) + ? setMemberActive(membership.id, membership.membership_status !== "ACTIVE") : addMember({ compute_allocation_id: allocation.id, user_id: userId, diff --git a/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx b/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx index a8e088c6b..4e01e3a13 100644 --- a/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx +++ b/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx @@ -42,7 +42,18 @@ const allocations = [ { id: "a-1", name: "Alpha", end_time: "2027-01-01T00:00:00Z" }, { id: "a-2", name: "Beta", end_time: "2027-01-01T00:00:00Z" }, ]; -const ciraInAlpha = { id: "m-1", compute_allocation_id: "a-1", user_id: "u-3" }; +const ciraInAlpha = { + id: "m-1", + compute_allocation_id: "a-1", + user_id: "u-3", + membership_status: "ACTIVE", +}; +const ciraInBeta = { + id: "m-2", + compute_allocation_id: "a-2", + user_id: "u-3", + membership_status: "INACTIVE", +}; const roleMutation = { mutateAsync: vi.fn(async () => undefined), isPending: false }; const toggle = { mutateAsync: vi.fn(async () => undefined), isPending: false }; @@ -56,7 +67,7 @@ vi.mock("../queries", () => ({ vi.mock("@/features/core/allocations/queries", () => ({ useAllocationsByProject: () => ({ data: { items: allocations }, isLoading: false, error: null }), useMembershipsByAllocation: () => ({ - byAllocation: { "a-1": [ciraInAlpha], "a-2": [] }, + byAllocation: { "a-1": [ciraInAlpha], "a-2": [ciraInBeta] }, isLoading: false, error: null, }), @@ -109,7 +120,7 @@ describe("", () => { expect.objectContaining({ userId: "u-3", membership: ciraInAlpha }), ); expect(toggle.mutateAsync).toHaveBeenCalledWith( - expect.objectContaining({ userId: "u-3", membership: undefined }), + expect.objectContaining({ userId: "u-3", membership: ciraInBeta }), ); }); diff --git a/web/src/features/core/projects/components/ProjectMembersTab.tsx b/web/src/features/core/projects/components/ProjectMembersTab.tsx index 5a10d682f..deb4f624f 100644 --- a/web/src/features/core/projects/components/ProjectMembersTab.tsx +++ b/web/src/features/core/projects/components/ProjectMembersTab.tsx @@ -178,7 +178,7 @@ function describe(change: Change, changes: Change[]): string { }`; } if (change.kind === "role") return `${change.row.name}: role → ${ROLE_LABELS[change.to]}`; - return `${change.row.name}: ${change.membership ? "remove from" : "add to"} ${change.allocation.name}`; + return `${change.row.name}: ${change.membership?.membership_status === "ACTIVE" ? "remove from" : "add to"} ${change.allocation.name}`; } export function ProjectMembersTab({ @@ -240,10 +240,12 @@ export function ProjectMembersTab({ ]; const membershipOf = (allocationId: string, userId: string) => memberships.byAllocation[allocationId]?.find((m) => m.user_id === userId); + const hasActiveMembership = (allocationId: string, userId: string) => + membershipOf(allocationId, userId)?.membership_status === "ACTIVE"; const accessKey = (allocationId: string, userId: string) => `${allocationId}:${userId}`; const roleOf = (row: GridRow) => draft.roles[row.userId] ?? row.role; const hasAccess = (allocationId: string, userId: string) => - draft.access[accessKey(allocationId, userId)] ?? Boolean(membershipOf(allocationId, userId)); + draft.access[accessKey(allocationId, userId)] ?? hasActiveMembership(allocationId, userId); const isNew = (row: GridRow) => draft.added.some((a) => a.userId === row.userId); const changes: Change[] = rows.flatMap((row) => [ @@ -252,7 +254,7 @@ export function ProjectMembersTab({ : []), ...allocations.flatMap((allocation) => { const membership = membershipOf(allocation.id, row.userId); - return hasAccess(allocation.id, row.userId) !== Boolean(membership) + return hasAccess(allocation.id, row.userId) !== hasActiveMembership(allocation.id, row.userId) ? [{ kind: "access" as const, row, allocation, membership }] : []; }), @@ -388,7 +390,7 @@ export function ProjectMembersTab({ {allocations.map((a) => { const checked = hasAccess(a.id, row.userId); - const changed = checked !== Boolean(membershipOf(a.id, row.userId)); + const changed = checked !== hasActiveMembership(a.id, row.userId); const label = `${row.name} in ${a.name}`; return ( = { ACTIVE: { variant: "active", label: "Active" }, PENDING: { variant: "pending", label: "Awaiting sign-in" }, - SUSPENDED: { variant: "warning", label: "Suspended" }, INACTIVE: { variant: "inactive", label: "Inactive" }, MERGED: { variant: "inactive", label: "Merged" }, }; diff --git a/web/src/mocks/handlers/allocations.ts b/web/src/mocks/handlers/allocations.ts index 43e9c1440..4c189a386 100644 --- a/web/src/mocks/handlers/allocations.ts +++ b/web/src/mocks/handlers/allocations.ts @@ -132,6 +132,15 @@ export const allocationsHandlers = [ return HttpResponse.json(found); }), + http.put<{ id: string }, Pick>( + "*/api/v1/compute-allocations/:id/status", + async ({ params, request }) => { + const found = allocations.find((a) => a.id === String(params.id)); + if (!found) return HttpResponse.json({ error: "allocation not found" }, { status: 404 }); + found.status = (await request.json()).status; + return HttpResponse.json(found); + }, + ), http.get<{ id: string }>("*/api/v1/compute-allocations/:id/resources", ({ params }) => { const id = String(params.id); return HttpResponse.json(resourcesByAlloc[id] ?? []); @@ -190,6 +199,16 @@ export const allocationsHandlers = [ } return HttpResponse.json({ error: "membership not found" }, { status: 404 }); }), + http.put<{ id: string }, Pick>( + "*/api/v1/compute-allocation-memberships/:id/status", + async ({ params, request }) => { + const all = Object.values(membersByAlloc).flat(); + const member = all.find((m) => m.id === String(params.id)); + if (!member) return HttpResponse.json({ error: "membership not found" }, { status: 404 }); + member.membership_status = (await request.json()).membership_status; + return HttpResponse.json(member); + }, + ), http.get<{ id: string }>("*/api/v1/compute-allocations/:id/change-requests", ({ params }) => { const id = String(params.id);