-
Notifications
You must be signed in to change notification settings - Fork 3
/
roundtripper.go
83 lines (66 loc) · 1.97 KB
/
roundtripper.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
package grafton
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/manifoldco/go-signature"
)
// Signer is the interface used to sign outgoing request payloads.
type Signer interface {
Sign([]byte) (*signature.Signature, error)
}
// SigningRoundTripper implements http.RoundTripper, signing requests before
// sending them.
type signingRoundTripper struct {
rt http.RoundTripper
signer Signer
}
// NewSigningRoundTripper returns an http.RoundTripper that will sign requests
// with the given signer before passing them on to the given RoundTripper.
func newSigningRoundTripper(rt http.RoundTripper, signer Signer) *signingRoundTripper {
return &signingRoundTripper{
rt: rt,
signer: signer,
}
}
// RoundTrip implements the http.RoundTripper interface
func (rt *signingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Date", time.Now().UTC().Format(time.RFC3339))
headers := []string{"host", "date"}
if req.Header.Get("X-Callback-ID") != "" {
headers = append(headers, "x-callback-id")
}
if req.Header.Get("X-Callback-URL") != "" {
headers = append(headers, "x-callback-url")
}
b := &bytes.Buffer{}
if req.Body != nil {
n, err := b.ReadFrom(req.Body)
if err != nil {
return nil, err
}
defer req.Body.Close()
if n != 0 {
// Since we've read from the Body (which is a ReadCloser),
// we have to replace with a new ReadCloser!
req.Body = ioutil.NopCloser(bytes.NewReader(b.Bytes()))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Length", fmt.Sprintf("%d", b.Len()))
headers = append(headers, "content-type", "content-length")
}
}
req.Header.Set("X-Signed-Headers", strings.ToLower(strings.Join(headers, " ")))
canonical, err := signature.Canonize(req, b)
if err != nil {
return nil, err
}
sig, err := rt.signer.Sign(canonical)
if err != nil {
return nil, err
}
req.Header.Set("X-Signature", sig.String())
return rt.rt.RoundTrip(req)
}