Thanks to visit codestin.com
Credit goes to github.com

Skip to content

chore: create ResourceNotificationMessage and AsNotifier #15301

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 5 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -910,8 +910,8 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
return xerrors.Errorf("failed to instantiate notification manager: %w", err)
}

// nolint:gocritic // TODO: create own role.
notificationsManager.Run(dbauthz.AsSystemRestricted(ctx))
// nolint:gocritic // We need to run the manager in a notifier context.
notificationsManager.Run(dbauthz.AsNotifier(ctx))

// Run report generator to distribute periodic reports.
notificationReportGenerator := reports.NewReportGenerator(ctx, logger.Named("notifications.report_generator"), options.Database, options.NotificationsEnqueuer, quartz.NewReal())
Expand Down
2 changes: 2 additions & 0 deletions coderd/apidoc/docs.go

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

2 changes: 2 additions & 0 deletions coderd/apidoc/swagger.json

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

38 changes: 31 additions & 7 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,23 @@ var (
Scope: rbac.ScopeAll,
}.WithCachedASTValue()

subjectNotifier = rbac.Subject{
FriendlyName: "Notifier",
ID: uuid.Nil.String(),
Roles: rbac.Roles([]rbac.Role{
{
Identifier: rbac.RoleIdentifier{Name: "notifier"},
DisplayName: "Notifier",
Site: rbac.Permissions(map[string][]policy.Action{
rbac.ResourceNotificationMessage.Type: {policy.ActionCreate, policy.ActionRead, policy.ActionUpdate, policy.ActionDelete},
}),
Org: map[string][]rbac.Permission{},
User: []rbac.Permission{},
},
}),
Scope: rbac.ScopeAll,
}.WithCachedASTValue()

