-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature.go
49 lines (42 loc) · 1.28 KB
/
signature.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package slap
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"io"
"net/http"
)
func (app *Application) validateSignature(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
signature := r.Header.Get("x-slack-signature")
timestamp := r.Header.Get("x-slack-request-timestamp")
if signature == "" || timestamp == "" {
http.Error(w, "Unauthenticated", http.StatusUnauthorized)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
app.logger.Error("Could not read request body", "error", err.Error())
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
r.Body = io.NopCloser(bytes.NewBuffer(body))
contents := "v0:" + timestamp + ":" + string(body)
hmac := hmac.New(sha256.New, []byte(app.signingSecret))
_, err = hmac.Write([]byte(contents))
if err != nil {
app.logger.Error("Could not write HMAC", "error", err.Error())
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
hmacHex := hex.EncodeToString(hmac.Sum(nil))
expected := "v0=" + hmacHex
if subtle.ConstantTimeCompare([]byte(expected), []byte(signature)) == 0 {
http.Error(w, "Unauthenticated", http.StatusUnauthorized)
return
}
handler(w, r)
}
}