1 package ghinstallation
2
3 import (
4 "bytes"
5 "fmt"
6 "io/ioutil"
7 "net/http"
8 "net/http/httptest"
9 "os"
10 "strings"
11 "testing"
12
13 jwt "github.com/golang-jwt/jwt/v4"
14 "github.com/google/go-cmp/cmp"
15 )
16
17 func TestNewAppsTransportKeyFromFile(t *testing.T) {
18 tmpfile, err := ioutil.TempFile("", "example")
19 if err != nil {
20 t.Fatal(err)
21 }
22 defer os.Remove(tmpfile.Name())
23
24 if _, err := tmpfile.Write(key); err != nil {
25 t.Fatal(err)
26 }
27 if err := tmpfile.Close(); err != nil {
28 t.Fatal(err)
29 }
30
31 _, err = NewAppsTransportKeyFromFile(&http.Transport{}, appID, tmpfile.Name())
32 if err != nil {
33 t.Fatal("unexpected error:", err)
34 }
35 }
36
37 type RoundTrip struct {
38 rt func(*http.Request) (*http.Response, error)
39 }
40
41 func (r RoundTrip) RoundTrip(req *http.Request) (*http.Response, error) {
42 return r.rt(req)
43 }
44
45 func TestAppsTransport(t *testing.T) {
46 customHeader := "my-header"
47 check := RoundTrip{
48 rt: func(req *http.Request) (*http.Response, error) {
49 h, ok := req.Header["Accept"]
50 if !ok {
51 t.Error("Header Accept not set")
52 }
53 want := []string{customHeader, acceptHeader}
54 if diff := cmp.Diff(want, h); diff != "" {
55 t.Errorf("HTTP Accept headers want->got: %s", diff)
56 }
57 return nil, nil
58 },
59 }
60
61 tr, err := NewAppsTransport(check, appID, key)
62 if err != nil {
63 t.Fatalf("error creating transport: %v", err)
64 }
65
66 req := httptest.NewRequest(http.MethodGet, "http://example.com", new(bytes.Buffer))
67 req.Header.Add("Accept", customHeader)
68 if _, err := tr.RoundTrip(req); err != nil {
69 t.Fatalf("error calling RoundTrip: %v", err)
70 }
71 }
72
73 func TestJWTExpiry(t *testing.T) {
74 key, err := jwt.ParseRSAPrivateKeyFromPEM(key)
75 if err != nil {
76 t.Fatal(err)
77 }
78
79 customHeader := "my-header"
80 check := RoundTrip{
81 rt: func(req *http.Request) (*http.Response, error) {
82 token := strings.Fields(req.Header.Get("Authorization"))[1]
83 tok, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(t *jwt.Token) (interface{}, error) {
84 if t.Header["alg"] != "RS256" {
85 return nil, fmt.Errorf("unexpected signing method: %v, expected: %v", t.Header["alg"], "RS256")
86 }
87 return &key.PublicKey, nil
88 })
89 if err != nil {
90 t.Fatalf("jwt parse: %v", err)
91 }
92
93 c := tok.Claims.(*jwt.StandardClaims)
94 if c.ExpiresAt == 0 {
95 t.Fatalf("missing exp claim")
96 }
97 return nil, nil
98 },
99 }
100
101 tr := NewAppsTransportFromPrivateKey(check, appID, key)
102 req := httptest.NewRequest(http.MethodGet, "http://example.com", new(bytes.Buffer))
103 req.Header.Add("Accept", customHeader)
104 if _, err := tr.RoundTrip(req); err != nil {
105 t.Fatalf("error calling RoundTrip: %v", err)
106 }
107 }
108
View as plain text