subjectSystemRestricted = rbac.Subject{
FriendlyName: "System",
ID: uuid.Nil.String(),
Expand All @@ -287,6 +304,7 @@ var (
rbac.ResourceWorkspace.Type: {policy.ActionUpdate, policy.ActionDelete, policy.ActionWorkspaceStart, policy.ActionWorkspaceStop, policy.ActionSSH},
rbac.ResourceWorkspaceProxy.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceDeploymentConfig.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceNotificationMessage.Type: {policy.ActionCreate, policy.ActionRead, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceNotificationPreference.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceNotificationTemplate.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceCryptoKey.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
Expand Down Expand Up @@ -327,6 +345,12 @@ func AsKeyReader(ctx context.Context) context.Context {
return context.WithValue(ctx, authContextKey{}, subjectCryptoKeyReader)
}

// AsNotifier returns a context with an actor that has permissions required for
// creating/reading/updating/deleting notifications.
func AsNotifier(ctx context.Context) context.Context {
return context.WithValue(ctx, authContextKey{}, subjectNotifier)
}

// AsSystemRestricted returns a context with an actor that has permissions
// required for various system operations (login, logout, metrics cache).
func AsSystemRestricted(ctx context.Context) context.Context {
Expand Down Expand Up @@ -950,7 +974,7 @@ func (q *querier) AcquireLock(ctx context.Context, id int64) error {
}

func (q *querier) AcquireNotificationMessages(ctx context.Context, arg database.AcquireNotificationMessagesParams) ([]database.AcquireNotificationMessagesRow, error) {
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceSystem); err != nil {
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceNotificationMessage); err != nil {
return nil, err
}
return q.db.AcquireNotificationMessages(ctx, arg)
Expand Down Expand Up @@ -1001,14 +1025,14 @@ func (q *querier) BatchUpdateWorkspaceLastUsedAt(ctx context.Context, arg databa
}

func (q *querier) BulkMarkNotificationMessagesFailed(ctx context.Context, arg database.BulkMarkNotificationMessagesFailedParams) (int64, error) {
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceSystem); err != nil {
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceNotificationMessage); err != nil {
return 0, err
}
return q.db.BulkMarkNotificationMessagesFailed(ctx, arg)
}

func (q *querier) BulkMarkNotificationMessagesSent(ctx context.Context, arg database.BulkMarkNotificationMessagesSentParams) (int64, error) {
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceSystem); err != nil {
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceNotificationMessage); err != nil {
return 0, err
}
return q.db.BulkMarkNotificationMessagesSent(ctx, arg)
Expand Down Expand Up @@ -1185,7 +1209,7 @@ func (q *querier) DeleteOAuth2ProviderAppTokensByAppAndUserID(ctx context.Contex
}

func (q *querier) DeleteOldNotificationMessages(ctx context.Context) error {
if err := q.authorizeContext(ctx, policy.ActionDelete, rbac.ResourceSystem); err != nil {
if err := q.authorizeContext(ctx, policy.ActionDelete, rbac.ResourceNotificationMessage); err != nil {
return err
}
return q.db.DeleteOldNotificationMessages(ctx)
Expand Down Expand Up @@ -1307,7 +1331,7 @@ func (q *querier) DeleteWorkspaceAgentPortSharesByTemplate(ctx context.Context,
}

func (q *querier) EnqueueNotificationMessage(ctx context.Context, arg database.EnqueueNotificationMessageParams) error {
if err := q.authorizeContext(ctx, policy.ActionCreate, rbac.ResourceSystem); err != nil {
if err := q.authorizeContext(ctx, policy.ActionCreate, rbac.ResourceNotificationMessage); err != nil {
return err
}
return q.db.EnqueueNotificationMessage(ctx, arg)
Expand All @@ -1321,7 +1345,7 @@ func (q *querier) FavoriteWorkspace(ctx context.Context, id uuid.UUID) error {
}

func (q *querier) FetchNewMessageMetadata(ctx context.Context, arg database.FetchNewMessageMetadataParams) (database.FetchNewMessageMetadataRow, error) {
if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceSystem); err != nil {
if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceNotificationMessage); err != nil {
return database.FetchNewMessageMetadataRow{}, err
}
return q.db.FetchNewMessageMetadata(ctx, arg)
Expand Down Expand Up @@ -1686,7 +1710,7 @@ func (q *querier) GetLogoURL(ctx context.Context) (string, error) {
}

func (q *querier) GetNotificationMessagesByStatus(ctx context.Context, arg database.GetNotificationMessagesByStatusParams) ([]database.NotificationMessage, error) {
if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceSystem); err != nil {
if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceNotificationMessage); err != nil {
return nil, err
}
return q.db.GetNotificationMessagesByStatus(ctx, arg)
Expand Down
33 changes: 13 additions & 20 deletions coderd/database/dbauthz/dbauthz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2888,40 +2888,33 @@ func (s *MethodTestSuite) TestSystemFunctions() {

func (s *MethodTestSuite) TestNotifications() {
// System functions
s.Run("AcquireNotificationMessages", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
check.Args(database.AcquireNotificationMessagesParams{}).Asserts(rbac.ResourceSystem, policy.ActionUpdate)
s.Run("AcquireNotificationMessages", s.Subtest(func(_ database.Store, check *expects) {
check.Args(database.AcquireNotificationMessagesParams{}).Asserts(rbac.ResourceNotificationMessage, policy.ActionUpdate)
}))
s.Run("BulkMarkNotificationMessagesFailed", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
check.Args(database.BulkMarkNotificationMessagesFailedParams{}).Asserts(rbac.ResourceSystem, policy.ActionUpdate)
s.Run("BulkMarkNotificationMessagesFailed", s.Subtest(func(_ database.Store, check *expects) {
check.Args(database.BulkMarkNotificationMessagesFailedParams{}).Asserts(rbac.ResourceNotificationMessage, policy.ActionUpdate)
}))
s.Run("BulkMarkNotificationMessagesSent", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
check.Args(database.BulkMarkNotificationMessagesSentParams{}).Asserts(rbac.ResourceSystem, policy.ActionUpdate)
s.Run("BulkMarkNotificationMessagesSent", s.Subtest(func(_ database.Store, check *expects) {
check.Args(database.BulkMarkNotificationMessagesSentParams{}).Asserts(rbac.ResourceNotificationMessage, policy.ActionUpdate)
}))
s.Run("DeleteOldNotificationMessages", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
check.Args().Asserts(rbac.ResourceSystem, policy.ActionDelete)
s.Run("DeleteOldNotificationMessages", s.Subtest(func(_ database.Store, check *expects) {
check.Args().Asserts(rbac.ResourceNotificationMessage, policy.ActionDelete)
}))
s.Run("EnqueueNotificationMessage", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
s.Run("EnqueueNotificationMessage", s.Subtest(func(_ database.Store, check *expects) {
check.Args(database.EnqueueNotificationMessageParams{
Method: database.NotificationMethodWebhook,
Payload: []byte("{}"),
}).Asserts(rbac.ResourceSystem, policy.ActionCreate)
}).Asserts(rbac.ResourceNotificationMessage, policy.ActionCreate)
}))
s.Run("FetchNewMessageMetadata", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
u := dbgen.User(s.T(), db, database.User{})
check.Args(database.FetchNewMessageMetadataParams{UserID: u.ID}).Asserts(rbac.ResourceSystem, policy.ActionRead)
check.Args(database.FetchNewMessageMetadataParams{UserID: u.ID}).Asserts(rbac.ResourceNotificationMessage, policy.ActionRead)
}))
s.Run("GetNotificationMessagesByStatus", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
s.Run("GetNotificationMessagesByStatus", s.Subtest(func(_ database.Store, check *expects) {
check.Args(database.GetNotificationMessagesByStatusParams{
Status: database.NotificationMessageStatusLeased,
Limit: 10,
}).Asserts(rbac.ResourceSystem, policy.ActionRead)
}).Asserts(rbac.ResourceNotificationMessage, policy.ActionRead)
}))

// Notification templates
Expand Down
36 changes: 19 additions & 17 deletions coderd/notifications/notifications_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func TestBasicNotificationRoundtrip(t *testing.T) {
}

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)
method := database.NotificationMethodSmtp
Expand Down Expand Up @@ -135,7 +135,7 @@ func TestSMTPDispatch(t *testing.T) {
// SETUP

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down Expand Up @@ -197,7 +197,7 @@ func TestWebhookDispatch(t *testing.T) {
// SETUP

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down Expand Up @@ -281,7 +281,7 @@ func TestBackpressure(t *testing.T) {
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)
// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitShort))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitShort))

const method = database.NotificationMethodWebhook
cfg := defaultNotificationsConfig(method)
Expand Down Expand Up @@ -407,7 +407,7 @@ func TestRetries(t *testing.T) {

const maxAttempts = 3
// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down Expand Up @@ -501,7 +501,7 @@ func TestExpiredLeaseIsRequeued(t *testing.T) {
}

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand All @@ -521,7 +521,7 @@ func TestExpiredLeaseIsRequeued(t *testing.T) {
noopInterceptor := newNoopStoreSyncer(store)

// nolint:gocritic // Unit test.
mgrCtx, cancelManagerCtx := context.WithCancel(dbauthz.AsSystemRestricted(context.Background()))
mgrCtx, cancelManagerCtx := context.WithCancel(dbauthz.AsNotifier(context.Background()))
t.Cleanup(cancelManagerCtx)

mgr, err := notifications.NewManager(cfg, noopInterceptor, defaultHelpers(), createMetrics(), logger.Named("manager"))
Expand Down Expand Up @@ -626,7 +626,7 @@ func TestNotifierPaused(t *testing.T) {
// Setup.

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down Expand Up @@ -1081,7 +1081,7 @@ func TestNotificationTemplates_Golden(t *testing.T) {
}()

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))

// smtp config shared between client and server
smtpConfig := codersdk.NotificationsEmailConfig{
Expand Down Expand Up @@ -1160,12 +1160,14 @@ func TestNotificationTemplates_Golden(t *testing.T) {
// as appearance changes are enterprise features and we do not want to mix those
// can't use the api
if tc.appName != "" {
err = (*db).UpsertApplicationName(ctx, "Custom Application")
// nolint:gocritic // Unit test.
err = (*db).UpsertApplicationName(dbauthz.AsSystemRestricted(ctx), "Custom Application")
require.NoError(t, err)
}

if tc.logoURL != "" {
err = (*db).UpsertLogoURL(ctx, "https://custom.application/logo.png")
// nolint:gocritic // Unit test.
err = (*db).UpsertLogoURL(dbauthz.AsSystemRestricted(ctx), "https://custom.application/logo.png")
require.NoError(t, err)
}

Expand Down Expand Up @@ -1248,7 +1250,7 @@ func TestNotificationTemplates_Golden(t *testing.T) {
}()

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))

// Spin up the mock webhook server
var body []byte
Expand Down Expand Up @@ -1377,7 +1379,7 @@ func TestDisabledBeforeEnqueue(t *testing.T) {
}

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down Expand Up @@ -1413,7 +1415,7 @@ func TestDisabledAfterEnqueue(t *testing.T) {
}

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down Expand Up @@ -1470,7 +1472,7 @@ func TestCustomNotificationMethod(t *testing.T) {
}

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down Expand Up @@ -1574,7 +1576,7 @@ func TestNotificationsTemplates(t *testing.T) {
}

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
api := coderdtest.New(t, createOpts(t))

// GIVEN: the first user (owner) and a regular member
Expand Down Expand Up @@ -1611,7 +1613,7 @@ func TestNotificationDuplicates(t *testing.T) {
}

// nolint:gocritic // Unit test.
ctx := dbauthz.AsSystemRestricted(testutil.Context(t, testutil.WaitSuperLong))
ctx := dbauthz.AsNotifier(testutil.Context(t, testutil.WaitSuperLong))
store, _ := dbtestutil.NewDB(t)
logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug)

Expand Down
11 changes: 11 additions & 0 deletions coderd/rbac/object_gen.go

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

8 changes: 8 additions & 0 deletions coderd/rbac/policy/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,14 @@ var RBACPermissions = map[string]PermissionDefinition{
ActionDelete: actDef(""),
},
},
"notification_message": {
Actions: map[Action]ActionDefinition{
ActionCreate: actDef("create notification messages"),
ActionRead: actDef("read notification messages"),
ActionUpdate: actDef("update notification messages"),
ActionDelete: actDef("delete notification messages"),
},
},
"notification_template": {
Actions: map[Action]ActionDefinition{
ActionRead: actDef("read notification templates"),
Expand Down
Loading
Loading