forked from bradleyfalzon/ghinstallation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
appsTransport_test.go
107 lines (93 loc) · 2.55 KB
/
appsTransport_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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package ghinstallation
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/google/go-cmp/cmp"
)
func TestNewAppsTransportKeyFromFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "example")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write(key); err != nil {
t.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
}
_, err = NewAppsTransportKeyFromFile(&http.Transport{}, appID, tmpfile.Name())
if err != nil {
t.Fatal("unexpected error:", err)
}
}
type RoundTrip struct {
rt func(*http.Request) (*http.Response, error)
}
func (r RoundTrip) RoundTrip(req *http.Request) (*http.Response, error) {
return r.rt(req)
}
func TestAppsTransport(t *testing.T) {
customHeader := "my-header"
check := RoundTrip{
rt: func(req *http.Request) (*http.Response, error) {
h, ok := req.Header["Accept"]
if !ok {
t.Error("Header Accept not set")
}
want := []string{customHeader, acceptHeader}
if diff := cmp.Diff(want, h); diff != "" {
t.Errorf("HTTP Accept headers want->got: %s", diff)
}
return nil, nil
},
}
tr, err := NewAppsTransport(check, appID, key)
if err != nil {
t.Fatalf("error creating transport: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "http://example.com", new(bytes.Buffer))
req.Header.Add("Accept", customHeader)
if _, err := tr.RoundTrip(req); err != nil {
t.Fatalf("error calling RoundTrip: %v", err)
}
}
func TestJWTExpiry(t *testing.T) {
key, err := jwt.ParseRSAPrivateKeyFromPEM(key)
if err != nil {
t.Fatal(err)
}
customHeader := "my-header"
check := RoundTrip{
rt: func(req *http.Request) (*http.Response, error) {
token := strings.Fields(req.Header.Get("Authorization"))[1]
tok, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(t *jwt.Token) (interface{}, error) {
if t.Header["alg"] != "RS256" {
return nil, fmt.Errorf("unexpected signing method: %v, expected: %v", t.Header["alg"], "RS256")
}
return &key.PublicKey, nil
})
if err != nil {
t.Fatalf("jwt parse: %v", err)
}
c := tok.Claims.(*jwt.StandardClaims)
if c.ExpiresAt == 0 {
t.Fatalf("missing exp claim")
}
return nil, nil
},
}
tr := NewAppsTransportFromPrivateKey(check, appID, key)
req := httptest.NewRequest(http.MethodGet, "http://example.com", new(bytes.Buffer))
req.Header.Add("Accept", customHeader)
if _, err := tr.RoundTrip(req); err != nil {
t.Fatalf("error calling RoundTrip: %v", err)
}
}