Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fix: add postgres triggers to remove deleted users from user_links#12117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Emyrk merged 27 commits intomainfromstevenmasley/deleted_user_links
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
27 commits
Select commitHold shift + click to select a range
7e17c09
chore: add database test fixture to insert non-unique linked_ids
EmyrkFeb 12, 2024
4abe528
mend
EmyrkFeb 12, 2024
5fdbf98
mend
EmyrkFeb 12, 2024
513e1cc
rename test fixute
EmyrkFeb 12, 2024
8435d59
add extra case
EmyrkFeb 12, 2024
9e3085d
accidental file change
EmyrkFeb 12, 2024
fea25b0
chore: add database test fixture to insert non-unique linked_ids
EmyrkFeb 12, 2024
51de1f4
mend
EmyrkFeb 12, 2024
0e9270b
mend
EmyrkFeb 12, 2024
0b80aa5
rename test fixute
EmyrkFeb 12, 2024
7030101
accidental file change
EmyrkFeb 12, 2024
4d89937
chore: creaet unit test to exercise failed email change bug
EmyrkFeb 12, 2024
4628c39
Add links to existing issues
EmyrkFeb 13, 2024
c426259
fix: add postgres triggers to keep user_links clear of deleted users
EmyrkFeb 13, 2024
188f03b
Add migrations to prevent deleted users with links
EmyrkFeb 13, 2024
e0902a3
Force soft delete of users, do not allow un-delete
EmyrkFeb 13, 2024
e3788d5
fix some tests
EmyrkFeb 13, 2024
ee6aabc
move code
EmyrkFeb 13, 2024
f2c90c1
linting
EmyrkFeb 13, 2024
c6ff417
move migration
EmyrkFeb 13, 2024
fa3401e
Make gen
EmyrkFeb 13, 2024
a54b652
fix user gen
EmyrkFeb 13, 2024
b70a8c9
remove excess fixture file
EmyrkFeb 13, 2024
f8b63ca
rename SoftDelete back to UpdateDeleted
EmyrkFeb 20, 2024
149875e
Fix dbauthz
EmyrkFeb 20, 2024
f97567c
Merge remote-tracking branch 'origin/main' into stevenmasley/deleted_…
EmyrkFeb 20, 2024
f28491e
bump migrations
EmyrkFeb 20, 2024
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
6 changes: 1 addition & 5 deletionscli/delete_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,6 @@ import (

"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
Expand DownExpand Up@@ -95,10 +94,7 @@ func TestDelete(t *testing.T) {
// this way.
ctx := testutil.Context(t, testutil.WaitShort)
// nolint:gocritic // Unit test
err := api.Database.UpdateUserDeletedByID(dbauthz.AsSystemRestricted(ctx), database.UpdateUserDeletedByIDParams{
ID: deleteMeUser.ID,
Deleted: true,
})
err := api.Database.UpdateUserDeletedByID(dbauthz.AsSystemRestricted(ctx), deleteMeUser.ID)
require.NoError(t, err)

inv, root := clitest.New(t, "delete", fmt.Sprintf("%s/%s", deleteMeUser.ID, workspace.Name), "-y", "--orphan")
Expand Down
22 changes: 2 additions & 20 deletionscoderd/database/dbauthz/dbauthz.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -607,16 +607,6 @@ func (q *querier) SoftDeleteTemplateByID(ctx context.Context, id uuid.UUID) erro
return deleteQ(q.log, q.auth, q.db.GetTemplateByID, deleteF)(ctx, id)
}

func (q *querier) SoftDeleteUserByID(ctx context.Context, id uuid.UUID) error {
deleteF := func(ctx context.Context, id uuid.UUID) error {
return q.db.UpdateUserDeletedByID(ctx, database.UpdateUserDeletedByIDParams{
ID: id,
Deleted: true,
})
}
return deleteQ(q.log, q.auth, q.db.GetUserByID, deleteF)(ctx, id)
}

func (q *querier) SoftDeleteWorkspaceByID(ctx context.Context, id uuid.UUID) error {
return deleteQ(q.log, q.auth, q.db.GetWorkspaceByID, func(ctx context.Context, id uuid.UUID) error {
return q.db.UpdateWorkspaceDeletedByID(ctx, database.UpdateWorkspaceDeletedByIDParams{
Expand DownExpand Up@@ -2881,16 +2871,8 @@ func (q *querier) UpdateUserAppearanceSettings(ctx context.Context, arg database
return q.db.UpdateUserAppearanceSettings(ctx, arg)
}

// UpdateUserDeletedByID
// Deprecated: Delete this function in favor of 'SoftDeleteUserByID'. Deletes are
// irreversible.
func (q *querier) UpdateUserDeletedByID(ctx context.Context, arg database.UpdateUserDeletedByIDParams) error {
fetch := func(ctx context.Context, arg database.UpdateUserDeletedByIDParams) (database.User, error) {
return q.db.GetUserByID(ctx, arg.ID)
}
// This uses the rbac.ActionDelete action always as this function should always delete.
// We should delete this function in favor of 'SoftDeleteUserByID'.
return deleteQ(q.log, q.auth, fetch, q.db.UpdateUserDeletedByID)(ctx, arg)
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) UpdateUserHashedPassword(ctx context.Context, arg database.UpdateUserHashedPasswordParams) error {
Expand Down
9 changes: 1 addition & 8 deletionscoderd/database/dbauthz/dbauthz_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1015,17 +1015,10 @@ func (s *MethodTestSuite) TestUser() {
LoginType: database.LoginTypeOIDC,
}).Asserts(u, rbac.ActionUpdate)
}))
s.Run("SoftDeleteUserByID", s.Subtest(func(db database.Store, check *expects) {
s.Run("UpdateUserDeletedByID", s.Subtest(func(db database.Store, check *expects) {
u := dbgen.User(s.T(), db, database.User{})
check.Args(u.ID).Asserts(u, rbac.ActionDelete).Returns()
}))
s.Run("UpdateUserDeletedByID", s.Subtest(func(db database.Store, check *expects) {
u := dbgen.User(s.T(), db, database.User{Deleted: true})
check.Args(database.UpdateUserDeletedByIDParams{
ID: u.ID,
Deleted: true,
}).Asserts(u, rbac.ActionDelete).Returns()
}))
s.Run("UpdateUserHashedPassword", s.Subtest(func(db database.Store, check *expects) {
u := dbgen.User(s.T(), db, database.User{})
check.Args(database.UpdateUserHashedPasswordParams{
Expand Down
5 changes: 1 addition & 4 deletionscoderd/database/dbgen/dbgen.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,10 +311,7 @@ func User(t testing.TB, db database.Store, orig database.User) database.User {
}

if orig.Deleted {
err = db.UpdateUserDeletedByID(genCtx, database.UpdateUserDeletedByIDParams{
ID: user.ID,
Deleted: orig.Deleted,
})
err = db.UpdateUserDeletedByID(genCtx, user.ID)
require.NoError(t, err, "set user as deleted")
}
return user
Expand Down
51 changes: 30 additions & 21 deletionscoderd/database/dbmem/dbmem.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -733,6 +733,18 @@ func isNotNull(v interface{}) bool {
return reflect.ValueOf(v).FieldByName("Valid").Bool()
}

// Took the error from the real database.
var deletedUserLinkError = &pq.Error{
Severity: "ERROR",
// "raise_exception" error
Code: "P0001",
Message: "Cannot create user_link for deleted user",
Where: "PL/pgSQL function insert_user_links_fail_if_user_deleted() line 7 at RAISE",
File: "pl_exec.c",
Line: "3864",
Routine: "exec_stmt_raise",
}

func (*FakeQuerier) AcquireLock(_ context.Context, _ int64) error {
return xerrors.New("AcquireLock must only be called within a transaction")
}
Expand DownExpand Up@@ -5560,6 +5572,10 @@ func (q *FakeQuerier) InsertUserLink(_ context.Context, args database.InsertUser
q.mutex.Lock()
defer q.mutex.Unlock()

if u, err := q.getUserByIDNoLock(args.UserID); err == nil && u.Deleted {
return database.UserLink{}, deletedUserLinkError
}

//nolint:gosimple
link := database.UserLink{
UserID: args.UserID,
Expand DownExpand Up@@ -6724,33 +6740,22 @@ func (q *FakeQuerier) UpdateUserAppearanceSettings(_ context.Context, arg databa
return database.User{}, sql.ErrNoRows
}

func (q *FakeQuerier) UpdateUserDeletedByID(_ context.Context, params database.UpdateUserDeletedByIDParams) error {
if err := validateDatabaseType(params); err != nil {
return err
}

func (q *FakeQuerier) UpdateUserDeletedByID(_ context.Context, id uuid.UUID) error {
q.mutex.Lock()
defer q.mutex.Unlock()

for i, u := range q.users {
if u.ID ==params.ID {
u.Deleted =params.Deleted
if u.ID ==id {
u.Deleted =true
q.users[i] = u
// NOTE: In the real world, this is done by a trigger.
i := 0
for {
if i >= len(q.apiKeys) {
break
}
k := q.apiKeys[i]
if k.UserID == u.ID {
q.apiKeys[i] = q.apiKeys[len(q.apiKeys)-1]
q.apiKeys = q.apiKeys[:len(q.apiKeys)-1]
// We removed an element, so decrement
i--
}
i++
}
q.apiKeys = slices.DeleteFunc(q.apiKeys, func(u database.APIKey) bool {
return id == u.UserID
})

q.userLinks = slices.DeleteFunc(q.userLinks, func(u database.UserLink) bool {
return id == u.UserID
})
return nil
}
}
Expand DownExpand Up@@ -6804,6 +6809,10 @@ func (q *FakeQuerier) UpdateUserLink(_ context.Context, params database.UpdateUs
q.mutex.Lock()
defer q.mutex.Unlock()

if u, err := q.getUserByIDNoLock(params.UserID); err == nil && u.Deleted {
return database.UserLink{}, deletedUserLinkError
}

for i, link := range q.userLinks {
if link.UserID == params.UserID && link.LoginType == params.LoginType {
link.OAuthAccessToken = params.OAuthAccessToken
Expand Down
6 changes: 3 additions & 3 deletionscoderd/database/dbmetrics/dbmetrics.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

2 changes: 1 addition & 1 deletioncoderd/database/dbmock/dbmock.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

29 changes: 27 additions & 2 deletionscoderd/database/dump.sql
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
DROP TRIGGER IF EXISTS trigger_update_users ON users;
DROP FUNCTION IF EXISTS delete_deleted_user_resources;

DROP TRIGGER IF EXISTS trigger_upsert_user_links ON user_links;
DROP FUNCTION IF EXISTS insert_user_links_fail_if_user_deleted;

-- Restore the previous trigger
CREATE FUNCTION delete_deleted_user_api_keys() RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
BEGIN
IF (NEW.deleted) THEN
DELETE FROM api_keys
WHERE user_id = OLD.id;
END IF;
RETURN NEW;
END;
$$;


CREATE TRIGGER trigger_update_users
AFTER INSERT OR UPDATE ON users
FOR EACH ROW
WHEN (NEW.deleted = true)
EXECUTE PROCEDURE delete_deleted_user_api_keys();
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
-- We need to delete all existing user_links for soft-deleted users
DELETE FROM
user_links
WHERE
user_id
IN (
SELECT id FROM users WHERE deleted
);

-- Drop the old trigger
DROP TRIGGER trigger_update_users ON users;
-- Drop the old function
DROP FUNCTION delete_deleted_user_api_keys;

-- When we soft-delete a user, we also want to delete their API key.
-- The previous function deleted all api keys. This extends that with user_links.
CREATE FUNCTION delete_deleted_user_resources() RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
BEGIN
IF (NEW.deleted) THEN
-- Remove their api_keys
DELETE FROM api_keys
WHERE user_id = OLD.id;

-- Remove their user_links
-- Their login_type is preserved in the users table.
-- Matching this user back to the link can still be done by their
-- email if the account is undeleted. Although that is not a guarantee.
DELETE FROM user_links
WHERE user_id = OLD.id;
END IF;
RETURN NEW;
END;
$$;


-- Update it to the new trigger
CREATE TRIGGER trigger_update_users
AFTER INSERT OR UPDATE ON users
FOR EACH ROW
WHEN (NEW.deleted = true)
EXECUTE PROCEDURE delete_deleted_user_resources();


-- Prevent adding new user_links for soft-deleted users
CREATE FUNCTION insert_user_links_fail_if_user_deleted() RETURNS trigger
LANGUAGE plpgsql
AS $$

DECLARE
BEGIN
IF (NEW.user_id IS NOT NULL) THEN
IF (SELECT deleted FROM users WHERE id = NEW.user_id LIMIT 1) THEN
RAISE EXCEPTION 'Cannot create user_link for deleted user';
END IF;
END IF;
RETURN NEW;
END;
$$;

CREATE TRIGGER trigger_upsert_user_links
BEFORE INSERT OR UPDATE ON user_links
FOR EACH ROW
EXECUTE PROCEDURE insert_user_links_fail_if_user_deleted();
2 changes: 1 addition & 1 deletioncoderd/database/querier.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

11 changes: 3 additions & 8 deletionscoderd/database/queries.sql.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

2 changes: 1 addition & 1 deletioncoderd/database/queries/users.sql
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -116,7 +116,7 @@ WHERE
UPDATE
users
SET
deleted =$2
deleted =true
WHERE
id = $1;

Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp