-
Notifications
You must be signed in to change notification settings - Fork 8
/
authenticator.go
166 lines (147 loc) · 4.08 KB
/
authenticator.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package httpsign
import (
"bytes"
"encoding/base64"
"fmt"
"net/http"
"strings"
"github.com/gin-contrib/httpsign/validator"
"github.com/gin-gonic/gin"
)
const (
requestTarget = "(request-target)"
date = "date"
digest = "digest"
host = "host"
)
var defaultRequiredHeaders = []string{requestTarget, date, digest}
// Authenticator is the gin authenticator middleware.
type Authenticator struct {
secrets Secrets
validators []validator.Validator
headers []string
}
// Option is the option to the Authenticator constructor.
type Option func(*Authenticator)
// WithValidator configures the Authenticator to use custom validator.
// The default validators are time based and digest.
func WithValidator(validators ...validator.Validator) Option {
return func(a *Authenticator) {
a.validators = validators
}
}
// WithRequiredHeaders is list of all requires HTTP headers that the client
// have to include in the singing string for the request to be considered valid.
// If not provided, the created Authenticator instance will use defaultRequiredHeaders variable.
func WithRequiredHeaders(headers []string) Option {
return func(a *Authenticator) {
a.headers = headers
}
}
// NewAuthenticator creates a new Authenticator instance with
// given allowed permissions and required header and secret keys.
func NewAuthenticator(secretKeys Secrets, options ...Option) *Authenticator {
a := &Authenticator{secrets: secretKeys}
for _, fn := range options {
fn(a)
}
if a.validators == nil {
a.validators = []validator.Validator{
validator.NewDateValidator(),
validator.NewDigestValidator(),
}
}
if len(a.headers) == 0 {
a.headers = defaultRequiredHeaders
}
return a
}
// Authenticated returns a gin middleware which permits given permissions in parameter.
func (a *Authenticator) Authenticated() gin.HandlerFunc {
return func(c *gin.Context) {
sigHeader, err := NewSignatureHeader(c.Request)
if err != nil {
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}
for _, v := range a.validators {
if err := v.Validate(c.Request); err != nil {
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}
}
if !a.isValidHeader(sigHeader.headers) {
_ = c.AbortWithError(http.StatusBadRequest, ErrHeaderNotEnough)
return
}
secret, err := a.getSecret(sigHeader.keyID, sigHeader.algorithm)
if err != nil {
if err == ErrInvalidKeyID {
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}
signString := constructSignMessage(c.Request, sigHeader.headers)
signature, err := secret.Algorithm.Sign(signString, secret.Key)
if err != nil {
_ = c.AbortWithError(http.StatusInternalServerError, err)
return
}
signatureBase64 := base64.StdEncoding.EncodeToString(signature)
if signatureBase64 != sigHeader.signature {
_ = c.AbortWithError(http.StatusUnauthorized, ErrInvalidSign)
return
}
c.Next()
}
}
// isValidHeader check if all server required header is in header list
func (a *Authenticator) isValidHeader(headers []string) bool {
m := len(headers)
for _, h := range a.headers {
i := 0
for i = 0; i < m; i++ {
if h == headers[i] {
break
}
}
if i == m {
return false
}
}
return true
}
func (a *Authenticator) getSecret(keyID KeyID, algorithm string) (*Secret, error) {
secret, ok := a.secrets[keyID]
if !ok {
return nil, ErrInvalidKeyID
}
if secret.Algorithm.Name() != algorithm {
if algorithm != "" {
return nil, ErrIncorrectAlgorithm
}
}
return secret, nil
}
func constructSignMessage(r *http.Request, headers []string) string {
var signBuffer bytes.Buffer
for i, field := range headers {
var fieldValue string
switch field {
case host:
fieldValue = r.Host
case requestTarget:
fieldValue = fmt.Sprintf("%s %s", strings.ToLower(r.Method), r.URL.RequestURI())
default:
fieldValue = r.Header.Get(field)
}
signString := fmt.Sprintf("%s: %s", field, fieldValue)
signBuffer.WriteString(signString)
if i < len(headers)-1 {
signBuffer.WriteString("\n")
}
}
return signBuffer.String()
}