Skip to content
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

notification/slack: add interactivity to alert notifications #2014

Merged
merged 19 commits into from
Nov 9, 2021
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
24 changes: 14 additions & 10 deletions alert/log/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"

"github.com/target/goalert/integrationkey"
"github.com/target/goalert/notification"
"github.com/target/goalert/notificationchannel"
"github.com/target/goalert/permission"
"github.com/target/goalert/user/contactmethod"
Expand Down Expand Up @@ -60,9 +61,10 @@ func NewDB(ctx context.Context, db *sql.DB) (*DB, error) {
return &DB{
db: db,
lookupCallbackType: p.P(`
select cm."type"
select cm."type", ch."type"
from outgoing_messages log
join user_contact_methods cm on cm.id = log.contact_method_id
left join user_contact_methods cm on cm.id = log.contact_method_id
left join notification_channels ch on ch.id = log.channel_id
where log.id = $1
`),
lookupCMType: p.P(`
Expand Down Expand Up @@ -341,20 +343,22 @@ func (db *DB) logAny(ctx context.Context, tx *sql.Tx, insertStmt *sql.Stmt, id i

case permission.SourceTypeNotificationCallback:
r.subject._type = SubjectTypeUser
var cmType contactmethod.Type
err = txWrap(ctx, tx, db.lookupCallbackType).QueryRowContext(ctx, src.ID).Scan(&cmType)
var dt notification.ScannableDestType
err = txWrap(ctx, tx, db.lookupCallbackType).QueryRowContext(ctx, src.ID).Scan(&dt.CM, &dt.NC)
if err != nil {
return errors.Wrap(err, "lookup contact method type for callback ID")
return errors.Wrap(err, "lookup notification type for callback ID")
}
switch cmType {
case contactmethod.TypeVoice:
switch dt.DestType() {
case notification.DestTypeVoice:
r.subject.classifier = "Voice"
case contactmethod.TypeSMS:
case notification.DestTypeSMS:
r.subject.classifier = "SMS"
case contactmethod.TypeEmail:
case notification.DestTypeUserEmail:
r.subject.classifier = "Email"
case contactmethod.TypeWebhook:
case notification.DestTypeUserWebhook:
r.subject.classifier = "Webhook"
case notification.DestTypeSlackChannel:
r.subject.classifier = "Slack"
}
r.subject.userID.String = permission.UserID(ctx)
if r.subject.userID.String != "" {
Expand Down
2 changes: 2 additions & 0 deletions app/inithttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ func (app *App) initHTTP(ctx context.Context) error {
mux.HandleFunc("/api/v2/twilio/call", app.twilioVoice.ServeCall)
mux.HandleFunc("/api/v2/twilio/call/status", app.twilioVoice.ServeStatusCallback)

mux.HandleFunc("/api/v2/slack/message-action", app.slackChan.ServeMessageAction)

// Legacy (v1) API mapping
mux.HandleFunc("/v1/graphql", app.graphql.ServeHTTP)

Expand Down
7 changes: 7 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ type Config struct {
// The `xoxb-` prefix is documented by Slack.
// https://api.slack.com/docs/token-types#bot
AccessToken string `password:"true" info:"Slack app bot user OAuth access token (should start with xoxb-)."`

SigningSecret string `password:"true" info:"Signing secret to verify requests from slack."`
InteractiveMessages bool `info:"Enable interactive messages (e.g. buttons)."`
}

Twilio struct {
Expand Down Expand Up @@ -394,6 +397,7 @@ func (cfg Config) Validate() error {
validatePath("OIDC.UserInfoEmailPath", cfg.OIDC.UserInfoEmailPath),
validatePath("OIDC.UserInfoEmailVerifiedPath", cfg.OIDC.UserInfoEmailVerifiedPath),
validatePath("OIDC.UserInfoNamePath", cfg.OIDC.UserInfoNamePath),
validateKey("Slack.SigningSecret", cfg.Slack.SigningSecret),
)

if cfg.OIDC.IssuerURL != "" {
Expand All @@ -417,6 +421,9 @@ func (cfg Config) Validate() error {
if cfg.SMTP.From != "" {
err = validate.Many(err, validate.Email("SMTP.From", cfg.SMTP.From))
}
if cfg.Slack.InteractiveMessages && cfg.Slack.SigningSecret == "" {
err = validate.Many(err, validation.NewFieldError("Slack.SigningSecret", "required to enable Slack interactive messages"))
}

err = validate.Many(
err,
Expand Down
160 changes: 160 additions & 0 deletions devtools/mockslack/actions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package mockslack

import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)

type actionItem struct {
ActionID string `json:"action_id"`
BlockID string `json:"block_id"`
Text struct {
Type string
Text string
}
Value string
Type string
}
type actionBody struct {
Type string
AppID string `json:"api_app_id"`
Channel struct{ ID string }
User struct {
ID string
Username string
Name string
TeamID string `json:"team_id"`
}
ResponseURL string `json:"response_url"`
Actions []actionItem
}

func (s *Server) ServeActionResponse(w http.ResponseWriter, r *http.Request) {
var req struct {
Text string
Type string `json:"response_type"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

if req.Type != "ephemeral" {
http.Error(w, "unexpected response type", http.StatusBadRequest)
return
}

actData := r.URL.Query().Get("action")
var a Action
err := json.Unmarshal([]byte(actData), &a)
if respondErr(w, err) {
return
}

msg, err := s.API().ChatPostMessage(r.Context(), ChatPostMessageOptions{
ChannelID: a.ChannelID,
Text: req.Text,
User: r.URL.Query().Get("user"),
})
if respondErr(w, err) {
return
}

var respData struct {
response
TS string
Channel string `json:"channel"`
Message *Message `json:"message"`
}
respData.TS = msg.TS
respData.OK = true
respData.Channel = msg.ChannelID
respData.Message = msg

respondWith(w, respData)
}

// PerformActionAs will preform the action as the given user.
func (s *Server) PerformActionAs(userID string, a Action) error {
usr := s.user(userID)
if usr == nil {
return errors.New("invalid Slack user ID")
}

app := s.app(a.AppID)
if app == nil {
return errors.New("invalid Slack app ID")
}

actionData, err := json.Marshal(a)
if err != nil {
return err
}

var p actionBody
p.Type = "block_actions"
p.User.ID = usr.ID
p.User.Username = usr.Name
p.User.Name = usr.Name
p.User.TeamID = a.TeamID
p.Channel.ID = a.ChannelID
p.AppID = a.AppID

tok := s.newToken(AuthToken{
User: userID,

Scopes: []string{"bot"},
})
p.ResponseURL = fmt.Sprintf("%s/actions/response?token=%s&user=%s&action=%s", strings.TrimSuffix(s.urlPrefix, "/"), url.QueryEscape(tok.ID), url.QueryEscape(usr.ID), url.QueryEscape(string(actionData)))

var action actionItem
action.ActionID = a.ActionID
action.BlockID = a.BlockID
action.Text.Type = "plain_text"
action.Text.Text = a.Text
action.Value = a.Value
action.Type = "button"
p.Actions = append(p.Actions, action)

data, err := json.Marshal(p)
if err != nil {
return fmt.Errorf("serialize action payload: %w", err)
}

v := make(url.Values)
v.Set("payload", string(data))
data = []byte(v.Encode())

req, err := http.NewRequest("POST", app.ActionURL, bytes.NewReader(data))
if err != nil {
return fmt.Errorf("create action request: %w", err)
}

req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
t := time.Now()
req.Header.Set("X-Slack-Request-Timestamp", strconv.FormatInt(t.Unix(), 10))
h := hmac.New(sha256.New, []byte(app.SigningSecret))
fmt.Fprintf(h, "v0:%d:%s", t.Unix(), string(data))
req.Header.Set("X-Slack-Signature", "v0="+fmt.Sprintf("%x", h.Sum(nil)))

resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("perform action: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != 200 {
return fmt.Errorf("perform action: %s", resp.Status)
}

return nil
}
5 changes: 5 additions & 0 deletions devtools/mockslack/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,9 @@ type Message struct {
User string `json:"user"`
Broadcast bool `json:"reply_broadcast"`
Color string `json:"color"`

ChannelID string
ToUserID string

Actions []Action
}
Loading