forked from keygen-sh/keygen-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
341 lines (276 loc) · 8.83 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
package keygen
import (
"bytes"
"fmt"
"io"
"net/http"
"runtime"
"strconv"
"strings"
"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
)
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
LicenseKey string
Token string
PublicKey string
UserAgent string
}
// Client represents the internal HTTP client and config used for API requests.
type Client struct {
HTTPClient *http.Client
ClientOptions
}
// NewClient creates a new Client with default settings.
func NewClient() *Client {
client := &Client{
HTTPClient,
ClientOptions{
Account: Account,
LicenseKey: LicenseKey,
Token: Token,
PublicKey: PublicKey,
UserAgent: UserAgent,
},
}
return client
}
// NewClientWithOptions creates a new client with custom settings.
func NewClientWithOptions(options *ClientOptions) *Client {
client := &Client{
HTTPClient,
ClientOptions{
Account: options.Account,
LicenseKey: options.LicenseKey,
Token: options.Token,
PublicKey: options.PublicKey,
UserAgent: options.UserAgent,
},
}
return client
}
// Post is a convenience helper for performing POST requests.
func (c *Client) Post(path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(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(path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(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(path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(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(path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(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(path string, params interface{}, model interface{}) (*Response, error) {
req, err := c.new(http.MethodDelete, path, params)
if err != nil {
return nil, err
}
return c.send(req, model)
}
func (c *Client) new(method string, path string, params interface{}) (*http.Request, error) {
var url string
// Support for custom domains
if APIURL == "https://api.keygen.sh" {
url = fmt.Sprintf("%s/%s/accounts/%s/%s", APIURL, APIPrefix, c.Account, path)
} else {
url = fmt.Sprintf("%s/%s/%s", APIURL, APIPrefix, 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 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)
}
req.Header.Add("Keygen-Version", APIVersion)
req.Header.Add("Content-Type", jsonapi.ContentType)
req.Header.Add("Accept", jsonapi.ContentType)
req.Header.Add("User-Agent", ua)
return req, nil
}
func (c *Client) send(req *http.Request, model interface{}) (*Response, error) {
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 {
return response, &NotAuthorizedError{err}
}
// TODO(ezekg) Handle additional error codes
code := ErrorCode(doc.Errors[0].Code)
switch {
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 == 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
}