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
170 changes: 157 additions & 13 deletions slack-welcomer/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,21 @@ import (
"io/ioutil"
"log"
"net/http"
"time"

"sigs.k8s.io/slack-infra/slack"
)

const (
workflowNotice = `Hi there! Your message in <#%s> was removed because that channel only accepts posts submitted via the official workflow.

To post a job listing or resume, please use the workflow shortcut (:zap:) in that channel.

If you have questions, reach out in #slack-admins.`

maxRetries = 5
)

type handler struct {
client *slack.Client
messagePath string
Expand All @@ -39,7 +50,6 @@ func logError(rw http.ResponseWriter, format string, args ...interface{}) {

type handlerFunc func(body []byte) ([]byte, error)

// ServeHTTP handles Slack webhook requests.
func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
Expand Down Expand Up @@ -96,35 +106,169 @@ func (h *handler) handleURLVerification(body []byte) ([]byte, error) {
}

func (h *handler) handleEvent(body []byte) ([]byte, error) {
event := struct {
t := struct {
Event struct {
Type string `json:"type"`
User slack.User `json:"user"`
Type string `json:"type"`
} `json:"event"`
}{}
if err := json.Unmarshal(body, &event); err != nil {
if err := json.Unmarshal(body, &t); err != nil {
return nil, fmt.Errorf("failed to parse JSON: %v", err)
}

// We should only be getting team_join events, but be sure to filter out anything else.
// We don't consider this an error, because Slack might get upset if we did.
if event.Event.Type != "team_join" {
return []byte{}, nil
switch t.Event.Type {
case "team_join":
event := struct {
Event struct {
User slack.User `json:"user"`
} `json:"event"`
}{}
if err := json.Unmarshal(body, &event); err != nil {
return nil, fmt.Errorf("failed to parse JSON: %v", err)
}
if err := h.sendWelcome(event.Event.User.ID); err != nil {
return nil, fmt.Errorf("failed to send welcome: %v", err)
}
case "message":
event := struct {
Event struct {
SubType string `json:"subtype"`
User string `json:"user"`
Channel string `json:"channel"`
Ts string `json:"ts"`
ThreadTS string `json:"thread_ts"`
BotID string `json:"bot_id"`
} `json:"event"`
}{}
if err := json.Unmarshal(body, &event); err != nil {
return nil, fmt.Errorf("failed to parse JSON: %v", err)
}
if event.Event.BotID != "" || event.Event.SubType == "bot_message" {
return []byte{}, nil
}
if event.Event.ThreadTS != "" && event.Event.ThreadTS != event.Event.Ts {
return []byte{}, nil
}
if h.isGuardedChannel(event.Event.Channel) && event.Event.User != "" {
if err := h.enforceWorkflowOnly(event.Event.Channel, event.Event.User, event.Event.Ts); err != nil {
return nil, fmt.Errorf("failed to enforce channel rules: %v", err)
}
}
}

if err := h.sendWelcome(event.Event.User.ID); err != nil {
return nil, fmt.Errorf("failed to send welcome: %v", err)
}
return []byte{}, nil
}

func (h *handler) isGuardedChannel(channel string) bool {
for _, c := range h.client.Config.GuardedChannels {
if c == channel {
return true
}
}
return false
}

func (h *handler) getUserInfo(id string) (slack.User, error) {
user := struct {
User slack.User `json:"user"`
}{}
if err := h.client.CallOldMethod("users.info", map[string]string{"user": id}, &user); err != nil {
return slack.User{}, fmt.Errorf("failed get user: %v", err)
}
return user.User, nil
}

func (h *handler) userIsAdmin(id string) (bool, error) {
user, err := h.getUserInfo(id)
if err != nil {
log.Printf("Failed to look up admin status: %v\n", err)
return false, err
}
return user.IsAdmin || user.IsOwner || user.IsPrimaryOwner, nil
}

func (h *handler) enforceWorkflowOnly(channel, userID, ts string) error {
admin, err := h.userIsAdmin(userID)
if err != nil {
log.Printf("Could not verify admin status for user %s, allowing post: %v\n", userID, err)
return nil
}
if admin {
return nil
}

log.Printf("Removing direct post from user %s in channel %s\n", userID, channel)

adminClient := slack.New(slack.Config{
AccessToken: h.client.Config.AdminToken,
SigningSecret: h.client.Config.SigningSecret,
})

req := map[string]interface{}{
"channel": channel,
"ts": ts,
"as_user": true,
}
for i := 0; i < maxRetries; i++ {
err := adminClient.CallMethod("chat.delete", req, nil)
if err == nil {
break
}
switch e := err.(type) {
case slack.ErrRateLimit:
if i == maxRetries-1 {
return fmt.Errorf("rate limit exceeded after %d retries: %v", maxRetries, err)
}
log.Printf("Slack is rate limiting us, trying again in %s...\n", e.Wait)
time.Sleep(e.Wait)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should maybe backoff with a maximum timeout. This can hang indefinitely currently (competing calls keep exhausting the rate limit)

case slack.ErrSlack:
if e.Type == "message_not_found" {
log.Printf("Message to delete not found, probably already deleted.\n")
return nil
}
return err
default:
return err
}
}

if err := h.notifyUser(userID, channel); err != nil {
log.Printf("Deleted message but failed to DM user %s: %v\n", userID, err)
}
return nil
}

func (h *handler) notifyUser(userID, channelID string) error {
response := struct {
Channel struct {
ID string `json:"id"`
} `json:"channel"`
}{}
if err := h.client.CallMethod("conversations.open", map[string]string{"users": userID}, &response); err != nil {
return fmt.Errorf("couldn't open a conversation channel: %v", err)
}
message := struct {
Channel string `json:"channel"`
Text string `json:"text"`
AsUser bool `json:"as_user"`
LinkNames bool `json:"link_names"`
}{
Channel: response.Channel.ID,
Text: fmt.Sprintf(workflowNotice, channelID),
AsUser: true,
LinkNames: true,
}
if err := h.client.CallMethod("chat.postMessage", message, nil); err != nil {
return fmt.Errorf("failed to send message: %v", err)
}
return nil
}

func (h *handler) sendWelcome(uid string) error {
welcome, err := h.getWelcome()
if err != nil {
return fmt.Errorf("couldn't get welcome: %v", err)
}

// Slack requires that we first open a "conversation channel" that we can then use to actually send messages.
response := struct {
Channel struct {
ID string `json:"id"`
Expand Down
16 changes: 11 additions & 5 deletions slack-welcomer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ func handleHealthz(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}

func runServer(sl *slack.Client, o options) {
h := &handler{client: sl, messagePath: o.messagePath}

func runServer(h *handler) error {
http.HandleFunc("/healthz", handleHealthz)
http.Handle(os.Getenv("PATH_PREFIX")+"/webhook", h)

Expand All @@ -56,7 +54,7 @@ func runServer(sl *slack.Client, o options) {
}

log.Printf("Listening on port %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
return http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
}

func main() {
Expand All @@ -65,6 +63,14 @@ func main() {
if err != nil {
log.Fatalf("Failed to load config from %s: %v", o.configPath, err)
}
if c.AdminToken == "" {
log.Fatalf("adminToken is required but was not found in %s", o.configPath)
}
if len(c.GuardedChannels) == 0 {
log.Fatalf("guardedChannels is required but was not found in %s", o.configPath)
}
s := slack.New(c)
runServer(s, o)

h := &handler{client: s, messagePath: o.messagePath}
log.Fatal(runServer(h))
}
8 changes: 5 additions & 3 deletions slack/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ import (

// Config is the information needed to communicate with Slack.
type Config struct {
SigningSecret string `json:"signingSecret"`
WebhookURL string `json:"webhook"`
AccessToken string `json:"accessToken"`
SigningSecret string `json:"signingSecret"`
WebhookURL string `json:"webhook"`
AccessToken string `json:"accessToken"`
AdminToken string `json:"adminToken"`
GuardedChannels []string `json:"guardedChannels"`
}

// LoadConfig loads a Config from a JSON file.
Expand Down