Skip to content

Commit

Permalink
fix: adds verification of slack request
Browse files Browse the repository at this point in the history
  • Loading branch information
ajpauwels committed Oct 5, 2023
1 parent 9b95e10 commit a23e05e
Show file tree
Hide file tree
Showing 5 changed files with 201 additions and 9 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ go.work

# executable file
slack-bot

# dot-env files
*.env
2 changes: 2 additions & 0 deletions config/base.yaml
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
port: 8080
slack:
signingkey: ""
24 changes: 22 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,26 @@ module github.com/pauwels-labs/slack-bot

go 1.21.1

require go.uber.org/zap v1.26.0
require (
github.com/ajpauwels/pit-of-vipers v1.0.3
go.uber.org/zap v1.26.0
)

require go.uber.org/multierr v1.10.0 // indirect
require (
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.10.1 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect
golang.org/x/text v0.3.7 // indirect
gopkg.in/ini.v1 v1.66.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
56 changes: 56 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,14 +1,70 @@
github.com/ajpauwels/pit-of-vipers v1.0.3 h1:5oLAgq8GPglqfezMzOlYKiJxZ2NaTW36hZb31Feo7PA=
github.com/ajpauwels/pit-of-vipers v1.0.3/go.mod h1:W0XhLRHi5ePju1cFND41E8CpQJSof0Foi0pPzvc6B00=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI=
github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs=
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls=
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs=
github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pelletier/go-toml v1.9.4 h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM=
github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY=
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA=
github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.10.1 h1:nuJZuYpG7gTj/XqiUwg8bA0cp1+M2mC3J4g5luUYBKk=
github.com/spf13/viper v1.10.1/go.mod h1:IGlFPqhNAPKRxohIzWpI5QEy4kuI7tcl5WvR+8qy1rU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 h1:5hpz5aRr+W1erYCL5JRhSUBJRph7l9XkNveoExlrKYk=
golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.66.2 h1:XfR1dOYubytKy4Shzc2LHrrGhU0lDCfDGG1yLPmpgsI=
gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
125 changes: 118 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,97 @@
package main

import (
"crypto/hmac"
"crypto/sha256"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"

viperpit "github.com/ajpauwels/pit-of-vipers"
"go.uber.org/zap"
)

func HandlerWithLogger(logger *zap.Logger) func(http.ResponseWriter, *http.Request) {
type SlackConfig struct {
SigningKey string `mapstructure:"signingkey"`
}

type Config struct {
Port uint16 `mapstructure:"port"`
Slack SlackConfig `mapstructure:"slack"`
}

func BuildHandler(logger *zap.Logger, config *Config) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
logger.Info("handling http request", zap.String("path", r.URL.Path))

// Ensure the request uses the POST method
method := r.Method
if method != "POST" {
logger.Error("incorrect request method", zap.String("method", method))
w.Header().Set("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
io.WriteString(w, "error: must be a POST request")
return
}

// Ensure the request includes a signature header
signatureHeader := []byte(r.Header.Get("x-slack-signature"))
if len(signatureHeader) == 0 {
logger.Error("missing request x-slack-signature-header")
w.Header().Set("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "error: must include the x-slack-signature header")
return
}

// Ensure the request includes a timestamp header
timestampHeader := []byte(r.Header.Get("x-slack-request-timestamp"))
if len(timestampHeader) == 0 {
logger.Error("missing request x-slack-request-timestamp header")
w.Header().Set("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "error: must include the x-slack-request-timestamp header")
return
}

// Parse the form body as a string
body, err := io.ReadAll(r.Body)
if err != nil {
logger.Error("unable to parse request body", zap.Error(err))
w.Header().Set("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "error: unable to read request body")
return
}

// Create the secured request signature using the Slack signing key
baseString := fmt.Sprintf("v0:%s:%s", timestampHeader, body)
mac := hmac.New(sha256.New, []byte(config.Slack.SigningKey))
bytesWritten, err := mac.Write([]byte(baseString))
if err != nil {
logger.Error("unable to compute request signature", zap.Error(err), zap.Int("bytesWritten", bytesWritten))
w.Header().Set("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "error: unable to compute request signature")
return
}
signatureComputed := mac.Sum(nil)

// Compare the generated signature with the provided signature
if !hmac.Equal(signatureHeader, signatureComputed) {
logger.Error("computed signature and provided signature do not match", zap.String("computed", string(signatureComputed)), zap.String("provided", string(signatureHeader)))
w.Header().Set("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "error: computed signature and provided signature do not match")
return
}

w.Header().Set("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
io.WriteString(w, "ok")
}
}

Expand All @@ -21,11 +103,40 @@ func main() {
}
defer logger.Sync()

// Define handlers
http.HandleFunc("/", HandlerWithLogger(logger))
// Load configuration
vpCh, errCh := viperpit.NewFromPathsAndName([]string{"./config"}, "base")
for {
select {
case vp := <-vpCh:
// Workaround to add ENV prefix and be able to unmarshal env-provided values
vp.SetEnvPrefix("SERVICE")
vp.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
for _, key := range vp.AllKeys() {
val := vp.Get(key)
vp.Set(key, val)
}

// Unmarshal config into struct
var config Config
vp.Unmarshal(&config)

// Start server
logger.Info("starting server", zap.Int("port", 8080))
err = http.ListenAndServe(":8080", nil)
logger.Error("failed to start http server", zap.Error(err))
logger.Info("config", zap.Uint16("port", config.Port), zap.String("slack.signingkey", string(config.Slack.SigningKey)))

// Define handlers
mux := http.NewServeMux()
mux.HandleFunc("/", BuildHandler(logger, &config))

// Start server
logger.Info("starting server", zap.Uint16("port", config.Port))
err = http.ListenAndServe(fmt.Sprintf(":%d", config.Port), mux)
if errors.Is(err, http.ErrServerClosed) {
logger.Info("server has shutdown normally")
break
} else {
logger.Fatal("failed to start http server", zap.Error(err))
}
case err := <-errCh:
logger.Error("error loading config", zap.Error(err))
}
}
}

0 comments on commit a23e05e

Please sign in to comment.