Skip to content
Open
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
132 changes: 113 additions & 19 deletions admin/server/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,26 +220,72 @@ func (s *Server) CreateAlert(ctx context.Context, req *adminv1.CreateAlertReques
return nil, status.Error(codes.PermissionDenied, "only users can create alerts")
}

name, err := s.createManagedAlert(ctx, proj, req.Options, ownerID, embedOwnerID, embedOwnerEmail, embedResources)
if err != nil {
return nil, err
}

return &adminv1.CreateAlertResponse{
Name: name,
}, nil
}

// CreateAlertForUser creates an alert owned by a user, like CreateAlert does for the calling user.
func (s *Server) CreateAlertForUser(ctx context.Context, req *adminv1.CreateAlertForUserRequest) (*adminv1.CreateAlertForUserResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.project_id", req.ProjectId),
attribute.String("args.user_id", req.UserId),
)

proj, err := s.admin.DB.FindProject(ctx, req.ProjectId)
if err != nil {
return nil, err
}

user, permissions, err := s.userForPrimaryDeployment(ctx, proj, req.UserId)
if err != nil {
return nil, err
}
if !permissions.CreateAlerts {
return nil, status.Error(codes.PermissionDenied, "user does not have permission to create alerts")
}

req.Options.EmailRecipients, err = s.recipientsForUser(ctx, proj, user, req.Options.EmailRecipients, req.Options.SlackUsers, req.Options.SlackChannels, req.Options.SlackWebhooks)
if err != nil {
return nil, err
}

name, err := s.createManagedAlert(ctx, proj, req.Options, user.ID, "", "", nil)
if err != nil {
return nil, err
}

return &adminv1.CreateAlertForUserResponse{Name: name}, nil
}

// createManagedAlert adds a virtual file for an alert created from the UI or by the AI, and waits for the alert to be added to the runtime catalog.
// It returns the alert's name.
func (s *Server) createManagedAlert(ctx context.Context, proj *database.Project, opts *adminv1.AlertOptions, ownerID, embedOwnerID, embedOwnerEmail string, embedResources []database.ResourceName) (string, error) {
if proj.PrimaryDeploymentID == nil {
return nil, status.Error(codes.FailedPrecondition, "project does not have a production deployment")
return "", status.Error(codes.FailedPrecondition, "project does not have a production deployment")
}

depl, err := s.admin.DB.FindDeployment(ctx, *proj.PrimaryDeploymentID)
if err != nil {
return nil, err
return "", err
}

name, err := s.generateVirtualFileName(ctx, req.Options.DisplayName, func(ctx context.Context, name string) error {
name, err := s.generateVirtualFileName(ctx, opts.DisplayName, func(ctx context.Context, name string) error {
_, err := s.admin.LookupAlert(ctx, depl, name)
return err
})
if err != nil {
return nil, err
return "", err
}

data, err := s.yamlForManagedAlert(req.Options, ownerID, embedOwnerID, embedOwnerEmail, embedResources)
data, err := s.yamlForManagedAlert(opts, ownerID, embedOwnerID, embedOwnerEmail, embedResources)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to generate alert YAML: %s", err.Error())
return "", status.Errorf(codes.InvalidArgument, "failed to generate alert YAML: %s", err.Error())
}

var embedOwnerIDPtr *string
Expand All @@ -255,20 +301,18 @@ func (s *Server) CreateAlert(ctx context.Context, req *adminv1.CreateAlertReques
EmbedOwnerID: embedOwnerIDPtr,
})
if err != nil {
return nil, fmt.Errorf("failed to insert virtual file: %w", err)
return "", fmt.Errorf("failed to insert virtual file: %w", err)
}

err = s.admin.TriggerParserAndAwaitResource(ctx, depl, name, runtime.ResourceKindAlert)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be created")
return "", status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be created")
}
return nil, fmt.Errorf("failed to reconcile alert: %w", err)
return "", fmt.Errorf("failed to reconcile alert: %w", err)
}

return &adminv1.CreateAlertResponse{
Name: name,
}, nil
return name, nil
}

