Skip to content

feat: add template delete notification #14250

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Notify all template admins
  • Loading branch information
BrunoQuaresma committed Aug 13, 2024
commit 1f7046cdd8d5d0ac7c84dea5d77aae2a5dda1a2d
6 changes: 5 additions & 1 deletion coderd/notifications/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ var (
TemplateWorkspaceDormant = uuid.MustParse("0ea69165-ec14-4314-91f1-69566ac3c5a0")
TemplateWorkspaceAutoUpdated = uuid.MustParse("c34a0c09-0704-4cac-bd1c-0c0146811c2b")
TemplateWorkspaceMarkedForDeletion = uuid.MustParse("51ce2fdf-c9ca-4be1-8d70-628674f9bc42")
TemplateTemplateDeleted = uuid.MustParse("29a09665-2a4c-403f-9648-54301670e7be")
)

// Account-related events.
var (
TemplateUserAccountCreated = uuid.MustParse("4e19c0ac-94e1-4532-9515-d1801aa283b2")
TemplateUserAccountDeleted = uuid.MustParse("f44d9314-ad03-4bc8-95d0-5cad491da6b6")
)

// Template-related events.
var (
TemplateTemplateDeleted = uuid.MustParse("29a09665-2a4c-403f-9648-54301670e7be")
)
40 changes: 36 additions & 4 deletions coderd/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,28 @@
return
}

api.notifyTemplateDeleted(ctx, template, apiKey.UserID)
admins, err := findTemplateAdmins(ctx, api.Database)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching template admins.",
Detail: err.Error(),
})
return
}
for _, admin := range admins {
if admin.ID == apiKey.UserID {
continue
}
api.notifyTemplateDeleted(ctx, template, apiKey.UserID, admin.ID)
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.Response{
Message: "Template has been deleted!",
})
}

func (api *API) notifyTemplateDeleted(ctx context.Context, template database.Template, initiatorID uuid.UUID) {
if template.CreatedBy == initiatorID {
func (api *API) notifyTemplateDeleted(ctx context.Context, template database.Template, initiatorID uuid.UUID, receiverID uuid.UUID) {
if initiatorID == receiverID {
return
}

Expand All @@ -125,7 +138,7 @@
return
}

if _, err := api.NotificationsEnqueuer.Enqueue(ctx, template.CreatedBy, notifications.TemplateTemplateDeleted,
if _, err := api.NotificationsEnqueuer.Enqueue(ctx, receiverID, notifications.TemplateTemplateDeleted,
map[string]string{
"name": template.Name,
"initiator": initiator.Username,
Expand All @@ -133,7 +146,7 @@
// Associate this notification with all the related entities.
template.ID, template.OrganizationID,
); err != nil {
api.Logger.Warn(ctx, "failed to notify of template deletion", slog.F("deleted_template", template.ID), slog.Error(err))

Check failure on line 149 in coderd/templates.go

View workflow job for this annotation

GitHub Actions / lint

ruleguard: uuid.UUID field "deleted_template" must have "_id" suffix. (gocritic)
}
}

Expand Down Expand Up @@ -979,3 +992,22 @@
MaxPortShareLevel: maxPortShareLevel,
}
}

// findTemplateAdmins fetches all users with template admin permission including owners.
func findTemplateAdmins(ctx context.Context, store database.Store) ([]database.GetUsersRow, error) {
// Notice: we can't scrape the user information in parallel as pq
// fails with: unexpected describe rows response: 'D'
owners, err := store.GetUsers(ctx, database.GetUsersParams{
RbacRole: []string{codersdk.RoleOwner},
})
if err != nil {
return nil, xerrors.Errorf("get owners: %w", err)
}
templateAdmins, err := store.GetUsers(ctx, database.GetUsersParams{
RbacRole: []string{codersdk.RoleTemplateAdmin},
})
if err != nil {
return nil, xerrors.Errorf("get template admins: %w", err)
}
return append(owners, templateAdmins...), nil
}
97 changes: 44 additions & 53 deletions coderd/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1328,65 +1328,56 @@ func TestTemplateMetrics(t *testing.T) {
)
}

