-
Notifications
You must be signed in to change notification settings - Fork 4
/
call.go
245 lines (209 loc) · 5.45 KB
/
call.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
/**
* Copyright 2024-present Coinbase Global, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package adv
import (
"bytes"
"context"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"github.com/golang-jwt/jwt"
"github.com/google/uuid"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
const emptyQueryParams = ""
type apiRequest struct {
path string
query string
httpMethod string
body []byte
expectedHttpStatusCode int
client Client
}
type apiResponse struct {
request *apiRequest
body []byte
httpStatusCode int
httpStatusMsg string
err error
errorMessage *ErrorMessage
}
func generateJwt(method, path, host, keyName, privateKeyPEM string) (string, error) {
keyBytes := []byte(privateKeyPEM)
block, _ := pem.Decode(keyBytes)
if block == nil {
return "", fmt.Errorf("failed to parse PEM block containing the key")
}
privateKey, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return "", fmt.Errorf("failed to parse EC private key: %w", err)
}
now := time.Now()
claims := jwt.MapClaims{
"sub": keyName,
"iss": "coinbase-cloud",
"nbf": now.Unix(),
"exp": now.Add(2 * time.Minute).Unix(),
"uri": fmt.Sprintf("%s %s%s", method, host, path),
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token.Header["kid"] = keyName
token.Header["nonce"] = uuid.New().String()
signedToken, err := token.SignedString(privateKey)
if err != nil {
return "", fmt.Errorf("failed to sign token: %w", err)
}
return signedToken, nil
}
func post(
ctx context.Context,
client Client,
path,
query string,
request,
response interface{},
) error {
return call(ctx, client, path, query, http.MethodPost, http.StatusOK, request, response)
}
func get(
ctx context.Context,
client Client,
path,
query string,
request,
response interface{},
) error {
return call(ctx, client, path, query, http.MethodGet, http.StatusOK, request, response)
}
func put(
ctx context.Context,
client Client,
path,
query string,
request,
response interface{},
) error {
return call(ctx, client, path, query, http.MethodPut, http.StatusOK, request, response)
}
func del(
ctx context.Context,
client Client,
path,
query string,
request,
response interface{},
) error {
return call(ctx, client, path, query, http.MethodDelete, http.StatusOK, request, response)
}
func call(
ctx context.Context,
client Client,
path,
query,
httpMethod string,
expectedHttpStatusCode int,
request,
response interface{},
) error {
if client.Credentials == nil {
return errors.New("credentials not set")
}
body, err := json.Marshal(request)
if err != nil {
return err
}
resp := makeCall(
ctx,
&apiRequest{
path: path,
query: query,
httpMethod: httpMethod,
body: body,
expectedHttpStatusCode: expectedHttpStatusCode,
client: client,
},
)
if resp.err != nil {
return resp.err
}
if err := json.Unmarshal(resp.body, response); err != nil {
return err
}
return nil
}
func makeCall(ctx context.Context, request *apiRequest) *apiResponse {
response := &apiResponse{
request: request,
}
callUrl := fmt.Sprintf("%s%s%s", request.client.HttpBaseUrl, request.path, request.query)
parsedUrl, err := url.Parse(callUrl)
if err != nil {
response.err = fmt.Errorf("invalid URL: %s - %w", callUrl, err)
return response
}
jwtToken, err := generateJwt(request.httpMethod, parsedUrl.Path, parsedUrl.Host, request.client.Credentials.AccessKey, request.client.Credentials.PrivatePemKey)
if err != nil {
response.err = fmt.Errorf("failed to generate JWT: %w", err)
return response
}
req, err := http.NewRequestWithContext(ctx, request.httpMethod, callUrl, bytes.NewReader(request.body))
if err != nil {
response.err = err
return response
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", jwtToken))
res, err := request.client.HttpClient.Do(req)
if err != nil {
response.err = err
return response
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
response.err = err
return response
}
response.body = body
response.httpStatusCode = res.StatusCode
response.httpStatusMsg = res.Status
if request.expectedHttpStatusCode > 0 && res.StatusCode != request.expectedHttpStatusCode {
var errMsg ErrorMessage
if strings.Contains(string(response.body), "message") {
_ = json.Unmarshal(response.body, &errMsg)
response.errorMessage = &errMsg
}
responseMsg := string(body)
if response.errorMessage != nil && len(response.errorMessage.Value) > 0 {
responseMsg = response.errorMessage.Value
}
response.err = fmt.Errorf(
"expected status code: %d - received: %d - status msg: %s - url %s - msg: %s",
request.expectedHttpStatusCode,
res.StatusCode,
res.Status,
callUrl,
responseMsg,
)
}
return response
}