func (s *Server) EditAlert(ctx context.Context, req *adminv1.EditAlertRequest) (*adminv1.EditAlertResponse, error) {
Expand Down Expand Up @@ -570,20 +614,70 @@ func (s *Server) DeleteAlert(ctx context.Context, req *adminv1.DeleteAlertReques
return nil, status.Error(codes.PermissionDenied, "does not have permission to edit alert")
}

err = s.admin.DB.UpdateVirtualFileDeleted(ctx, proj.ID, "prod", virtualFilePathForManagedAlert(req.Name))
err = s.deleteManagedAlert(ctx, proj, depl, req.Name)
if err != nil {
return nil, fmt.Errorf("failed to delete virtual file: %w", err)
return nil, err
}

err = s.admin.TriggerParserAndAwaitResource(ctx, depl, req.Name, runtime.ResourceKindAlert)
return &adminv1.DeleteAlertResponse{}, nil
}

// DeleteAlertForUser deletes an alert owned by a user, like DeleteAlert does for the calling user.
// Unlike DeleteAlert, it only deletes the user's own alerts, even if the user can manage other users' alerts.
func (s *Server) DeleteAlertForUser(ctx context.Context, req *adminv1.DeleteAlertForUserRequest) (*adminv1.DeleteAlertForUserResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.project_id", req.ProjectId),
attribute.String("args.user_id", req.UserId),
attribute.String("args.name", req.Name),
)

proj, err := s.admin.DB.FindProject(ctx, req.ProjectId)
if err != nil {
return nil, err
}

user, _, err := s.userForPrimaryDeployment(ctx, proj, req.UserId)
if err != nil {
return nil, err
}

depl, err := s.admin.DB.FindDeployment(ctx, *proj.PrimaryDeploymentID)
if err != nil {
return nil, err
}

spec, err := s.admin.LookupAlert(ctx, depl, req.Name)
if err != nil {
return nil, fmt.Errorf("could not get alert: %w", err)
}
annotations := parseAlertAnnotations(spec.Annotations)
if !annotations.AdminManaged || annotations.AdminOwnerUserID != user.ID {
return nil, status.Error(codes.PermissionDenied, "can only delete alerts the user owns")
}

err = s.deleteManagedAlert(ctx, proj, depl, req.Name)
if err != nil {
return nil, err
}

return &adminv1.DeleteAlertForUserResponse{}, nil
}

// deleteManagedAlert deletes the virtual file of an alert created from the UI or by the AI, and waits for the alert to be removed from the runtime catalog.
func (s *Server) deleteManagedAlert(ctx context.Context, proj *database.Project, depl *database.Deployment, name string) error {
err := s.admin.DB.UpdateVirtualFileDeleted(ctx, proj.ID, "prod", virtualFilePathForManagedAlert(name))
if err != nil {
return fmt.Errorf("failed to delete virtual file: %w", err)
}

err = s.admin.TriggerParserAndAwaitResource(ctx, depl, name, runtime.ResourceKindAlert)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be deleted")
return status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be deleted")
}
return nil, fmt.Errorf("failed to reconcile alert: %w", err)
return fmt.Errorf("failed to reconcile alert: %w", err)
}

return &adminv1.DeleteAlertResponse{}, nil
return nil
}

func (s *Server) GenerateAlertYAML(ctx context.Context, req *adminv1.GenerateAlertYAMLRequest) (*adminv1.GenerateAlertYAMLResponse, error) {
Expand Down
89 changes: 89 additions & 0 deletions admin/server/for_user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package server

import (
"context"
"errors"
"regexp"
"slices"
"strings"

"github.com/google/uuid"
"github.com/rilldata/rill/admin/database"
"github.com/rilldata/rill/admin/server/auth"
adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

// userForPrimaryDeployment checks that the caller is the project's primary deployment, and returns the user it acts for with their permissions on the project.
// The deployment is trusted to pass the user of its session, as for GetAlertMeta, GetReportMeta and GetConnectorOAuthToken.
// Other deployments are rejected, because alerts and reports created from the UI live in the prod environment, which only the primary deployment reads.
func (s *Server) userForPrimaryDeployment(ctx context.Context, proj *database.Project, userID string) (*database.User, *adminv1.ProjectPermissions, error) {
claims := auth.GetClaims(ctx)
if claims.OwnerType() != auth.OwnerTypeDeployment || proj.PrimaryDeploymentID == nil || *proj.PrimaryDeploymentID != claims.OwnerID() {
return nil, nil, status.Error(codes.PermissionDenied, "only the project's primary deployment can act for a user")
}

// Only users, not services, magic tokens or embed users, own the resources this creates.
if _, err := uuid.Parse(userID); err != nil {
return nil, nil, status.Error(codes.PermissionDenied, "can only act for a user")
}
user, err := s.admin.DB.FindUser(ctx, userID)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, nil, status.Error(codes.PermissionDenied, "can only act for a user")
}
return nil, nil, err
}

orgPerms, err := s.admin.OrganizationPermissionsForUser(ctx, proj.OrganizationID, user.ID)
if err != nil {
return nil, nil, err
}
projPerms, err := s.admin.ProjectPermissionsForUser(ctx, proj.ID, user.ID, orgPerms)
if err != nil {
return nil, nil, err
}
// Like the user's own requests, requests for a user who lost access to the project are rejected, including deletes of their own resources.
if !projPerms.ReadProd {
return nil, nil, status.Error(codes.PermissionDenied, "user does not have access to the project")
}
return user, projPerms, nil

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Could we check projPerms.ReadProd here? The regular DeleteAlert and DeleteReport endpoints both check current production access before checking ownership. The new delete handlers only check ownership, so their behavior diverges after a user's project access is revoked.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 8883105: userForPrimaryDeployment now rejects users without ReadProd, so all four RPCs, deletes included, match the regular endpoints; a new subtest covers a user removed from the project.

}

