-
Notifications
You must be signed in to change notification settings - Fork 0
/
lockbox.go
459 lines (403 loc) · 13.7 KB
/
lockbox.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package lockbox
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"time"
"yall.in"
"lockbox.dev/hmac"
"github.com/hashicorp/go-cleanhttp"
)
var (
// ErrNoAccessTokenSet is returned when the Client tries to use an
// access token but is not configured with one
ErrNoAccessTokenSet = errors.New("no access token set")
// ErrNoRefreshTokenSet is returned when the Client tries to use a
// refresh token but is not configured with one
ErrNoRefreshTokenSet = errors.New("no refresh token set")
// ErrNoClientIDSet is returned when the Client tries to use a client
// ID but is not configured with one
ErrNoClientIDSet = errors.New("no client ID set")
// ErrNoClientSecretSet is returned when the Client tries to use a
// client secret but is not configured with one
ErrNoClientSecretSet = errors.New("no client secret set")
// ErrNoClientRedirectURISet is returned when the Client tries to use a
// redirect URI but is not configured with one
ErrNoClientRedirectURISet = errors.New("no client redirect URI set")
// ErrNoClientsHMACSecretSet is returned when the Client tries to make
// an HMAC request to the clients service but is not configured with an
// HMAC secret
ErrNoClientsHMACSecretSet = errors.New("no HMAC secret for the clients service set")
// ErrNoClientsHMACMaxSkewSet is returned when the Client tries to make
// an HMAC request to the clients service but is not configured with an
// HMAC max skew
ErrNoClientsHMACMaxSkewSet = errors.New("no HMAC max skew for the clients service set")
// ErrNoClientsHMACOrgKeySet is returned when the Client tries to make
// an HMAC request to the clients service but is not configured with an
// HMAC org key
ErrNoClientsHMACOrgKeySet = errors.New("no HMAC org key for the clients service set")
// ErrNoClientsHMACKeySet is returned when the Client tries to make an
// HMAC request to the clients service but is not configured with an
// HMAC key
ErrNoClientsHMACKeySet = errors.New("no HMAC key for the clients service set")
// ErrNoScopesHMACSecretSet is returned when the Client tries to make
// an HMAC request to the scopes service but is not configured with an
// HMAC secret
ErrNoScopesHMACSecretSet = errors.New("no HMAC secret for the scopes service set")
// ErrNoScopesHMACMaxSkewSet is returned when the Client tries to make
// an HMAC request to the scopes service but is not configured with an
// HMAC max skew
ErrNoScopesHMACMaxSkewSet = errors.New("no HMAC max skew for the scopes service set")
// ErrNoScopesHMACOrgKeySet is returned when the Client tries to make
// an HMAC request to the scopes service but is not configured with an
// HMAC org key
ErrNoScopesHMACOrgKeySet = errors.New("no HMAC org key for the scopes service set")
// ErrNoScopesHMACKeySet is returned when the Client tries to make an
// HMAC request to the scopes service but is not configured with an
// HMAC key
ErrNoScopesHMACKeySet = errors.New("no HMAC key for the scopes service set")
// ErrBothClientSecretAndRedirectURISet is return when the Client tries
// to make a request using client credentials and both the redirect URI
// and client secret are set
ErrBothClientSecretAndRedirectURISet = errors.New("both client secret and redirect URI set")
)
// Client is an HTTP client that can make requests against Lockbox's various
// services and the services that use Lockbox for authentication.
type Client struct {
client *http.Client
transport *loggingTransport
baseURL *url.URL
userAgentPrepend []string
userAgentAppend []string
userAgentMu *sync.RWMutex
clientID string
clientSecret string
clientRedirectURI string
accessToken string
refreshToken string
tokenMu sync.RWMutex
hmacs hmacAuths
Accounts *AccountsService
Clients *ClientsService
OAuth2 *OAuth2Service
Scopes *ScopesService
}
type hmacAuths struct {
clients HMACAuth
scopes HMACAuth
}
// HMACAuth contains all the information necessary to authenticate against an
// HMAC-secured service, like the clients service.
type HMACAuth struct {
// MaxSkew is the maximum amount of clock skew to accept
MaxSkew time.Duration
// OrgKey is the organization key the service is using
OrgKey string
// Key is the key ID the service is using
Key string
// Secret is the HMAC secret the service is using
Secret []byte
}
// AuthMethod is a way of authenticating the Client. When constructing a
// Client, passed AuthMethods will configure the Client to authenticate with
// various services.
type AuthMethod interface {
Apply(c *Client)
}
// AuthTokens configures the client with credentials necessary to authenticate
// against services that use token authentication, like services utilising
// Lockbox as an authentication service.
type AuthTokens struct {
Access string
Refresh string
}
// Apply configures the Client `c` with the access and refresh tokens in `a`.
func (a AuthTokens) Apply(c *Client) {
c.accessToken = a.Access
c.refreshToken = a.Refresh
}
// ClientCredentials configures the client with credentials necessary to
// authenticate against services that use those credentials, like the oauth2
// service.
type ClientCredentials struct {
ID string
Secret string
RedirectURI string
}
type loggingTransport struct {
active bool
t http.RoundTripper
log *yall.Logger
mu sync.RWMutex
}
// RoundTrip makes the http.Request using the http.RoundTripper associated with
// the loggingTransport, logging the request and response if its active
// property is set to true.
func (l *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
var active bool
l.mu.RLock()
active = l.active
l.mu.RUnlock()
if active {
reqBody, err := httputil.DumpRequestOut(req, true)
if err != nil {
l.log.WithError(err).Error("error dumping request")
} else {
l.log.WithField("request", string(reqBody)).Debug("making request")
}
}
resp, err := l.t.RoundTrip(req)
if err != nil {
return resp, err
}
if active {
respData, err := httputil.DumpResponse(resp, true)
if err != nil {
l.log.WithError(err).Error("error dumping response")
} else {
l.log.WithField("response", string(respData)).Debug("got response")
}
}
return resp, nil
}
// Apply configures the Client `c` with the client ID, client secret, and
// redirect URI set on `creds`.
func (creds ClientCredentials) Apply(c *Client) {
c.clientID = creds.ID
c.clientSecret = creds.Secret
c.clientRedirectURI = creds.RedirectURI
}
// HMACCredentials configures the Client with credentials necessary to
// authenticate against HMAC-secured endpoints, like the clients service.
type HMACCredentials struct {
Clients HMACAuth
Scopes HMACAuth
}
// Apply configures the Client `c` with the HMAC credentials set in `h`.
func (h HMACCredentials) Apply(c *Client) {
c.hmacs.clients = h.Clients
c.hmacs.scopes = h.Scopes
}
// NewClient returns a new client capable of interacting with Lockbox services.
// The baseURL specified should point to the URL that lockbox-apid is serving
// at. Any number of AuthMethods can be passed to configure the client,
// including none.
func NewClient(ctx context.Context, baseURL string, auth ...AuthMethod) (*Client, error) {
base, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("error parsing baseURL: %w", err)
}
client := &Client{
client: cleanhttp.DefaultPooledClient(),
baseURL: base,
userAgentMu: new(sync.RWMutex),
}
client.transport = &loggingTransport{
log: yall.FromContext(ctx),
t: client.client.Transport,
}
client.client.Transport = client.transport
for _, method := range auth {
method.Apply(client)
}
client.Accounts = &AccountsService{
BasePath: accountsServiceDefaultBasePath,
client: client,
}
client.Clients = &ClientsService{
BasePath: clientsServiceDefaultBasePath,
client: client,
}
client.OAuth2 = &OAuth2Service{
BasePath: oauth2ServiceDefaultBasePath,
client: client,
}
client.Scopes = &ScopesService{
BasePath: scopesServiceDefaultBasePath,
client: client,
}
return client, nil
}
// RefreshTokens exchanges the token credentials configured on `c` for new
// token credentials, and configures `c` with the new token credentials.
func (c *Client) RefreshTokens(ctx context.Context, scopes []string) error {
c.tokenMu.Lock()
defer c.tokenMu.Unlock()
if c.refreshToken == "" {
return ErrNoRefreshTokenSet
}
resp, err := c.OAuth2.ExchangeRefreshToken(ctx, c.refreshToken, scopes)
if err != nil {
return fmt.Errorf("error exchanging refresh token: %w", err)
}
c.accessToken = resp.AccessToken
c.refreshToken = resp.RefreshToken
return nil
}
// EnableLogs turns on request and response logging for the client, for
// debugging purposes. This should probably not be called in production, as
// sensitive values will be logged.
func (c *Client) EnableLogs() {
c.transport.mu.Lock()
defer c.transport.mu.Unlock()
c.transport.active = true
}
// AppendToUserAgent adds the string to the end of the User-Agent header that
// will be sent with requests from this client.
func (c *Client) AppendToUserAgent(s string) {
c.userAgentMu.Lock()
c.userAgentAppend = append(c.userAgentAppend, s)
c.userAgentMu.Unlock()
}
// PrependToUserAgent adds the string to the beginning of the User-Agent header
// that will be sent with requests from this client.
func (c *Client) PrependToUserAgent(s string) {
c.userAgentMu.Lock()
c.userAgentPrepend = append(c.userAgentPrepend, s)
c.userAgentMu.Unlock()
}
// Do executes an *http.Request using the *http.Client associated with `c`.
func (c *Client) Do(req *http.Request) (*http.Response, error) {
return c.client.Do(req)
}
// NewRequest builds a new *http.Request against the specified `path`, using
// the configured base URL of the client.
func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
u, err := url.Parse(path)
if err != nil {
return nil, fmt.Errorf("error parsing path: %w", err)
}
reqURL := c.baseURL.ResolveReference(u)
req, err := http.NewRequestWithContext(ctx, method, reqURL.String(), body)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", c.buildUA())
return req, nil
}
func (c *Client) buildUA() string {
userAgent := "go-lockbox/" + getVersion()
c.userAgentMu.RLock()
uaAppend := strings.TrimSpace(strings.Join(c.userAgentAppend, " "))
uaPrepend := strings.TrimSpace(strings.Join(c.userAgentPrepend, " "))
c.userAgentMu.RUnlock()
if uaPrepend != "" {
userAgent = uaPrepend + " " + userAgent
}
if uaAppend != "" {
userAgent = userAgent + " " + uaAppend
}
return userAgent
}
// AddClientCredentials adds the configured client credentials to `r`,
// authenticating the request. This is usually used for OAuth2 requests.
func (c *Client) AddClientCredentials(r *http.Request) error {
if c.clientID == "" {
return ErrNoClientIDSet
}
if c.clientSecret == "" && c.clientRedirectURI == "" {
return ErrNoClientSecretSet
}
if c.clientSecret != "" && c.clientRedirectURI != "" {
return ErrBothClientSecretAndRedirectURISet
}
if c.clientSecret != "" {
r.SetBasicAuth(c.clientID, c.clientSecret)
return nil
}
values := r.URL.Query()
values.Set("client_id", c.clientID)
values.Set("redirect_uri", c.clientRedirectURI)
r.URL.RawQuery = values.Encode()
return nil
}
// AddTokenCredentials adds the configured tokens to `r` as credentials,
// authenticating the request.
func (c *Client) AddTokenCredentials(r *http.Request) error {
c.tokenMu.RLock()
defer c.tokenMu.RUnlock()
if c.accessToken == "" {
return ErrNoAccessTokenSet
}
r.Header.Set("Authorization", "Bearer "+c.accessToken)
return nil
}
// MakeClientsHMACRequest signs an *http.Request so it can be executed against
// the Clients service.
func (c *Client) MakeClientsHMACRequest(r *http.Request) error {
if len(c.hmacs.clients.Secret) == 0 {
return ErrNoClientsHMACSecretSet
}
if c.hmacs.clients.MaxSkew == 0 {
return ErrNoClientsHMACMaxSkewSet
}
if c.hmacs.clients.OrgKey == "" {
return ErrNoClientsHMACOrgKeySet
}
if c.hmacs.clients.Key == "" {
return ErrNoClientsHMACKeySet
}
return c.makeHMACRequest(r, c.hmacs.clients)
}
// MakeScopesHMACRequest signs an *http.Request so it can be executed against
// the Scopes service.
func (c *Client) MakeScopesHMACRequest(r *http.Request) error {
if len(c.hmacs.scopes.Secret) == 0 {
return ErrNoScopesHMACSecretSet
}
if c.hmacs.scopes.MaxSkew == 0 {
return ErrNoScopesHMACMaxSkewSet
}
if c.hmacs.scopes.OrgKey == "" {
return ErrNoScopesHMACOrgKeySet
}
if c.hmacs.scopes.Key == "" {
return ErrNoScopesHMACKeySet
}
return c.makeHMACRequest(r, c.hmacs.scopes)
}
func (*Client) makeHMACRequest(r *http.Request, auth HMACAuth) error {
var buf *bytes.Buffer
if r.Body != nil {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("error reading request body: %w", err)
}
buf = bytes.NewBuffer(body)
r.Body = ioutil.NopCloser(buf)
}
signer := hmac.Signer{
Secret: auth.Secret,
MaxSkew: auth.MaxSkew,
OrgKey: auth.OrgKey,
Key: auth.Key,
}
var content []byte
if buf != nil {
content = buf.Bytes()
}
r.Header.Set("Date", time.Now().Format(time.RFC1123))
r.Header.Set("Content-SHA256", base64.StdEncoding.EncodeToString(sha256.New().Sum(content)))
sig := signer.Sign(r)
r.Header.Set("Authorization", fmt.Sprintf("%s v1 %s:%s", signer.OrgKey, signer.Key, sig))
return nil
}
// GetTokens retrieves the currently set access and refresh tokens for the
// Client. It is meant to be used to persist the tokens to avoid authenticating
// on every Client instantiation; there should be no other reason to interact
// with the tokens this way.
func (c *Client) GetTokens() (access, refresh string) {
c.tokenMu.RLock()
defer c.tokenMu.RUnlock()
return c.accessToken, c.refreshToken
}