-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsignatureheader.go
86 lines (75 loc) · 1.9 KB
/
signatureheader.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
package httpsign
import (
"net/http"
"strings"
)
const (
authorizationHeader = "Authorization"
authorizationHeaderInitString = "Signature "
signatureHeader = "Signature"
signingKeyID = "keyId"
signingAlgorithm = "algorithm"
signingSignature = "signature"
signingHeaders = "headers"
)
// SignatureHeader contains basic info signature header
type SignatureHeader struct {
keyID KeyID
headers []string
signature string
algorithm string
}
// NewSignatureHeader new instance of SignatureHeader
func NewSignatureHeader(r *http.Request) (*SignatureHeader, error) {
return parseHTTPRequest(r)
}
func parseHTTPRequest(r *http.Request) (*SignatureHeader, error) {
s, err := getSignatureString(r)
if err != nil {
return nil, err
}
return parseSignatureString(s)
}
func parseSignatureString(s string) (*SignatureHeader, error) {
p := newParser(s)
results, err := p.parse()
if err != nil {
return nil, err
}
keyID, ok := results[signingKeyID]
if !ok {
return nil, ErrMissingKeyID
}
signature, ok := results[signingSignature]
if !ok {
return nil, ErrMissingSignature
}
headerString, ok := results[signingHeaders]
var headers []string
if !ok || len(headerString) == 0 {
headers = []string{"date"}
} else {
headers = strings.Split(headerString, " ")
}
algorithm := results[signingAlgorithm]
return &SignatureHeader{
keyID: KeyID(keyID),
signature: signature,
headers: headers,
algorithm: algorithm,
}, nil
}
func getSignatureString(r *http.Request) (string, error) {
s := r.Header.Get(signatureHeader)
if s != "" {
return s, nil
}
s = r.Header.Get(authorizationHeader)
if s != "" {
if strings.Index(s, authorizationHeaderInitString) != 0 {
return "", ErrInvalidAuthorizationHeader
}
return strings.TrimPrefix(s, authorizationHeaderInitString), nil
}
return "", ErrNoSignature
}