/
auth_config.go
300 lines (256 loc) · 7.3 KB
/
auth_config.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package httpclient
import (
"context"
"crypto"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io/fs"
"math/rand"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"github.com/benthosdev/benthos/v4/internal/filepath/ifs"
)
// AuthConfig contains configuration params for various HTTP auth strategies.
type AuthConfig struct {
OAuth OAuthConfig
BasicAuth BasicAuthConfig
JWT JWTConfig
}
// NewAuthConfig creates a new Config with default values.
func NewAuthConfig() AuthConfig {
return AuthConfig{
OAuth: NewOAuthConfig(),
BasicAuth: NewBasicAuthConfig(),
JWT: NewJWTConfig(),
}
}
// Sign method to sign an HTTP request for configured auth strategies.
func (c AuthConfig) Sign(f fs.FS, req *http.Request) error {
if err := c.OAuth.Sign(req); err != nil {
return err
}
if err := c.JWT.Sign(f, req); err != nil {
return err
}
return c.BasicAuth.Sign(req)
}
//------------------------------------------------------------------------------
// BasicAuthConfig contains fields for setting basic authentication in HTTP
// requests.
type BasicAuthConfig struct {
Enabled bool
Username string
Password string
}
// NewBasicAuthConfig returns a default configuration for basic authentication
// in HTTP client requests.
func NewBasicAuthConfig() BasicAuthConfig {
return BasicAuthConfig{
Enabled: false,
Username: "",
Password: "",
}
}
// Sign method to sign an HTTP request for an OAuth exchange.
func (basic BasicAuthConfig) Sign(req *http.Request) error {
if basic.Enabled {
req.SetBasicAuth(basic.Username, basic.Password)
}
return nil
}
//------------------------------------------------------------------------------
// JWTConfig holds the configuration parameters for an JWT exchange.
type JWTConfig struct {
Enabled bool
Claims jwt.MapClaims
Headers map[string]any
SigningMethod string
PrivateKeyFile string
// internal private fields
keyMx *sync.Mutex
key *crypto.PrivateKey
}
// NewJWTConfig returns a new JWTConfig with default values.
func NewJWTConfig() JWTConfig {
var key crypto.PrivateKey
return JWTConfig{
Enabled: false,
Claims: map[string]any{},
Headers: map[string]any{},
SigningMethod: "",
PrivateKeyFile: "",
keyMx: &sync.Mutex{},
key: &key,
}
}
// Sign method to sign an HTTP request for an JWT exchange.
func (j JWTConfig) Sign(f fs.FS, req *http.Request) error {
if !j.Enabled {
return nil
}
if err := j.parsePrivateKey(f); err != nil {
return err
}
var token *jwt.Token
switch j.SigningMethod {
case "RS256":
token = jwt.NewWithClaims(jwt.SigningMethodRS256, j.Claims)
case "RS384":
token = jwt.NewWithClaims(jwt.SigningMethodRS384, j.Claims)
case "RS512":
token = jwt.NewWithClaims(jwt.SigningMethodRS512, j.Claims)
case "EdDSA":
token = jwt.NewWithClaims(jwt.SigningMethodEdDSA, j.Claims)
default:
return fmt.Errorf("jwt signing method %s not acepted. Try with RS256, RS384, RS512 or EdDSA", j.SigningMethod)
}
for name, value := range j.Headers {
token.Header[name] = value
}
ss, err := token.SignedString(*j.key)
if err != nil {
return fmt.Errorf("failed to sign jwt: %v", err)
}
req.Header.Set("Authorization", "Bearer "+ss)
return nil
}
// parsePrivateKey parses once the RSA private key.
// Needs mutex locking as Sign might be called by parallel threads.
func (j JWTConfig) parsePrivateKey(fs fs.FS) error {
j.keyMx.Lock()
defer j.keyMx.Unlock()
if *j.key != nil {
return nil
}
privateKey, err := ifs.ReadFile(fs, j.PrivateKeyFile)
if err != nil {
return fmt.Errorf("failed to read private key: %v", err)
}
switch j.SigningMethod {
case "RS256", "RS384", "RS512":
*j.key, err = jwt.ParseRSAPrivateKeyFromPEM(privateKey)
case "EdDSA":
*j.key, err = jwt.ParseEdPrivateKeyFromPEM(privateKey)
}
if err != nil {
return fmt.Errorf("failed to parse %s private key: %v", j.SigningMethod, err)
}
return nil
}
//------------------------------------------------------------------------------
// OAuthConfig holds the configuration parameters for an OAuth exchange.
type OAuthConfig struct {
Enabled bool
ConsumerKey string
ConsumerSecret string
AccessToken string
AccessTokenSecret string
}
// NewOAuthConfig returns a new OAuthConfig with default values.
func NewOAuthConfig() OAuthConfig {
return OAuthConfig{
Enabled: false,
ConsumerKey: "",
ConsumerSecret: "",
AccessToken: "",
AccessTokenSecret: "",
}
}
// Sign method to sign an HTTP request for an OAuth exchange.
func (oauth OAuthConfig) Sign(req *http.Request) error {
if !oauth.Enabled {
return nil
}
nonceGenerator := rand.New(rand.NewSource(time.Now().UnixNano()))
nonce := strconv.FormatInt(nonceGenerator.Int63(), 10)
ts := strconv.FormatInt(time.Now().Unix(), 10)
params := &url.Values{}
params.Add("oauth_consumer_key", oauth.ConsumerKey)
params.Add("oauth_nonce", nonce)
params.Add("oauth_signature_method", "HMAC-SHA1")
params.Add("oauth_timestamp", ts)
params.Add("oauth_token", oauth.AccessToken)
params.Add("oauth_version", "1.0")
sig, err := oauth.getSignature(req, params)
if err != nil {
return err
}
str := fmt.Sprintf(
` oauth_consumer_key="%s", oauth_nonce="%s", oauth_signature="%s",`+
` oauth_signature_method="%s", oauth_timestamp="%s",`+
` oauth_token="%s", oauth_version="%s"`,
url.QueryEscape(oauth.ConsumerKey),
nonce,
url.QueryEscape(sig),
"HMAC-SHA1",
ts,
url.QueryEscape(oauth.AccessToken),
"1.0",
)
req.Header.Add("Authorization", str)
return nil
}
func (oauth OAuthConfig) getSignature(
req *http.Request,
params *url.Values,
) (string, error) {
baseSignatureString := req.Method + "&" +
url.QueryEscape(req.URL.String()) + "&" +
url.QueryEscape(params.Encode())
signingKey := url.QueryEscape(oauth.ConsumerSecret) + "&" +
url.QueryEscape(oauth.AccessTokenSecret)
return oauth.computeHMAC(baseSignatureString, signingKey)
}
func (oauth OAuthConfig) computeHMAC(
message string,
key string,
) (string, error) {
h := hmac.New(sha1.New, []byte(key))
if _, err := h.Write([]byte(message)); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(h.Sum(nil)), nil
}
//------------------------------------------------------------------------------
// OAuth2Config holds the configuration parameters for an OAuth2 exchange.
type OAuth2Config struct {
Enabled bool
ClientKey string
ClientSecret string
TokenURL string
Scopes []string
EndpointParams map[string][]string
}
// NewOAuth2Config returns a new OAuth2Config with default values.
func NewOAuth2Config() OAuth2Config {
return OAuth2Config{
Enabled: false,
ClientKey: "",
ClientSecret: "",
TokenURL: "",
Scopes: []string{},
EndpointParams: map[string][]string{},
}
}
// Client returns an http.Client with OAuth2 configured.
func (oauth OAuth2Config) Client(ctx context.Context, base *http.Client) *http.Client {
if !oauth.Enabled {
return base
}
conf := &clientcredentials.Config{
ClientID: oauth.ClientKey,
ClientSecret: oauth.ClientSecret,
TokenURL: oauth.TokenURL,
Scopes: oauth.Scopes,
EndpointParams: oauth.EndpointParams,
}
return conf.Client(context.WithValue(ctx, oauth2.HTTPClient, base))
}