This is an automated email from the ASF dual-hosted git repository.
lahirujayathilake pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
The following commit(s) were added to refs/heads/master by this push:
new 5862f6b8e Let admins correct a pending user's email (#717)
5862f6b8e is described below
commit 5862f6b8e7399007cb76fbf23af6c1f1e10c0be5
Author: Yasith Jayawardana <[email protected]>
AuthorDate: Thu Nov 5 19:49:02 2026 -0500
Let admins correct a pending user's email (#717)
* Let admins correct a pending user's email
* Audit pending user email changes
---
api/core.openapi.yaml | 56 +++++++++++++++++++
internal/server/server.go | 1 +
internal/server/user.go | 35 ++++++++++++
pkg/service/interface.go | 1 +
pkg/service/mock.go | 62 ++++++++++++++++++++++
pkg/service/user.go | 50 +++++++++++++++++
pkg/service/user_onboard.go | 34 +++++++-----
pkg/service/user_onboard_integration_test.go | 29 ++++++++++
web/src/features/core/users/api.ts | 4 ++
.../core/users/components/PendingEmailField.tsx | 61 +++++++++++++++++++++
.../core/users/components/PermissionsDrawer.tsx | 4 ++
web/src/features/core/users/queries.ts | 10 ++++
12 files changed, 335 insertions(+), 12 deletions(-)
diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml
index 3110aa422..c46fb47ae 100644
--- a/api/core.openapi.yaml
+++ b/api/core.openapi.yaml
@@ -1166,6 +1166,11 @@ definitions:
note:
type: string
type: object
+ emailUpdateRequest:
+ properties:
+ email:
+ type: string
+ type: object
grantPrivilegeRequest:
properties:
privilege:
@@ -5607,6 +5612,57 @@ paths:
summary: List compute cluster users for a user
tags:
- Compute Cluster Users
+ /users/{id}/email:
+ put:
+ consumes:
+ - application/json
+ description: Changes the email first sign-in matches on. Refused once
the user
+ has a sign-in identity.
+ parameters:
+ - description: User ID
+ in: path
+ name: id
+ required: true
+ type: string
+ - description: Email patch
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/emailUpdateRequest'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/User'
+ "400":
+ description: Bad Request
+ schema:
+ properties:
+ error:
+ type: string
+ type: object
+ "404":
+ description: Not Found
+ schema:
+ properties:
+ error:
+ type: string
+ type: object
+ "409":
+ description: Conflict
+ schema:
+ properties:
+ error:
+ type: string
+ type: object
+ security:
+ - BearerAuth: []
+ summary: Update a pending user's email
+ tags:
+ - Users
/users/{id}/privileges:
get:
description: Returns DIRECT grants only (not role-derived). Combine with
`GET
diff --git a/internal/server/server.go b/internal/server/server.go
index 9e19ca16c..3ace6306f 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -62,6 +62,7 @@ func (s *Server) routes() {
s.router.RequirePrivilege("GET /users/{id}", models.UsersRead,
s.getUser)
s.router.RequirePrivilege("PUT /users/{id}", models.UsersWrite,
s.updateUser)
s.router.RequirePrivilege("PUT /users/{id}/status", models.UsersWrite,
s.updateUserStatus)
+ s.router.RequirePrivilege("PUT /users/{id}/email", models.UsersWrite,
s.updatePendingUserEmail)
s.router.RequirePrivilege("POST /users/merge", models.UsersWrite,
s.mergeUsers)
s.router.RequireAuth("GET /projects", s.listProjects)
diff --git a/internal/server/user.go b/internal/server/user.go
index 40cf6a4a0..9ca45ed3b 100644
--- a/internal/server/user.go
+++ b/internal/server/user.go
@@ -142,6 +142,41 @@ func (s *Server) updateUserStatus(w http.ResponseWriter, r
*http.Request) {
common.WriteJSON(w, http.StatusOK, u)
}
+type emailUpdateRequest struct {
+ Email string `json:"email"`
+}
+
+// @Summary Update a pending user's email
+// @Description Changes the email first sign-in matches on. Refused
once the user has a sign-in identity.
+// @Tags Users
+// @Security BearerAuth
+// @Accept json
+// @Produce json
+// @Param id path string true "User ID"
+// @Param request body emailUpdateRequest true "Email patch"
+// @Success 200 {object} models.User
+// @Failure 400 {object} object{error=string}
+// @Failure 404 {object} object{error=string}
+// @Failure 409 {object} object{error=string}
+// @Router /users/{id}/email [put]
+func (s *Server) updatePendingUserEmail(w http.ResponseWriter, r
*http.Request) {
+ var req emailUpdateRequest
+ if err := common.DecodeJSON(r, &req); err != nil {
+ common.WriteError(w, http.StatusBadRequest, err)
+ return
+ }
+ caller := common.RequireCaller(w, r)
+ if caller == nil {
+ return
+ }
+ u, err := s.svc.UpdatePendingUserEmail(r.Context(), caller.UserID,
r.PathValue("id"), req.Email)
+ if err != nil {
+ common.WriteServiceError(w, err)
+ return
+ }
+ common.WriteJSON(w, http.StatusOK, u)
+}
+
type userNameUpdateRequest struct {
FirstName string `json:"first_name"`
MiddleName string `json:"middle_name"`
diff --git a/pkg/service/interface.go b/pkg/service/interface.go
index 3eba9f10a..7330dcba9 100644
--- a/pkg/service/interface.go
+++ b/pkg/service/interface.go
@@ -59,6 +59,7 @@ type UserService interface {
ListUsersByOrganization(ctx context.Context, organizationID string)
([]models.User, error)
UpdateUser(ctx context.Context, user *models.User) error
UpdateUserStatus(ctx context.Context, id string, status
models.UserStatus) (*models.User, error)
+ UpdatePendingUserEmail(ctx context.Context, actorID, id, email string)
(*models.User, error)
DeleteUser(ctx context.Context, id string) error
MergeUsers(ctx context.Context, survivingID, retiringID string)
(*models.User, error)
ValidateUsername(name string) error
diff --git a/pkg/service/mock.go b/pkg/service/mock.go
index fe244d8d7..f6fea8d1e 100644
--- a/pkg/service/mock.go
+++ b/pkg/service/mock.go
@@ -457,6 +457,9 @@ var _ CoreService = &CoreServiceMock{}
// UpdateOrganizationFunc: func(ctx context.Context, org
*models.Organization) error {
// panic("mock out the UpdateOrganization method")
// },
+// UpdatePendingUserEmailFunc: func(ctx context.Context,
actorID string, id string, email string) (*models.User, error) {
+// panic("mock out the UpdatePendingUserEmail
method")
+// },
// UpdateProjectFunc: func(ctx context.Context, project
*models.Project) error {
// panic("mock out the UpdateProject method")
// },
@@ -926,6 +929,9 @@ type CoreServiceMock struct {
// UpdateOrganizationFunc mocks the UpdateOrganization method.
UpdateOrganizationFunc func(ctx context.Context, org
*models.Organization) error
+ // UpdatePendingUserEmailFunc mocks the UpdatePendingUserEmail method.
+ UpdatePendingUserEmailFunc func(ctx context.Context, actorID string, id
string, email string) (*models.User, error)
+
// UpdateProjectFunc mocks the UpdateProject method.
UpdateProjectFunc func(ctx context.Context, project *models.Project)
error
@@ -2064,6 +2070,17 @@ type CoreServiceMock struct {
// Org is the org argument value.
Org *models.Organization
}
+ // UpdatePendingUserEmail holds details about calls to the
UpdatePendingUserEmail method.
+ UpdatePendingUserEmail []struct {
+ // Ctx is the ctx argument value.
+ Ctx context.Context
+ // ActorID is the actorID argument value.
+ ActorID string
+ // ID is the id argument value.
+ ID string
+ // Email is the email argument value.
+ Email string
+ }
// UpdateProject holds details about calls to the UpdateProject
method.
UpdateProject []struct {
// Ctx is the ctx argument value.
@@ -2285,6 +2302,7 @@ type CoreServiceMock struct {
lockUpdateComputeClusterUser sync.RWMutex
lockUpdateMembershipStatus sync.RWMutex
lockUpdateOrganization sync.RWMutex
+ lockUpdatePendingUserEmail sync.RWMutex
lockUpdateProject sync.RWMutex
lockUpdateProjectStatus sync.RWMutex
lockUpdateRole sync.RWMutex
@@ -7703,6 +7721,50 @@ func (mock *CoreServiceMock) UpdateOrganizationCalls()
[]struct {
return calls
}
+// UpdatePendingUserEmail calls UpdatePendingUserEmailFunc.
+func (mock *CoreServiceMock) UpdatePendingUserEmail(ctx context.Context,
actorID string, id string, email string) (*models.User, error) {
+ if mock.UpdatePendingUserEmailFunc == nil {
+ panic("CoreServiceMock.UpdatePendingUserEmailFunc: method is
nil but CoreService.UpdatePendingUserEmail was just called")
+ }
+ callInfo := struct {
+ Ctx context.Context
+ ActorID string
+ ID string
+ Email string
+ }{
+ Ctx: ctx,
+ ActorID: actorID,
+ ID: id,
+ Email: email,
+ }
+ mock.lockUpdatePendingUserEmail.Lock()
+ mock.calls.UpdatePendingUserEmail =
append(mock.calls.UpdatePendingUserEmail, callInfo)
+ mock.lockUpdatePendingUserEmail.Unlock()
+ return mock.UpdatePendingUserEmailFunc(ctx, actorID, id, email)
+}
+
+// UpdatePendingUserEmailCalls gets all the calls that were made to
UpdatePendingUserEmail.
+// Check the length with:
+//
+// len(mockedCoreService.UpdatePendingUserEmailCalls())
+func (mock *CoreServiceMock) UpdatePendingUserEmailCalls() []struct {
+ Ctx context.Context
+ ActorID string
+ ID string
+ Email string
+} {
+ var calls []struct {
+ Ctx context.Context
+ ActorID string
+ ID string
+ Email string
+ }
+ mock.lockUpdatePendingUserEmail.RLock()
+ calls = mock.calls.UpdatePendingUserEmail
+ mock.lockUpdatePendingUserEmail.RUnlock()
+ return calls
+}
+
// UpdateProject calls UpdateProjectFunc.
func (mock *CoreServiceMock) UpdateProject(ctx context.Context, project
*models.Project) error {
if mock.UpdateProjectFunc == nil {
diff --git a/pkg/service/user.go b/pkg/service/user.go
index d131ef064..b25999c32 100644
--- a/pkg/service/user.go
+++ b/pkg/service/user.go
@@ -22,6 +22,7 @@ import (
"database/sql"
"errors"
"fmt"
+ "log/slog"
"github.com/apache/airavata-custos/pkg/events"
"github.com/apache/airavata-custos/pkg/models"
@@ -227,6 +228,55 @@ func (s *Service) UpdateUserStatus(ctx context.Context, id
string, status models
return existing, nil
}
+const (
+ userAuditEmailChangeRequested = "USER_EMAIL_CHANGE_REQUESTED"
+ userAuditEmailChanged = "USER_EMAIL_CHANGED"
+ userAuditEmailChangeFailed = "USER_EMAIL_CHANGE_FAILED"
+)
+
+// UpdatePendingUserEmail changes the email first sign-in matches on; refused
once a sub is bound.
+// The request and a failure are audited in their own transactions, so they
outlive a rollback.
+func (s *Service) UpdatePendingUserEmail(ctx context.Context, actorID, id,
email string) (*models.User, error) {
+ if email == "" {
+ return nil, fmt.Errorf("%w: email is required", ErrInvalidInput)
+ }
+ auditCtx := context.WithoutCancel(ctx)
+ audit := func(eventType string, details map[string]any) error {
+ return s.inTx(auditCtx, func(tx *sql.Tx) error { return
s.writeAuditTx(auditCtx, tx, "user", eventType, id, details) })
+ }
+ if err := audit(userAuditEmailChangeRequested,
map[string]any{"actor_id": actorID, "email": email}); err != nil {
+ return nil, fmt.Errorf("audit email change request: %w", err)
+ }
+ var updated *models.User
+ err := s.inTx(ctx, func(tx *sql.Tx) error {
+ user, err := s.lockUnboundPendingTx(ctx, tx, id)
+ if err != nil {
+ return err
+ }
+ previous := user.Email
+ user.Email = email
+ if err := s.users.Update(ctx, tx, user); err != nil {
+ return err
+ }
+ if err := s.writeAuditTx(ctx, tx, "user",
userAuditEmailChanged, id, map[string]any{
+ "actor_id": actorID,
+ "from": previous,
+ "to": email,
+ }); err != nil {
+ return err
+ }
+ updated = user
+ return s.eventBus.Publish(ctx, tx, events.UserUpdateEvent, user)
+ })
+ if err != nil {
+ if aerr := audit(userAuditEmailChangeFailed,
map[string]any{"actor_id": actorID, "error": err.Error()}); aerr != nil {
+ slog.ErrorContext(ctx, "audit email change failure",
"user_id", id, "error", aerr)
+ }
+ return nil, fmt.Errorf("update pending user email: %w", err)
+ }
+ return updated, nil
+}
+
// DeleteUser removes a user by ID.
func (s *Service) DeleteUser(ctx context.Context, id string) error {
if id == "" {
diff --git a/pkg/service/user_onboard.go b/pkg/service/user_onboard.go
index 59ac0541b..5abea8afd 100644
--- a/pkg/service/user_onboard.go
+++ b/pkg/service/user_onboard.go
@@ -398,20 +398,13 @@ func (s *Service) CompleteOnboarding(ctx context.Context,
claims *identity.Claim
return nil, err
}
if err := s.inTx(ctx, func(tx *sql.Tx) error {
- // Recheck under the row lock. A parallel submit may have
onboarded this user already.
- user, err := s.users.FindByIDTx(ctx, tx, matched.ID,
store.NoKeyUpdateLock)
+ // Recheck under the row lock. A parallel submit or email edit
may have changed this user.
+ user, err := s.lockUnboundPendingTx(ctx, tx, matched.ID)
if err != nil {
- return fmt.Errorf("lock user: %w", err)
- }
- if user == nil || user.Status != models.UserPending {
- return fmt.Errorf("%w: user is not waiting for
onboarding", ErrInvalidInput)
- }
- bound, err := s.userIdentities.FindByUserAndSource(ctx,
user.ID, identitySourceOIDC)
- if err != nil {
- return fmt.Errorf("lookup oidc identity: %w", err)
+ return err
}
- if bound != nil {
- return fmt.Errorf("%w: user already has a sign-in
identity", ErrInvalidInput)
+ if user.Email != claims.Email {
+ return fmt.Errorf("%w: user email changed during
sign-in", ErrInvalidInput)
}
current, err := s.agreements.FindCurrent(ctx)
@@ -444,6 +437,23 @@ func (s *Service) CompleteOnboarding(ctx context.Context,
claims *identity.Claim
return s.GetUser(ctx, matched.ID)
}
+// lockUnboundPendingTx locks a user that is PENDING with no sign-in identity
bound yet.
+func (s *Service) lockUnboundPendingTx(ctx context.Context, tx *sql.Tx, id
string) (*models.User, error) {
+ user, err := s.users.FindByIDTx(ctx, tx, id, store.NoKeyUpdateLock)
+ if err != nil {
+ return nil, fmt.Errorf("lock user: %w", err)
+ }
+ if user == nil || user.Status != models.UserPending {
+ return nil, fmt.Errorf("%w: user is not waiting for
onboarding", ErrInvalidInput)
+ }
+ if bound, err := s.userIdentities.FindByUserAndSource(ctx, id,
identitySourceOIDC); err != nil {
+ return nil, fmt.Errorf("lookup oidc identity: %w", err)
+ } else if bound != nil {
+ return nil, fmt.Errorf("%w: user already has a sign-in
identity", ErrInvalidInput)
+ }
+ return user, nil
+}
+
// A locked name is skipped, not refused, so onboarding still finishes.
func (s *Service) renameClusterAccountsTx(ctx context.Context, tx *sql.Tx,
user *models.User, name string) error {
accounts, err := s.clusterUsers.FindByUserTx(ctx, tx, user.ID)
diff --git a/pkg/service/user_onboard_integration_test.go
b/pkg/service/user_onboard_integration_test.go
index d6128ceb1..98f4cf518 100644
--- a/pkg/service/user_onboard_integration_test.go
+++ b/pkg/service/user_onboard_integration_test.go
@@ -529,3 +529,32 @@ func TestSetupSteps_FollowProvisioning(t *testing.T) {
}
}
}
+
+// Make sure only a pending user without a bound sub can change email.
+func TestUpdatePendingUserEmail(t *testing.T) {
+ database := setupTestDB(t)
+ svc := newTestService(database)
+ active := seedUser(t, database,
"active-"+uuid.NewString()[:8]+"@example.edu")
+ bound := seedPendingUserWithEmail(t, database,
"bound-"+uuid.NewString()[:8]+"@example.edu")
+ if _, err := svc.CreateUserIdentity(ctx(), &models.UserIdentity{UserID:
bound, Source: "oidc", ExternalID: "sub-x", OIDCSub: "sub-x"}); err != nil {
+ t.Fatalf("create oidc identity: %v", err)
+ }
+ pending := seedPendingUserWithEmail(t, database,
"pending-"+uuid.NewString()[:8]+"@example.edu")
+ alias := "alias-" + uuid.NewString()[:8] + "@example.edu"
+
+ for _, user := range []string{active, bound} {
+ if _, err := svc.UpdatePendingUserEmail(ctx(), active, user,
alias); !errors.Is(err, ErrInvalidInput) {
+ t.Errorf("user %s: got %v, want ErrInvalidInput", user,
err)
+ }
+ }
+ if u, err := svc.UpdatePendingUserEmail(ctx(), active, pending, alias);
err != nil || u.Email != alias {
+ t.Fatalf("pending user: got %+v, %v, want email %s", u, err,
alias)
+ }
+ for user, want := range map[string][3]int{active: {1, 0, 1}, pending:
{1, 1, 0}} {
+ for i, ev := range []string{userAuditEmailChangeRequested,
userAuditEmailChanged, userAuditEmailChangeFailed} {
+ if got := countAuditEventsOfType(t, database, ev,
user); got != want[i] {
+ t.Errorf("user %s audit %s: got %d, want %d",
user, ev, got, want[i])
+ }
+ }
+ }
+}
diff --git a/web/src/features/core/users/api.ts
b/web/src/features/core/users/api.ts
index 1d92e1330..0a776bb68 100644
--- a/web/src/features/core/users/api.ts
+++ b/web/src/features/core/users/api.ts
@@ -57,6 +57,10 @@ export async function getUser(id: string): Promise<User> {
return zGetUsersByIdResponse.parse(await apiFetch(`/users/${id}`));
}
+export async function updatePendingUserEmail(userId: string, email: string):
Promise<User> {
+ return zUser.parse(await apiFetch(`/users/${userId}/email`, { method: "PUT",
body: { email } }));
+}
+
export async function listRolesCatalog(): Promise<Role[]> {
return rolesResponseSchema.parse(await apiFetch("/roles"));
}
diff --git a/web/src/features/core/users/components/PendingEmailField.tsx
b/web/src/features/core/users/components/PendingEmailField.tsx
new file mode 100644
index 000000000..303b412a4
--- /dev/null
+++ b/web/src/features/core/users/components/PendingEmailField.tsx
@@ -0,0 +1,61 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+"use client";
+
+import { useAbility } from "@/shared/casl/AbilityProvider";
+import { Button } from "@/shared/ui/button";
+import { Input } from "@/shared/ui/input";
+import { useUpdatePendingUserEmail } from "../queries";
+
+// First sign-in matches a pending user by email, so an admin may correct it
until then.
+export function PendingEmailField({ userId, email }: { userId: string; email:
string }) {
+ const canEdit = useAbility().can("manage", "User");
+ const update = useUpdatePendingUserEmail();
+ if (!canEdit) return null;
+ return (
+ <>
+ <dt className="text-muted-foreground">Email</dt>
+ <dd>
+ <form
+ className="flex items-center gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const next = new FormData(event.currentTarget).get("email");
+ update.mutate({ userId, email: String(next).trim() });
+ }}
+ >
+ <Input
+ name="email"
+ type="email"
+ aria-label="Email"
+ className="h-8"
+ defaultValue={email}
+ />
+ <Button type="submit" variant="outline" size="sm"
disabled={update.isPending}>
+ Save
+ </Button>
+ </form>
+ {update.error ? (
+ <p role="alert" className="mt-1 text-xs text-destructive">
+ {update.error.message}
+ </p>
+ ) : null}
+ </dd>
+ </>
+ );
+}
diff --git a/web/src/features/core/users/components/PermissionsDrawer.tsx
b/web/src/features/core/users/components/PermissionsDrawer.tsx
index 9129bc92b..93871f511 100644
--- a/web/src/features/core/users/components/PermissionsDrawer.tsx
+++ b/web/src/features/core/users/components/PermissionsDrawer.tsx
@@ -37,6 +37,7 @@ import Link from "next/link";
import * as React from "react";
import { toast } from "sonner";
import type { ClusterAccountsView, UserAccountRow } from "../types";
+import { PendingEmailField } from "./PendingEmailField";
import { PrivilegeList } from "./PrivilegeList";
import { RoleAssignMenu } from "./RoleAssignMenu";
import { UserStatusBadge } from "./UserStatusBadge";
@@ -193,6 +194,9 @@ export function PermissionsDrawer({
<section>
<h3 className={HEADING}>Details</h3>
<dl className="grid grid-cols-[max-content_1fr] items-center
gap-x-4 gap-y-2 text-sm">
+ {user.status === "PENDING" ? (
+ <PendingEmailField key={user.id} userId={user.id}
email={user.email} />
+ ) : null}
<dt className="text-muted-foreground">Status</dt>
<dd>
<UserStatusBadge status={user.status} />
diff --git a/web/src/features/core/users/queries.ts
b/web/src/features/core/users/queries.ts
index d068e1d96..334ff65b9 100644
--- a/web/src/features/core/users/queries.ts
+++ b/web/src/features/core/users/queries.ts
@@ -38,6 +38,7 @@ import {
listUserIdentities,
listUsers,
removeUserRole,
+ updatePendingUserEmail,
} from "./api";
import type { CreateUserPayload } from "./schemas";
import type {
@@ -137,6 +138,15 @@ export function useCreateUser() {
});
}
+export function useUpdatePendingUserEmail() {
+ const client = useQueryClient();
+ return useMutation({
+ mutationFn: ({ userId, email }: { userId: string; email: string }) =>
+ updatePendingUserEmail(userId, email),
+ onSuccess: () => client.invalidateQueries({ queryKey: userKeys.all }),
+ });
+}
+
export function useUsers(params: UserListParams = {}, options: { enabled?:
boolean } = {}) {
return useQuery({
queryKey: userKeys.list(params),