generated from ZEISS/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sing.go
114 lines (92 loc) · 1.86 KB
/
sing.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
108
109
110
111
112
113
114
package carry
import (
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/zeiss/pkg/b64"
)
// SignProvid provides a Signer for requests.
type SignerProvider interface {
Sign(req *http.Request) error
}
type noopSigner struct{}
func (s noopSigner) Sign(req *http.Request) error {
return nil
}
// NewHMacSigner returns a new HMACSigner.
func NewHMacSigner(key string) *HMACSigner {
return &HMACSigner{
Key: key,
}
}
// HMACSigner signs requests with an HMAC signature.
type HMACSigner struct {
Key string
}
// Sign signs the request with an HMAC signature.
func (s HMACSigner) Sign(req *http.Request) error {
r, err := req.GetBody()
if err != nil {
return err
}
b, err := io.ReadAll(r)
if err != nil {
return err
}
reqURL, err := url.Parse(req.URL.String())
if err != nil {
return err
}
host := reqURL.Host
reqURL.Host = ""
reqURL.Scheme = ""
date := time.Now().UTC().Format(http.TimeFormat)
hash, authHeader, err := createAuthHeader(
req.Method,
host,
reqURL.String(),
date,
s.Key,
b,
)
if err != nil {
return err
}
req.Header.Set("x-ms-date", date)
req.Header.Set("x-ms-content-sha256", hash)
req.Header.Set("Authorization", authHeader)
req.Header.Set("Content-Type", "application/json")
return nil
}
func createAuthHeader(method string, host string, path string, date string, secret string, body []byte) (string, string, error) {
hash, err := b64.ContentHash(body)
if err != nil {
return "", "", err
}
msg := stringBuilder(
method,
"\n",
path,
"\n",
date,
";",
host,
";",
hash,
)
sig, err := b64.Hmac256(msg, secret)
if err != nil {
return "", "", err
}
authorizationHeader := signedHeaderPrefix + sig
return hash, authorizationHeader, nil
}
func stringBuilder(strs ...string) string {
buff := strings.Builder{}
for _, str := range strs {
buff.WriteString(str)
}
return buff.String()
}