func TestTemplateNotifications(t *testing.T) {
func TestNotifyDeletedTemplate(t *testing.T) {
t.Parallel()

t.Run("Delete", func(t *testing.T) {
t.Run("OnlyNotifyOwnersAndTemplateAdmins", func(t *testing.T) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a separate test to validate the functionality in isolation; you can then reduce some complexity in this test and keep it nicely scoped.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if I got it. What should I separate and what complexity does it solve?

t.Parallel()

t.Run("InitiatorNotTemplateAdmin", func(t *testing.T) {
t.Parallel()

var (
notifyEnq = &testutil.FakeNotificationsEnqueuer{}
client = coderdtest.New(t, &coderdtest.Options{
IncludeProvisionerDaemon: true,
NotificationsEnqueuer: notifyEnq,
})
user = coderdtest.CreateFirstUser(t, client)
version = coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, nil)
_ = coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template = coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
initiatorClient, _ = coderdtest.CreateAnotherUser(t, client, user.OrganizationID, rbac.RoleOwner())
ctx = testutil.Context(t, testutil.WaitLong)
)

// When: initiator is not the template admin
err := initiatorClient.DeleteTemplate(ctx, template.ID)
require.NoError(t, err)

// Then: the template admin should receive a notification
require.Len(t, notifyEnq.Sent, 1)
require.Equal(t, notifyEnq.Sent[0].TemplateID, notifications.TemplateTemplateDeleted)
require.Equal(t, notifyEnq.Sent[0].UserID, template.CreatedByID)
require.Contains(t, notifyEnq.Sent[0].Targets, template.ID)
require.Contains(t, notifyEnq.Sent[0].Targets, template.OrganizationID)
require.Contains(t, notifyEnq.Sent[0].Labels["name"], template.Name)
require.Contains(t, notifyEnq.Sent[0].Labels["initiator"], coderdtest.FirstUserParams.Username)
})
var (
notifyEnq = &testutil.FakeNotificationsEnqueuer{}
client = coderdtest.New(t, &coderdtest.Options{
IncludeProvisionerDaemon: true,
NotificationsEnqueuer: notifyEnq,
})
firstUser = coderdtest.CreateFirstUser(t, client)
version = coderdtest.CreateTemplateVersion(t, client, firstUser.OrganizationID, nil)
_ = coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template = coderdtest.CreateTemplate(t, client, firstUser.OrganizationID, version.ID)
ctx = testutil.Context(t, testutil.WaitLong)
)

t.Run("InitiatorIsTemplateAdmin", func(t *testing.T) {
t.Parallel()
_, anotherOwner := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID, rbac.RoleOwner())
_, tmplAdmin := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID, rbac.RoleTemplateAdmin())
coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID, rbac.RoleMember())

var (
notifyEnq = &testutil.FakeNotificationsEnqueuer{}
client = coderdtest.New(t, &coderdtest.Options{
IncludeProvisionerDaemon: true,
NotificationsEnqueuer: notifyEnq,
})
user = coderdtest.CreateFirstUser(t, client)
version = coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, nil)
_ = coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template = coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
ctx = testutil.Context(t, testutil.WaitLong)
)

// When: initiator is the template admin
err := client.DeleteTemplate(ctx, template.ID)
require.NoError(t, err)
// When: template is deleted
err := client.DeleteTemplate(ctx, template.ID)
require.NoError(t, err)

// Then: the template admin should not receive a notification
require.Len(t, notifyEnq.Sent, 0)
})
// Then: the template owners and template admins should receive the notification
shouldBeNotified := []uuid.UUID{anotherOwner.ID, tmplAdmin.ID}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it'd be good to explicitly specify that the first user is not receiving the notification because they initiated it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it'd also be a good idea here to create another admin but with a different role like user admin, and validate that they don't receive the notification either.

var deleteTemplateNotifications []*testutil.Notification
for _, n := range notifyEnq.Sent {
if n.TemplateID == notifications.TemplateTemplateDeleted {
deleteTemplateNotifications = append(deleteTemplateNotifications, n)
}
}
require.Len(t, deleteTemplateNotifications, len(shouldBeNotified))

for _, userID := range shouldBeNotified {
var notification *testutil.Notification
for _, n := range deleteTemplateNotifications {
if n.UserID == userID {
notification = n
break
}
}
require.NotNil(t, notification)
require.Contains(t, notification.Targets, template.ID)
require.Contains(t, notification.Targets, template.OrganizationID)
require.Equal(t, notification.Labels["name"], template.Name)
require.Equal(t, notification.Labels["initiator"], coderdtest.FirstUserParams.Username)
}
})
}
Loading