This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
clients.go
251 lines (214 loc) · 6.72 KB
/
clients.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
// Copyright 2021 the Exposure Notifications Verification Server authors
//
// 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 clients defines API clients for interacting with select APIs.
package clients
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/google/exposure-notifications-server/pkg/logging"
"github.com/google/exposure-notifications-verification-server/internal/project"
"github.com/google/exposure-notifications-verification-server/pkg/controller"
)
// Option is a customization option for the client.
type Option func(c *client) *client
// WithCookieJar installs the specified cookier jar in the client. This
// is necessary if you are making successive requests that need to utilize
// cookies.
func WithCookieJar(jar http.CookieJar) Option {
return func(c *client) *client {
c.httpClient.Jar = jar
return c
}
}
// WithTimeout sets a custom timeout for each request. The default is 5s.
func WithTimeout(d time.Duration) Option {
return func(c *client) *client {
c.httpClient.Timeout = d
return c
}
}
// WithMaxBodySize sets a custom max body size for each request. The default is
// 64kib.
func WithMaxBodySize(max int64) Option {
return func(c *client) *client {
c.maxBodySize = max
return c
}
}
// WithHostOverride creates a new client that overrides the Host header.
func WithHostOverride(host string) Option {
return func(c *client) *client {
ot := c.httpClient.Transport
c.httpClient.Transport = &hostOverrideRoundTripper{ot, host}
return c
}
}
// WithUserAgent sets a custom User-Agent header
func WithUserAgent(userAgent string) Option {
return func(c *client) *client {
c.userAgent = userAgent
return c
}
}
// WithCustomRequestHeaders injects the given headers into the request. It can
// be called multiple times.
func WithCustomRequestHeaders(headers http.Header) Option {
return func(c *client) *client {
ot := c.httpClient.Transport
c.httpClient.Transport = &headerInjectorRoundTripper{ot, headers}
return c
}
}
type hostOverrideRoundTripper struct {
original http.RoundTripper
host string
}
func (t *hostOverrideRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
if t.host != "" {
r.Host = t.host
}
return t.original.RoundTrip(r)
}
type headerInjectorRoundTripper struct {
original http.RoundTripper
headers http.Header
}
func (t *headerInjectorRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
for k := range t.headers {
r.Header.Set(k, t.headers.Get(k))
}
return t.original.RoundTrip(r)
}
// client is a private client that handles the heavy lifting.
type client struct {
httpClient *http.Client
baseURL *url.URL
apiKey string
maxBodySize int64
userAgent string
}
// newClient creates a new client.
func newClient(base, apiKey string, opts ...Option) (*client, error) {
u, err := url.Parse(base)
if err != nil {
return nil, err
}
// Enable debug response logging.
if project.DebugGoogleCloudResponses {
opts = append([]Option{WithCustomRequestHeaders(http.Header{
"X-Return-Encrypted-Headers": []string{"all_response"},
})}, opts...)
}
client := &client{
httpClient: controller.TracedHTTPClient(5 * time.Second),
baseURL: u,
apiKey: apiKey,
maxBodySize: 65536, // 64 KiB
}
for _, opt := range opts {
client = opt(client)
}
return client, nil
}
// newRequest creates a new request with the given method, path (relative to the
// baseURL), and optional body. If the body is given, it's encoded as json.
func (c *client) newRequest(ctx context.Context, method, pth string, body interface{}) (*http.Request, error) {
pth = strings.TrimPrefix(pth, "/")
u := c.baseURL.ResolveReference(&url.URL{Path: pth})
var b bytes.Buffer
if body != nil {
if err := json.NewEncoder(&b).Encode(body); err != nil {
return nil, fmt.Errorf("failed to encode JSON: %w", err)
}
}
req, err := http.NewRequestWithContext(ctx, method, u.String(), &b)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
if c.apiKey != "" {
req.Header.Set("X-API-Key", c.apiKey)
}
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
return req, nil
}
// doOK is like do, but expects a 200 response.
func (c *client) doOK(req *http.Request, out interface{}) error {
resp, err := c.do(req, out)
if err != nil {
return err
}
defer resp.Body.Close()
if project.DebugGoogleCloudResponses {
logger := logging.FromContext(req.Context())
logger.Debugw("response headers", "response_headers", resp.Header)
}
if resp.StatusCode > 299 {
return fmt.Errorf("expected 200 response, got %d", resp.StatusCode)
}
return nil
}
// errorResponse is used to extract an error from the response, if it exists.
// This is a fallback for when all else fails.
type errorResponse struct {
Error1 string `json:"error"`
Error2 string `json:"Error"`
}
// Error returns the error string, if any.
func (e *errorResponse) Error() string {
if e.Error1 != "" {
return e.Error1
}
return e.Error2
}
// do executes the request and decodes the result into out. It returns the http
// response. It does NOT do error checking on the response code.
func (c *client) do(req *http.Request, out interface{}) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
errPrefix := fmt.Sprintf("%s %s - %d", strings.ToUpper(req.Method), req.URL.String(), resp.StatusCode)
r := io.LimitReader(resp.Body, c.maxBodySize)
body, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("%s: failed to read body: %w", errPrefix, err)
}
ct := resp.Header.Get("Content-Type")
if !strings.HasPrefix(ct, "application/json") {
return nil, fmt.Errorf("%s: response content-type is not application/json (got %s): body: %s",
errPrefix, ct, body)
}
var errResp errorResponse
if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error() != "" {
return nil, fmt.Errorf("%s: error response from API: %s, err: %w, body: %s",
errPrefix, errResp.Error(), err, body)
}
if err := json.Unmarshal(body, out); err != nil {
return nil, fmt.Errorf("%s: failed to decode JSON response: %w: body: %s",
errPrefix, err, body)
}
return resp, nil
}