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 10 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")
)
60 changes: 60 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 @@ import (
"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 @@ func (api *API) template(rw http.ResponseWriter, r *http.Request) {
// @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,47 @@ func (api *API) deleteTemplate(rw http.ResponseWriter, r *http.Request) {
})
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 {
// Don't send notification to user which initiated the event.
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) {
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_id", template.ID), slog.Error(err))
}
}

// Create a new template in an organization.
// Returns a single template.
//
Expand Down Expand Up @@ -948,3 +989,22 @@ func (api *API) convertTemplate(
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
}
91 changes: 91 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,93 @@ func TestTemplateMetrics(t *testing.T) {
dbtime.Now(), res.Workspaces[0].LastUsedAt, time.Minute,
)
}

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

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

t.Run("SendNotification", 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.

Now this is a great test! Needs a little work but it's very nice.
Doesn't this feel better to read now?

Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
t.Run("SendNotification", func(t *testing.T) {
t.Run("InitiatorIsNotNotified", func(t *testing.T) {

t.Parallel()

// Given: an owner and a template admin
var (
notifyEnq = &testutil.FakeNotificationsEnqueuer{}
client = coderdtest.New(t, &coderdtest.Options{
IncludeProvisionerDaemon: true,
NotificationsEnqueuer: notifyEnq,
})
owner = coderdtest.CreateFirstUser(t, client)
version = coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
_ = coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template = coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
ctx = testutil.Context(t, testutil.WaitLong)
_, templateAdmin = coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.RoleTemplateAdmin())
)

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

// Then: verify that the notification is sent to the correct user
// (template admin) and targets, using the appropriate labels. Note that
// the owner, being the initiator, will not receive the notification.
deleteNotifications := make([]*testutil.Notification, 0)
for _, n := range notifyEnq.Sent {
if n.TemplateID == notifications.TemplateTemplateDeleted {
deleteNotifications = append(deleteNotifications, n)
}
}
require.Len(t, deleteNotifications, 1)
require.Contains(t, deleteNotifications[0].TemplateID, notifications.TemplateTemplateDeleted)
require.Contains(t, deleteNotifications[0].UserID, templateAdmin.ID)
require.Contains(t, deleteNotifications[0].Targets, template.ID)
require.Contains(t, deleteNotifications[0].Targets, template.OrganizationID)
require.Equal(t, deleteNotifications[0].Labels["name"], template.Name)
require.Equal(t, deleteNotifications[0].Labels["initiator"], coderdtest.FirstUserParams.Username)
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 you could simplify this to show that the notification is not received at all in this test if there's only one owner.
In the other test you're checking for exactly the same thing.
Tests should validate one (or as close to one) aspect of business logic at a time, IMHO.

})

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

// Given: multiple users with different roles
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())
coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID, rbac.RoleUserAdmin())

// When: the template is deleted by the owner
Copy link
Contributor

Choose a reason for hiding this comment

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

Which owner? You have the first user, which is performing this action, and anotherOwner.

Suggested change
// When: the template is deleted by the owner
// When: the template is deleted by firstUser

err := client.DeleteTemplate(ctx, template.ID)
require.NoError(t, err)

// Then: only the template owners and template admins should receive the
// notification. Since the first user is the initiator, it should not
// receive the notification.
shouldBeNotified := []uuid.UUID{anotherOwner.ID, tmplAdmin.ID}
var deleteTemplateNotifications []*testutil.Notification
for _, n := range notifyEnq.Sent {
if n.TemplateID == notifications.TemplateTemplateDeleted {
deleteTemplateNotifications = append(deleteTemplateNotifications, n)
}
}
notifiedUsers := make([]uuid.UUID, 0, len(deleteTemplateNotifications))
for _, n := range deleteTemplateNotifications {
notifiedUsers = append(notifiedUsers, n.UserID)
}
require.ElementsMatch(t, shouldBeNotified, notifiedUsers)
})
})
}
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