feat: add notification preferences database & audit support (#14100)

This commit is contained in:
Danny Kopping
2024-08-05 16:18:45 +02:00
committed by GitHub
parent 49a2880abc
commit e164b1e71c
49 changed files with 3229 additions and 368 deletions

View File

@ -368,7 +368,6 @@ func New(ctx context.Context, options *Options) (_ *API, err error) {
r.Put("/", api.putAppearance)
})
})
r.Route("/users/{user}/quiet-hours", func(r chi.Router) {
r.Use(
api.autostopRequirementEnabledMW,
@ -388,6 +387,15 @@ func New(ctx context.Context, options *Options) (_ *API, err error) {
r.Post("/jfrog/xray-scan", api.postJFrogXrayScan)
r.Get("/jfrog/xray-scan", api.jFrogXrayScan)
})
// The /notifications base route is mounted by the AGPL router, so we can't group it here.
// Additionally, because we have a static route for /notifications/templates/system which conflicts
// with the below route, we need to register this route without any mounts or groups to make both work.
r.With(
apiKeyMiddleware,
httpmw.RequireExperiment(api.AGPL.Experiments, codersdk.ExperimentNotifications),
httpmw.ExtractNotificationTemplateParam(options.Database),
).Put("/notifications/templates/{notification_template}/method", api.updateNotificationTemplateMethod)
})
if len(options.SCIMAPIKey) != 0 {

View File

@ -0,0 +1,98 @@
package coderd
import (
"fmt"
"net/http"
"strings"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/codersdk"
)
// @Summary Update notification template dispatch method
// @ID update-notification-template-dispatch-method
// @Security CoderSessionToken
// @Produce json
// @Param notification_template path string true "Notification template UUID"
// @Tags Enterprise
// @Success 200 "Success"
// @Success 304 "Not modified"
// @Router /notifications/templates/{notification_template}/method [put]
func (api *API) updateNotificationTemplateMethod(rw http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
template = httpmw.NotificationTemplateParam(r)
auditor = api.AGPL.Auditor.Load()
aReq, commitAudit = audit.InitRequest[database.NotificationTemplate](rw, &audit.RequestParams{
Audit: *auditor,
Log: api.Logger,
Request: r,
Action: database.AuditActionWrite,
})
)
var req codersdk.UpdateNotificationTemplateMethod
if !httpapi.Read(ctx, rw, r, &req) {
return
}
var nm database.NullNotificationMethod
if err := nm.Scan(req.Method); err != nil || !nm.Valid || !nm.NotificationMethod.Valid() {
vals := database.AllNotificationMethodValues()
acceptable := make([]string, len(vals))
for i, v := range vals {
acceptable[i] = string(v)
}
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Invalid request to update notification template method",
Validations: []codersdk.ValidationError{
{
Field: "method",
Detail: fmt.Sprintf("%q is not a valid method; %s are the available options",
req.Method, strings.Join(acceptable, ", "),
),
},
},
})
return
}
if template.Method == nm {
httpapi.Write(ctx, rw, http.StatusNotModified, codersdk.Response{
Message: "Notification template method unchanged.",
})
return
}
defer commitAudit()
aReq.Old = template
err := api.Database.InTx(func(tx database.Store) error {
var err error
template, err = api.Database.UpdateNotificationTemplateMethodByID(r.Context(), database.UpdateNotificationTemplateMethodByIDParams{
ID: template.ID,
Method: nm,
})
if err != nil {
return xerrors.Errorf("failed to update notification template ID: %w", err)
}
return err
}, nil)
if err != nil {
httpapi.InternalServerError(rw, err)
return
}
aReq.New = template
httpapi.Write(ctx, rw, http.StatusOK, codersdk.Response{
Message: "Successfully updated notification template method.",
})
}

View File

