Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 66 additions & 2 deletions api/core.openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1134,14 +1134,12 @@ definitions:
- PENDING
- ACTIVE
- INACTIVE
- SUSPENDED
- MERGED
type: string
x-enum-varnames:
- UserPending
- UserActive
- UserInactive
- UserSuspended
- UserMerged
UserType:
enum:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 9 additions & 6 deletions connectors/ACCESS/AMIE-Processor/handler/request_person_merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 2 additions & 0 deletions connectors/COmanage/Identity-Provisioner/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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=<id> username=<local> uid=<n>`. |
| `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=<id> username=<local> 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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package operations

import (
"cmp"
"encoding/json"
"fmt"
)
Expand Down Expand Up @@ -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"], &current)
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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package operations

import (
"context"
"encoding/json"
"errors"
"fmt"

Expand Down Expand Up @@ -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
}
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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)
}
}
Loading