feat: add break-glass user email update (#29256)
Adds an owner-only experimental API and hidden CLI command for break-glass user email corrections. The operation verifies the existing email, updates it transactionally, clears outstanding password-reset state, revokes the target user's Coder sessions and API tokens, and records successful and failed authenticated attempts in the audit log. External-auth links remain unchanged. Generated by Coder Agents.
This commit is contained in:
1 parent
1321b41854
commit
2cf819bfca
19 files changed
+915
No files matched your search
@@ -8326,6 +8326,22 @@ func (q *querier) UpdateUserDeletedByID(ctx context.Context, id uuid.UUID) error
|
||||
return deleteQ(q.log, q.auth, q.db.GetUserByID, q.db.UpdateUserDeletedByID)(ctx, id)
|
||||
}
|
||||
|
||||
func (q *querier) UpdateUserEmail(ctx context.Context, arg database.UpdateUserEmailParams) (database.User, error) {
|
||||
// Resolve the existing user by old email to obtain the RBAC object for
|
||||
// authorization. The handler enforces the built-in owner role gate; this
|
||||
// check adds defense-in-depth at the database layer.
|
||||
existing, err := q.db.GetUserByEmailOrUsername(ctx, database.GetUserByEmailOrUsernameParams{
|
||||
Email: arg.OldEmail,
|
||||
})
|
||||
if err != nil {
|
||||
return database.User{}, err
|
||||
}
|
||||
if err := q.authorizeContext(ctx, policy.ActionUpdate, existing); err != nil {
|
||||
return database.User{}, err
|
||||
}
|
||||
return q.db.UpdateUserEmail(ctx, arg)
|
||||
}
|
||||
|
||||
func (q *querier) UpdateUserGithubComUserID(ctx context.Context, arg database.UpdateUserGithubComUserIDParams) error {
|
||||
user, err := q.db.GetUserByID(ctx, arg.ID)
|
||||
if err != nil {
|
||||
|
||||
@@ -3159,6 +3159,13 @@ func (s *MethodTestSuite) TestUser() {
|
||||
dbm.EXPECT().UpdateUserDeletedByID(gomock.Any(), u.ID).Return(nil).AnyTimes()
|
||||
check.Args(u.ID).Asserts(u, policy.ActionDelete).Returns()
|
||||
}))
|
||||
s.Run("UpdateUserEmail", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
|
||||
u := testutil.Fake(s.T(), faker, database.User{})
|
||||
arg := database.UpdateUserEmailParams{OldEmail: u.Email, NewEmail: "new@example.com", UpdatedAt: u.UpdatedAt}
|
||||
dbm.EXPECT().GetUserByEmailOrUsername(gomock.Any(), database.GetUserByEmailOrUsernameParams{Email: u.Email}).Return(u, nil).AnyTimes()
|
||||
dbm.EXPECT().UpdateUserEmail(gomock.Any(), arg).Return(u, nil).AnyTimes()
|
||||
check.Args(arg).Asserts(u, policy.ActionUpdate).Returns(u)
|
||||
}))
|
||||
s.Run("UpdateUserGithubComUserID", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
|
||||
u := testutil.Fake(s.T(), faker, database.User{})
|
||||
arg := database.UpdateUserGithubComUserIDParams{ID: u.ID}
|
||||
|
||||
+8
@@ -5801,6 +5801,14 @@ func (m queryMetricsStore) UpdateUserDeletedByID(ctx context.Context, id uuid.UU
|
||||
return r0
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) UpdateUserEmail(ctx context.Context, arg database.UpdateUserEmailParams) (database.User, error) {
|
||||
start := time.Now()
|
||||
r0, r1 := m.s.UpdateUserEmail(ctx, arg)
|
||||
m.queryLatencies.WithLabelValues("UpdateUserEmail").Observe(time.Since(start).Seconds())
|
||||
m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "UpdateUserEmail").Inc()
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) UpdateUserGithubComUserID(ctx context.Context, arg database.UpdateUserGithubComUserIDParams) error {
|
||||
start := time.Now()
|
||||
r0 := m.s.UpdateUserGithubComUserID(ctx, arg)
|
||||
|
||||
Generated
+15
@@ -10962,6 +10962,21 @@ func (mr *MockStoreMockRecorder) UpdateUserDeletedByID(ctx, id any) *gomock.Call
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateUserDeletedByID", reflect.TypeOf((*MockStore)(nil).UpdateUserDeletedByID), ctx, id)
|
||||
}
|
||||
|
||||
// UpdateUserEmail mocks base method.
|
||||
func (m *MockStore) UpdateUserEmail(ctx context.Context, arg database.UpdateUserEmailParams) (database.User, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "UpdateUserEmail", ctx, arg)
|
||||
ret0, _ := ret[0].(database.User)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// UpdateUserEmail indicates an expected call of UpdateUserEmail.
|
||||
func (mr *MockStoreMockRecorder) UpdateUserEmail(ctx, arg any) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateUserEmail", reflect.TypeOf((*MockStore)(nil).UpdateUserEmail), ctx, arg)
|
||||
}
|
||||
|
||||
// UpdateUserGithubComUserID mocks base method.
|
||||
func (m *MockStore) UpdateUserGithubComUserID(ctx context.Context, arg database.UpdateUserGithubComUserIDParams) error {
|
||||
m.ctrl.T.Helper()
|
||||
|
||||
Generated
+1
@@ -1587,6 +1587,7 @@ type sqlcQuerier interface {
|
||||
UpdateUserChatCustomPrompt(ctx context.Context, arg UpdateUserChatCustomPromptParams) (UserConfig, error)
|
||||
UpdateUserCodeDiffDisplayMode(ctx context.Context, arg UpdateUserCodeDiffDisplayModeParams) (string, error)
|
||||
UpdateUserDeletedByID(ctx context.Context, id uuid.UUID) error
|
||||
UpdateUserEmail(ctx context.Context, arg UpdateUserEmailParams) (User, error)
|
||||
UpdateUserGithubComUserID(ctx context.Context, arg UpdateUserGithubComUserIDParams) error
|
||||
UpdateUserHashedOneTimePasscode(ctx context.Context, arg UpdateUserHashedOneTimePasscodeParams) error
|
||||
UpdateUserHashedPassword(ctx context.Context, arg UpdateUserHashedPasswordParams) error
|
||||
|
||||
@@ -19106,3 +19106,74 @@ func sessionFamilyCounts(t *testing.T, data json.RawMessage) map[codersdk.AppFam
|
||||
require.NoError(t, err)
|
||||
return counts
|
||||
}
|
||||
|
||||
func TestUpdateUserEmail(t *testing.T) {
|
||||
t.Parallel()
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
sqlDB := testSQLDB(t)
|
||||
err := migrations.Up(sqlDB)
|
||||
require.NoError(t, err)
|
||||
db := database.New(sqlDB)
|
||||
ctx := context.Background()
|
||||
|
||||
// SQL-specific: the WHERE clause matches old_email case-insensitively.
|
||||
t.Run("MatchesCaseInsensitively", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
origEmail := "CaseSensitive" + testutil.GetRandomName(t) + "@example.com"
|
||||
user := dbgen.User(t, db, database.User{Email: origEmail})
|
||||
updated, err := db.UpdateUserEmail(ctx, database.UpdateUserEmailParams{
|
||||
OldEmail: strings.ToLower(origEmail),
|
||||
NewEmail: "newcase" + testutil.GetRandomName(t) + "@example.com",
|
||||
UpdatedAt: dbtime.Now(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, user.ID, updated.ID, "should match the same user case-insensitively")
|
||||
})
|
||||
|
||||
// SQL-specific: the WHERE clause excludes soft-deleted users.
|
||||
t.Run("DoesNotMatchDeletedUsers", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
user := dbgen.User(t, db, database.User{})
|
||||
err := db.UpdateUserDeletedByID(ctx, user.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = db.UpdateUserEmail(ctx, database.UpdateUserEmailParams{
|
||||
OldEmail: user.Email,
|
||||
NewEmail: "shouldfail@example.com",
|
||||
UpdatedAt: dbtime.Now(),
|
||||
})
|
||||
require.ErrorIs(t, err, sql.ErrNoRows)
|
||||
})
|
||||
|
||||
// SQL-specific: new_email is stored verbatim (no lower-casing on write).
|
||||
t.Run("PreservesNewEmailCasing", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
user := dbgen.User(t, db, database.User{})
|
||||
mixedCase := "Mixed.Case." + testutil.GetRandomName(t) + "@Example.COM"
|
||||
updated, err := db.UpdateUserEmail(ctx, database.UpdateUserEmailParams{
|
||||
OldEmail: user.Email,
|
||||
NewEmail: mixedCase,
|
||||
UpdatedAt: dbtime.Now(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, mixedCase, updated.Email, "new email casing must be preserved exactly")
|
||||
})
|
||||
|
||||
// SQL-specific: the unique index name is users_email_lower_idx and the
|
||||
// constraint fires on a case-variant collision.
|
||||
t.Run("RejectsUniqueEmailCollision", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
user1 := dbgen.User(t, db, database.User{})
|
||||
user2 := dbgen.User(t, db, database.User{})
|
||||
_, err := db.UpdateUserEmail(ctx, database.UpdateUserEmailParams{
|
||||
OldEmail: user1.Email,
|
||||
NewEmail: strings.ToUpper(user2.Email),
|
||||
UpdatedAt: dbtime.Now(),
|
||||
})
|
||||
require.True(t, database.IsUniqueViolation(err, database.UniqueUsersEmailLowerIndex),
|
||||
"expected unique_violation on users_email_lower_idx, got: %v", err)
|
||||
})
|
||||
}
|
||||
Generated
+48
@@ -31815,6 +31815,54 @@ func (q *sqlQuerier) UpdateUserDeletedByID(ctx context.Context, id uuid.UUID) er
|
||||
return err
|
||||
}
|
||||
|
||||
const updateUserEmail = `-- name: UpdateUserEmail :one
|
||||
UPDATE
|
||||
users
|
||||
SET
|
||||
email = $1,
|
||||
updated_at = $2,
|
||||
hashed_one_time_passcode = NULL,
|
||||
one_time_passcode_expires_at = NULL
|
||||
WHERE
|
||||
LOWER(email) = LOWER($3)
|
||||
AND deleted = false
|
||||
RETURNING id, email, username, hashed_password, created_at, updated_at, status, rbac_roles, login_type, avatar_url, deleted, last_seen_at, quiet_hours_schedule, name, github_com_user_id, hashed_one_time_passcode, one_time_passcode_expires_at, is_system, is_service_account, chat_spend_limit_micros
|
||||
`
|
||||
|
||||
type UpdateUserEmailParams struct {
|
||||
NewEmail string `db:"new_email" json:"new_email"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||
OldEmail string `db:"old_email" json:"old_email"`
|
||||
}
|
||||
|
||||
func (q *sqlQuerier) UpdateUserEmail(ctx context.Context, arg UpdateUserEmailParams) (User, error) {
|
||||
row := q.db.QueryRowContext(ctx, updateUserEmail, arg.NewEmail, arg.UpdatedAt, arg.OldEmail)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.Username,
|
||||
&i.HashedPassword,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Status,
|
||||
&i.RBACRoles,
|
||||
&i.LoginType,
|
||||
&i.AvatarURL,
|
||||
&i.Deleted,
|
||||
&i.LastSeenAt,
|
||||
&i.QuietHoursSchedule,
|
||||
&i.Name,
|
||||
&i.GithubComUserID,
|
||||
&i.HashedOneTimePasscode,
|
||||
&i.OneTimePasscodeExpiresAt,
|
||||
&i.IsSystem,
|
||||
&i.IsServiceAccount,
|
||||
&i.ChatSpendLimitMicros,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const updateUserGithubComUserID = `-- name: UpdateUserGithubComUserID :exec
|
||||
UPDATE
|
||||
users
|
||||
|
||||
@@ -396,6 +396,19 @@ SET
|
||||
WHERE
|
||||
id = $1;
|
||||
|
||||
-- name: UpdateUserEmail :one
|
||||
UPDATE
|
||||
users
|
||||
SET
|
||||
email = @new_email,
|
||||
updated_at = @updated_at,
|
||||
hashed_one_time_passcode = NULL,
|
||||
one_time_passcode_expires_at = NULL
|
||||
WHERE
|
||||
LOWER(email) = LOWER(@old_email)
|
||||
AND deleted = false
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateUserDeletedByID :exec
|
||||
UPDATE
|
||||
users
|
||||
|
||||
Reference in new issue
Block a user