-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
client.go
432 lines (353 loc) · 11.3 KB
/
client.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
package keygen
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/google/go-querystring/query"
"github.com/keygen-sh/jsonapi-go"
)
var (
userAgent = "keygen/" + APIVersion + " sdk/" + SDKVersion + " go/" + runtime.Version() + " " + runtime.GOOS + "/" + runtime.GOARCH
// mutex is used to sychronize access to the HTTP client.
mutex = &sync.Mutex{}
)
type Response struct {
Request *http.Request
ID string
Headers http.Header
Document *jsonapi.Document
Size int
Body []byte
Status int
}
// tldr truncates the response body if it's too large, just in case this is some
// sort of unexpected response format. We should always be responding with JSON,
// regardless of any errors that occur, but this may be from infra.
func (r *Response) tldr() string {
tldr := string(r.Body)
if len(tldr) > 500 {
tldr = tldr[0:500] + "..."
}
// Make sure a multi-line response ends up all on one line.
tldr = strings.Replace(tldr, "\n", "\\n", -1)
return tldr
}
// ClientOptions stores config options used in API requests.
type ClientOptions struct {
Account string
Environment string
LicenseKey string
Token string
PublicKey string
UserAgent string
APIVersion string
APIPrefix string
APIURL string
}
// Client represents the internal HTTP client and config used for API requests.
type Client struct {
HTTPClient *http.Client
ClientOptions
mutex *sync.Mutex
}
// NewClient creates a new Client with default settings.
func NewClient() *Client {
client := &Client{
HTTPClient,
ClientOptions{
Account: Account,
Environment: Environment,
LicenseKey: LicenseKey,
Token: Token,
PublicKey: PublicKey,
UserAgent: UserAgent,
APIPrefix: APIPrefix,
APIVersion: APIVersion,
APIURL: APIURL,
},
mutex,
}
return client
}
// NewClientWithOptions creates a new client with custom settings.
func NewClientWithOptions(options *ClientOptions) *Client {
client := &Client{
HTTPClient,
ClientOptions{
Account: options.Account,
Environment: options.Environment,
LicenseKey: options.LicenseKey,
Token: options.Token,
PublicKey: options.PublicKey,
UserAgent: options.UserAgent,
APIPrefix: options.APIPrefix,
APIVersion: options.APIVersion,
APIURL: options.APIURL,
},
mutex,
}
return client
}
// Post is a convenience helper for performing POST requests.
func (c *Client) Post(ctx context.Context, path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(ctx, http.MethodPost, path, params)
if err != nil {
return nil, err
}
return c.send(req, model)
}
// Get is a convenience helper for performing GET requests.
func (c *Client) Get(ctx context.Context, path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(ctx, http.MethodGet, path, params)
if err != nil {
return nil, err
}
return c.send(req, model)
}
// Put is a convenience helper for performing PUT requests.
func (c *Client) Put(ctx context.Context, path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(ctx, http.MethodPut, path, params)
if err != nil {
return nil, err
}
return c.send(req, model)
}
// Patch is a convenience helper for performing PATCH requests.
func (c *Client) Patch(ctx context.Context, path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(ctx, http.MethodPatch, path, params)
if err != nil {
return nil, err
}
return c.send(req, model)
}
// Delete is a convenience helper for performing DELETE requests.
func (c *Client) Delete(ctx context.Context, path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(ctx, http.MethodDelete, path, params)
if err != nil {
return nil, err
}
return c.send(req, model)
}
func (c *Client) new(ctx context.Context, method string, path string, params interface{}) (*http.Request, error) {
var url string
if c.APIVersion == "" {
c.APIVersion = APIVersion
}
if c.APIPrefix == "" {
c.APIPrefix = APIPrefix
}
if c.APIURL == "" {
c.APIURL = APIURL
}
// Local vars so we don't mutate the client
account := c.Account
prefix := c.APIPrefix
host := c.APIURL
// Add scheme if not present (e.g. with self-hosted KEYGEN_HOST env var via the CLI)
if !strings.HasPrefix(host, "https://") && !strings.HasPrefix(host, "http://") {
host = "https://" + host
}
// Support for custom domains
if host == "https://api.keygen.sh" {
url = fmt.Sprintf("%s/%s/accounts/%s/%s", host, prefix, account, path)
} else {
url = fmt.Sprintf("%s/%s/%s", host, prefix, path)
}
ua := strings.Join([]string{userAgent, c.UserAgent}, " ")
var in bytes.Buffer
if params != nil {
if method == http.MethodPost || method == http.MethodPatch || method == http.MethodPut {
serialized, err := jsonapi.Marshal(params)
if err != nil {
return nil, err
}
in = *bytes.NewBuffer(serialized)
}
if opts, ok := params.(CheckoutOptions); ok {
values, err := query.Values(opts)
if err != nil {
return nil, err
}
if enc := values.Encode(); enc != "" {
url += "?" + values.Encode()
}
}
if qs, ok := params.(querystring); ok {
values, err := query.Values(qs)
if err != nil {
return nil, err
}
if enc := values.Encode(); enc != "" {
url += "?" + values.Encode()
}
}
}
Logger.Infof("Request: method=%s url=%s size=%d", method, url, in.Len())
if in.Len() > 0 {
Logger.Debugf(" body=%s", in.Bytes())
}
req, err := http.NewRequest(method, url, &in)
if err != nil {
Logger.Errorf("Error building request: method=%s url=%s err=%v", method, url, err)
return nil, err
}
switch {
case c.LicenseKey != "":
req.Header.Add("Authorization", "License "+c.LicenseKey)
case c.Token != "":
req.Header.Add("Authorization", "Bearer "+c.Token)
}
if c.Environment != "" {
req.Header.Add("Keygen-Environment", c.Environment)
}
req.Header.Add("Keygen-Version", c.APIVersion)
if in.Len() > 0 {
req.Header.Add("Content-Type", jsonapi.ContentType)
}
req.Header.Add("Accept", jsonapi.ContentType)
req.Header.Add("User-Agent", ua)
return req.WithContext(ctx), nil
}
func (c *Client) send(req *http.Request, model interface{}) (*Response, error) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.HTTPClient.CheckRedirect = c.checkRedirect
res, err := c.HTTPClient.Do(req)
if err != nil {
Logger.Errorf("Error performing request: method=%s url=%s err=%v", req.Method, req.URL, err)
return nil, err
}
requestID := res.Header.Get("x-request-id")
out, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
Logger.Errorf("Error reading response body: id=%s status=%d err=%v", requestID, res.StatusCode, err)
return nil, err
}
response := &Response{
Request: res.Request,
ID: requestID,
Status: res.StatusCode,
Headers: res.Header,
Size: len(out),
Body: out,
}
Logger.Infof("Response: id=%s status=%d size=%d", response.ID, response.Status, response.Size)
if response.Size > 0 {
Logger.Debugf(" body=%s", response.Body)
}
// Handle certain error statuses before we check signature
switch {
case response.Status == http.StatusTooManyRequests:
err := &Error{response, "", "", "TOO_MANY_REQUESTS", ""}
window := response.Headers.Get("X-RateLimit-Window")
var retryAfter, count, limit, remaining int
var reset time.Time
if i, e := strconv.Atoi(response.Headers.Get("Retry-After")); e == nil {
retryAfter = i
}
if i, e := strconv.Atoi(response.Headers.Get("X-RateLimit-Count")); e == nil {
count = i
}
if i, e := strconv.Atoi(response.Headers.Get("X-RateLimit-Limit")); e == nil {
limit = i
}
if i, e := strconv.Atoi(response.Headers.Get("X-RateLimit-Remaining")); e == nil {
remaining = i
}
if i, e := strconv.ParseInt(response.Headers.Get("X-RateLimit-Reset"), 10, 64); e == nil {
reset = time.Unix(i, 0)
}
return response, &RateLimitError{
Window: window,
Count: count,
Limit: limit,
Remaining: remaining,
Reset: reset,
RetryAfter: retryAfter,
Err: err,
}
case response.Status >= http.StatusInternalServerError:
Logger.Errorf("An unexpected API error occurred: id=%s status=%d size=%d body=%s", response.ID, response.Status, response.Size, response.tldr())
return response, fmt.Errorf("an error occurred: id=%s status=%d size=%d body=%s", response.ID, response.Status, response.Size, response.tldr())
}
if c.PublicKey != "" {
verifier := &verifier{c.PublicKey}
if err := verifier.VerifyResponse(response); err != nil {
Logger.Errorf("Error verifying response signature: id=%s status=%d size=%d body=%s err=%v", response.ID, response.Status, response.Size, response.tldr(), err)
return response, err
}
}
if response.Status == http.StatusNoContent || response.Size == 0 {
return response, nil
}
doc, err := jsonapi.Unmarshal(response.Body, model)
if err != nil {
Logger.Errorf("Error parsing response JSON: id=%s status=%d size=%d body=%s err=%v", response.ID, response.Status, response.Size, response.tldr(), err)
return response, err
}
response.Document = doc
if len(doc.Errors) > 0 {
err := &Error{response, doc.Errors[0].Title, doc.Errors[0].Detail, doc.Errors[0].Code, doc.Errors[0].Source.Pointer}
if response.Status == http.StatusForbidden {
code := ErrorCode(err.Code)
// Handle certain license auth error codes so that we emit helpful errors
switch {
case code == ErrorCodeTokenNotAllowed:
return response, ErrTokenNotAllowed
case code == ErrorCodeTokenFormatInvalid:
return response, ErrTokenFormatInvalid
case code == ErrorCodeTokenInvalid:
return response, ErrTokenInvalid
case code == ErrorCodeTokenExpired:
return response, ErrTokenExpired
case code == ErrorCodeLicenseNotAllowed:
return response, ErrLicenseNotAllowed
case code == ErrorCodeLicenseSuspended:
return response, ErrLicenseSuspended
case code == ErrorCodeLicenseExpired:
return response, ErrLicenseExpired
default:
return response, &NotAuthorizedError{err}
}
}
// TODO(ezekg) Handle additional error codes
code := ErrorCode(doc.Errors[0].Code)
switch {
case code == ErrorCodeEnvironmentNotSupported || code == ErrorCodeEnvironmentInvalid:
return response, &EnvironmentError{err}
case code == ErrorCodeMachineHeartbeatDead || code == ErrorCodeProcessHeartbeatDead:
return response, ErrHeartbeatDead
case code == ErrorCodeFingerprintTaken:
return response, ErrMachineAlreadyActivated
case code == ErrorCodeMachineLimitExceeded:
return response, ErrMachineLimitExceeded
case code == ErrorCodeProcessLimitExceeded:
return response, ErrProcessLimitExceeded
case code == ErrorCodeComponentFingerprintConflict:
return response, ErrComponentConflict
case code == ErrorCodeComponentFingerprintTaken:
return response, ErrComponentAlreadyActivated
case code == ErrorCodeTokenInvalid:
return response, &LicenseTokenError{err}
case code == ErrorCodeLicenseInvalid:
return response, &LicenseKeyError{err}
case code == ErrorCodeNotFound:
return response, &NotFoundError{err}
default:
return response, err
}
}
return response, nil
}
// We don't want to automatically follow redirects
func (c *Client) checkRedirect(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}