@ -0,0 +1,180 @@
package coderd_test
import (
"context"
"fmt"
"net/http"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/enterprise/coderd/coderdenttest"
"github.com/coder/coder/v2/testutil"
)
func createOpts(t *testing.T) *coderdenttest.Options {
t.Helper()
dt := coderdtest.DeploymentValues(t)
dt.Experiments = []string{string(codersdk.ExperimentNotifications)}
return &coderdenttest.Options{
Options: &coderdtest.Options{
DeploymentValues: dt,
},
}
}
func TestUpdateNotificationTemplateMethod(t *testing.T) {
t.Parallel()
t.Run("Happy path", func(t *testing.T) {
t.Parallel()
if !dbtestutil.WillUsePostgres() {
t.Skip("This test requires postgres; it relies on read from and writing to the notification_templates table")
}
ctx := testutil.Context(t, testutil.WaitSuperLong)
api, _ := coderdenttest.New(t, createOpts(t))
var (
method = string(database.NotificationMethodSmtp)
templateID = notifications.TemplateWorkspaceDeleted
)
// Given: a template whose method is initially empty (i.e. deferring to the global method value).
template, err := getTemplateByID(t, ctx, api, templateID)
require.NoError(t, err)
require.NotNil(t, template)
require.Empty(t, template.Method)
// When: calling the API to update the method.
require.NoError(t, api.UpdateNotificationTemplateMethod(ctx, notifications.TemplateWorkspaceDeleted, method), "initial request to set the method failed")
// Then: the method should be set.
template, err = getTemplateByID(t, ctx, api, templateID)
require.NoError(t, err)
require.NotNil(t, template)
require.Equal(t, method, template.Method)
})
t.Run("Insufficient permissions", func(t *testing.T) {
t.Parallel()
if !dbtestutil.WillUsePostgres() {
t.Skip("This test requires postgres; it relies on read from and writing to the notification_templates table")
}
ctx := testutil.Context(t, testutil.WaitSuperLong)
// Given: the first user which has an "owner" role, and another user which does not.
api, firstUser := coderdenttest.New(t, createOpts(t))
anotherClient, _ := coderdtest.CreateAnotherUser(t, api, firstUser.OrganizationID)
// When: calling the API as an unprivileged user.
err := anotherClient.UpdateNotificationTemplateMethod(ctx, notifications.TemplateWorkspaceDeleted, string(database.NotificationMethodWebhook))
// Then: the request is denied because of insufficient permissions.
var sdkError *codersdk.Error
require.Error(t, err)
require.ErrorAsf(t, err, &sdkError, "error should be of type *codersdk.Error")
require.Equal(t, http.StatusNotFound, sdkError.StatusCode())
require.Equal(t, "Resource not found or you do not have access to this resource", sdkError.Response.Message)
})
t.Run("Invalid notification method", func(t *testing.T) {
t.Parallel()
if !dbtestutil.WillUsePostgres() {
t.Skip("This test requires postgres; it relies on read from and writing to the notification_templates table")
}
ctx := testutil.Context(t, testutil.WaitSuperLong)
// Given: the first user which has an "owner" role
api, _ := coderdenttest.New(t, createOpts(t))
// When: calling the API with an invalid method.
const method = "nope"
// nolint:gocritic // Using an owner-scope user is kinda the point.
err := api.UpdateNotificationTemplateMethod(ctx, notifications.TemplateWorkspaceDeleted, method)
// Then: the request is invalid because of the unacceptable method.
var sdkError *codersdk.Error
require.Error(t, err)
require.ErrorAsf(t, err, &sdkError, "error should be of type *codersdk.Error")
require.Equal(t, http.StatusBadRequest, sdkError.StatusCode())
require.Equal(t, "Invalid request to update notification template method", sdkError.Response.Message)
require.Len(t, sdkError.Response.Validations, 1)
require.Equal(t, "method", sdkError.Response.Validations[0].Field)
require.Equal(t, fmt.Sprintf("%q is not a valid method; smtp, webhook are the available options", method), sdkError.Response.Validations[0].Detail)
})
t.Run("Not modified", func(t *testing.T) {
t.Parallel()
if !dbtestutil.WillUsePostgres() {
t.Skip("This test requires postgres; it relies on read from and writing to the notification_templates table")
}
ctx := testutil.Context(t, testutil.WaitSuperLong)
api, _ := coderdenttest.New(t, createOpts(t))
var (
method = string(database.NotificationMethodSmtp)
templateID = notifications.TemplateWorkspaceDeleted
)
template, err := getTemplateByID(t, ctx, api, templateID)
require.NoError(t, err)
require.NotNil(t, template)
// Given: a template whose method is initially empty (i.e. deferring to the global method value).
require.Empty(t, template.Method)
// When: calling the API to update the method, it should set it.
require.NoError(t, api.UpdateNotificationTemplateMethod(ctx, notifications.TemplateWorkspaceDeleted, method), "initial request to set the method failed")
template, err = getTemplateByID(t, ctx, api, templateID)
require.NoError(t, err)
require.NotNil(t, template)
require.Equal(t, method, template.Method)
// Then: when calling the API again with the same method, the method will remain unchanged.
require.NoError(t, api.UpdateNotificationTemplateMethod(ctx, notifications.TemplateWorkspaceDeleted, method), "second request to set the method failed")
template, err = getTemplateByID(t, ctx, api, templateID)
require.NoError(t, err)
require.NotNil(t, template)
require.Equal(t, method, template.Method)
})
}
// nolint:revive // t takes precedence.
func getTemplateByID(t *testing.T, ctx context.Context, api *codersdk.Client, id uuid.UUID) (*codersdk.NotificationTemplate, error) {
t.Helper()
var template codersdk.NotificationTemplate
templates, err := api.GetSystemNotificationTemplates(ctx)
if err != nil {
return nil, err
}
for _, tmpl := range templates {
if tmpl.ID == id {
template = tmpl
}
}
if template.ID == uuid.Nil {
return nil, xerrors.Errorf("template not found: %q", id.String())
}
return &template, nil
}