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 3 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
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
INSERT INTO
notification_templates (
id,
name,
title_template,
body_template,
"group",
actions
)
VALUES (
'29a09665-2a4c-403f-9648-54301670e7be',
'Template Deleted',
E'Template "{{.Labels.name}}" deleted',
E'Hi {{.UserName}}\n\nThe template **{{.Labels.name}}** was deleted by **{{ .Labels.initiator }}**.',
'Template Events',
'[
{
"label": "View templates",
"url": "{{ base_url }}/templates"
}
]'::jsonb
);
5 changes: 5 additions & 0 deletions coderd/notifications/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,8 @@ 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")
)
63 changes: 63 additions & 0 deletions coderd/templates.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package coderd

import (
"context"
"database/sql"
"errors"
"fmt"
Expand All @@ -12,12 +13,15 @@
"github.com/google/uuid"
"golang.org/x/xerrors"

"cdr.dev/slog"

"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/schedule"
Expand Down Expand Up @@ -56,6 +60,7 @@
// @Router /templates/{template} [delete]
func (api *API) deleteTemplate(rw http.ResponseWriter, r *http.Request) {
var (
apiKey = httpmw.APIKey(r)
ctx = r.Context()
template = httpmw.TemplateParam(r)
auditor = *api.Auditor.Load()
Expand Down Expand Up @@ -101,11 +106,50 @@
})
return
}

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, receiverID uuid.UUID) {
if initiatorID == receiverID {
return
}

initiator, err := api.Database.GetUserByID(ctx, initiatorID)
if err != nil {
api.Logger.Warn(ctx, "failed to fetch initiator for template deletion notification", slog.F("initiator_id", initiatorID), slog.Error(err))
return
}

if _, err := api.NotificationsEnqueuer.Enqueue(ctx, receiverID, notifications.TemplateTemplateDeleted,
map[string]string{
"name": template.Name,
"initiator": initiator.Username,
}, "api-templates-delete",
// 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)
}
}

// Create a new template in an organization.
// Returns a single template.
//
Expand Down Expand Up @@ -948,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
}
55 changes: 55 additions & 0 deletions coderd/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/schedule"
"github.com/coder/coder/v2/coderd/util/ptr"
Expand Down Expand Up @@ -1326,3 +1327,57 @@ func TestTemplateMetrics(t *testing.T) {
dbtime.Now(), res.Workspaces[0].LastUsedAt, time.Minute,
)
}

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

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()

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)
)

_, 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())

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

// 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)
}
})
}
2 changes: 1 addition & 1 deletion coderd/workspaces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3441,7 +3441,7 @@ func TestWorkspaceUsageTracking(t *testing.T) {
})
}

func TestNotifications(t *testing.T) {
func TestWorkspaceNotifications(t *testing.T) {
t.Parallel()

t.Run("Dormant", func(t *testing.T) {
Expand Down
Loading