// slackDirectMessageDestination matches the destinations other than channels that chat.postMessage takes as a channel:
// "@name", and user and direct message IDs, which are upper case, while channel names are lower case.
var slackDirectMessageDestination = regexp.MustCompile(`^@|^[UWD][A-Z0-9]+$`)

// recipientsForUser checks the recipients of an alert or report that the AI creates for a user, and returns its email recipients.
// The AI can be steered by the data and tools it reads, so what it creates can only reach the project's members and its Slack workspace:
// the email recipients default to the user when there are no other recipients, other email recipients and Slack users must be members of the project,
// Slack channels are allowed, since they're in the Slack workspace the project's admin configured, but not direct messages to other people,
// and Slack webhooks, which can be any URL, are rejected.
func (s *Server) recipientsForUser(ctx context.Context, proj *database.Project, user *database.User, emails, slackUsers, slackChannels, slackWebhooks []string) ([]string, error) {
if len(slackWebhooks) > 0 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Can recipientsForUser require a verified internal Slack channel here? sendTextToChannels passes the destination straight to chat.postMessage, which also accepts DM destinations, and Slack Connect channels can have readers outside the workspace. That can send an alert’s rows or a report’s summary beyond the intended audience. Resolve the destination to a channel ID and check its conversation type and external-sharing status before accepting it. Posting destinations · Slack Connect channel flags

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Partly fixed in 7f91a46: @name and user or DM IDs (U/W/D) are now rejected as channels, so people are only reached as Slack users who are project members; ruling out Slack Connect channels needs a conversations.info call with the project's Slack token, which only the runtime has, so I've left that for a decision (the regular create endpoints and the form don't check channels either).

return nil, status.Error(codes.InvalidArgument, "the AI can't send to Slack webhooks, since they can be any URL")
}
for _, channel := range slackChannels {
if slackDirectMessageDestination.MatchString(strings.TrimPrefix(channel, "#")) {
return nil, status.Errorf(codes.InvalidArgument, "%q is not a Slack channel: the AI can only send to people as Slack users, who must be members of the project", channel)
}
}
if len(emails) == 0 && len(slackUsers) == 0 && len(slackChannels) == 0 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

A Slack-only alert or report can now be created in a project with no Slack setup, with no email fallback. The user gets a success response and delivery fails later in sendTextToChannels. Could the for-user create path check notifier availability before saving and tell the user to configure Slack or choose email? The web form already checks ListNotifierConnectors in FormMetadataProvider.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Leaving this to the chat tools in #10233 and #10234: the admin service can't see whether the instance has a Slack connector (it can come from project files or variables), so they will check it like the form's ListNotifierConnectors before calling this RPC.

return []string{user.Email}, nil
}

for _, recipient := range slices.Concat(emails, slackUsers) {
if strings.EqualFold(recipient, user.Email) {
continue
}
_, memberID, err := s.getAttributesForProjectMember(ctx, recipient, proj.OrganizationID, proj.ID)
if err != nil {
return nil, err
}
if memberID == "" {
return nil, status.Errorf(codes.InvalidArgument, "%s is not a member of the project, and the AI can only send to project members", recipient)
}
}
return emails, nil
}
Loading
Loading