-
Notifications
You must be signed in to change notification settings - Fork 9
/
githubhook_test.go
82 lines (67 loc) · 2.12 KB
/
githubhook_test.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package githubhook
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"strings"
"testing"
)
const testSecret = "foobar"
func expectErrorMessage(t *testing.T, msg string, err error) {
if err == nil || err.Error() != msg {
t.Error(fmt.Sprintf("Expected '%s', got %s", msg, err))
}
}
func expectNewError(t *testing.T, msg string, r *http.Request) {
_, err := New(r)
expectErrorMessage(t, msg, err)
}
func expectParseError(t *testing.T, msg string, r *http.Request) {
_, err := Parse([]byte(testSecret), r)
expectErrorMessage(t, msg, err)
}
func signature(body string) string {
dst := make([]byte, sha256.Size*2)
computed := hmac.New(sha256.New, []byte(testSecret))
computed.Write([]byte(body))
hex.Encode(dst, computed.Sum(nil))
return signaturePrefix + string(dst)
}
func TestNonPost(t *testing.T) {
r, _ := http.NewRequest("GET", "/path", nil)
expectNewError(t, "Unknown method!", r)
}
func TestMissingSignature(t *testing.T) {
r, _ := http.NewRequest("POST", "/path", nil)
expectNewError(t, "No signature!", r)
}
func TestMissingEvent(t *testing.T) {
r, _ := http.NewRequest("POST", "/path", nil)
r.Header.Add("x-hub-signature-256", "bogus signature")
expectNewError(t, "No event!", r)
}
func TestMissingEventId(t *testing.T) {
r, _ := http.NewRequest("POST", "/path", nil)
r.Header.Add("x-hub-signature-256", "bogus signature")
r.Header.Add("x-github-event", "bogus event")
expectNewError(t, "No event Id!", r)
}
func TestInvalidSignature(t *testing.T) {
r, _ := http.NewRequest("POST", "/path", strings.NewReader("..."))
r.Header.Add("x-hub-signature-256", "bogus signature")
r.Header.Add("x-github-event", "bogus event")
r.Header.Add("x-github-delivery", "bogus id")
expectParseError(t, "Invalid signature", r)
}
func TestValidSignature(t *testing.T) {
body := "{}"
r, _ := http.NewRequest("POST", "/path", strings.NewReader(body))
r.Header.Add("x-hub-signature-256", signature(body))
r.Header.Add("x-github-event", "bogus event")
r.Header.Add("x-github-delivery", "bogus id")
if _, err := Parse([]byte(testSecret), r); err != nil {
t.Error(fmt.Sprintf("Unexpected error '%s'", err))
}
}