Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
155 changes: 142 additions & 13 deletions slack-welcomer/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,25 @@ import (
"io/ioutil"
"log"
"net/http"
"time"

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

var guardedChannels = map[string]bool{
"C25QWBR71": true, // #kubernetes-careers

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.

Should probably be configurable? I think there are other instances of this application (CNCF?)

May also make this testable against another instance.

}

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.`

type handler struct {
client *slack.Client
messagePath string
adminToken string
}

func logError(rw http.ResponseWriter, format string, args ...interface{}) {
Expand All @@ -39,7 +51,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 +107,153 @@ 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"`
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 guardedChannels[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) 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.adminToken,
SigningSecret: h.client.Config.SigningSecret,
})

req := map[string]interface{}{
"channel": channel,
"ts": ts,
"as_user": true,
}
for {
err := adminClient.CallMethod("chat.delete", req, nil)
if err == nil {
break
}
switch e := err.(type) {
case slack.ErrRateLimit:
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
30 changes: 25 additions & 5 deletions slack-welcomer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ limitations under the License.
package main

import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
Expand All @@ -43,9 +45,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 +56,21 @@ 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 loadAdminToken(path string) (string, error) {
extraConf := struct {
AdminToken string `json:"adminToken"`
}{}
content, err := ioutil.ReadFile(path)
if err != nil {
return "", fmt.Errorf("couldn't open file: %v", err)
}
if err := json.Unmarshal(content, &extraConf); err != nil {
return "", fmt.Errorf("couldn't parse config: %v", err)
}
return extraConf.AdminToken, nil
}

func main() {
Expand All @@ -65,6 +79,12 @@ func main() {
if err != nil {
log.Fatalf("Failed to load config from %s: %v", o.configPath, err)
}
adminToken, err := loadAdminToken(o.configPath)

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.

Can we make this part of the main config instead of reading in configPath twice?

if err != nil {
log.Fatalf("Failed to load admin token from %s: %v", o.configPath, err)
}
s := slack.New(c)
runServer(s, o)

h := &handler{client: s, messagePath: o.messagePath, adminToken: adminToken}
log.Fatal(runServer(h))
}