/
client.go
384 lines (309 loc) · 9.57 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
/*
Package Client is a Go client for the NHS FHIR API.
For more information about the API visit this link here:
https://digital.nhs.uk/developer/api-catalogue/personal-demographics-service-fhir#api-description__overview
Usage:
You use this library by creating a new client and calling methods on the client.
Example:
package main
import (
client "github.com/welldigital/nhs-fhir"
"fmt"
"context"
)
func main() {
c, err := client.NewClient()
if err != nil {
panic(err)
}
ctx := context.Background()
patient, _, err := c.Patient.Get(ctx, "9000000009")
}
*/
package client
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"github.com/google/go-querystring/query"
"github.com/google/uuid"
)
// Client manages communication with the NHS FHIR API.
type Client struct {
BaseURL *url.URL
UserAgent string
withAuth bool
httpClient *http.Client
Patient *PatientService
accessToken AccessTokenResponse
jwt string
authConfig *AuthConfigOptions
tracingConfig *TracingOptions
}
//go:generate moq -out client_moq.go . IClient
// IClient interface for Client
type IClient interface {
newRequest(method, path string, body interface{}) (*http.Request, error)
do(ctx context.Context, req *http.Request, v interface{}) (*Response, error)
postForm(ctx context.Context, url string, data url.Values, v interface{}) (*Response, error)
baseURLGetter() *url.URL
dumpHTTP(req *http.Request, resp *http.Response) error
}
var errNonNilContext = errors.New("context must be non-nil")
const (
sandboxURL = "https://sandbox.api.service.nhs.uk/"
defaultBaseURL = sandboxURL
redactedString = "** REDACTED **"
)
// NewClientWithOptions takes in some options to create the client with.
// If no options are given then its treated the same as NewClient(nil)
func NewClientWithOptions(opts *Options) (*Client, error) {
c := &Client{}
if opts == nil {
return NewClient(nil), nil
}
if opts.Client != nil {
c.httpClient = opts.Client
} else {
c.httpClient = newDefaultHttpClient()
}
c.UserAgent = opts.UserAgent
if opts.AuthConfigOptions != nil {
c.withAuth = true
c.authConfig = opts.AuthConfigOptions
}
if opts.TracingOptions != nil {
c.tracingConfig = opts.TracingOptions
}
if opts.BaseURL != "" {
baseURL, err := url.Parse(opts.BaseURL)
if err != nil {
return nil, err
}
c.BaseURL = baseURL
} else {
c.BaseURL = newDefaultBaseURL()
}
patientService := PatientService{client: c}
c.Patient = &patientService
return c, nil
}
// NewClient returns a new FHIR client. If a nil httpClient is provided then a new http.client will be used.
// To use API methods requiring auth then provide a http.Client which will perform the authentication for you e.g. oauth2
func NewClient(httpClient *http.Client) *Client {
c := &Client{}
if httpClient == nil {
c.httpClient = newDefaultHttpClient()
}
baseURL := newDefaultBaseURL()
c.BaseURL = baseURL
patientService := PatientService{client: c}
c.Patient = &patientService
return c
}
// redactFieldFromHeader - replaces the field with some fixed string
func redactFieldFromHeader(header *http.Header, field string) {
headerVal := header.Get(field)
if headerVal != "" {
header.Set(field, redactedString)
}
}
// dumpHTTP - logs both the request and response to the clients tracing output (defaults to std out).
// additionally it scrubs the sensitive authorization bearer token from the output.
func (c *Client) dumpHTTP(req *http.Request, resp *http.Response) error {
writer := c.getTraceOutputWriter()
_, err := fmt.Fprintln(writer, "||------------ BEGIN TRACE ------------||")
if err != nil {
return err
}
hasBody := resp.StatusCode == http.StatusNoContent && resp.StatusCode != http.StatusOK
// dump client outgoing request
redactFieldFromHeader(&req.Header, "Authorization")
dumpReq, err := httputil.DumpRequestOut(req, hasBody)
if err != nil {
return err
}
_, err = fmt.Fprint(writer, string(dumpReq))
if err != nil {
return err
}
// dump response
var dumpResp []byte
dumpResp, err = httputil.DumpResponse(resp, hasBody)
if err != nil {
return err
}
_, err = fmt.Fprint(writer, strings.TrimSuffix(string(dumpResp), "\r\n"))
if err != nil {
return err
}
_, err = fmt.Fprintln(writer, "||------------ END TRACE ------------||")
if err != nil {
return err
}
return nil
}
// NewRequest creates an API request. A relative URL can be provided in path,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.
func (c *Client) newRequest(method, path string, body interface{}) (*http.Request, error) {
rel := &url.URL{Path: path}
u := c.baseURLGetter().ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.UserAgent)
// Every request to NHS API should contain a unique id otherwise we receive a 429
req.Header.Set("X-Request-ID", uuid.New().String())
// sandbox doesnt have auth
if c.withAuth && c.baseURLGetter().String() != sandboxURL {
bearerToken, err := c.getAccessToken(context.Background())
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+bearerToken)
}
return req, nil
}
// Do sends an API request and returns the API response. The API response is
// JSON decoded and stored in the value pointed to by v, or returned as an
// error if an API error has occurred.
func (c *Client) do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) {
if ctx == nil {
return nil, errNonNilContext
}
req = req.WithContext(ctx)
resp, err := c.httpClientGetter().Do(req)
// use the error stored in context as likely to be more informative
if err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
defer resp.Body.Close()
if c.tracingConfig != nil && c.tracingConfig.Enabled && !(c.tracingConfig.TraceErrorsOnly && resp.StatusCode == http.StatusOK) {
if err := c.dumpHTTP(req, resp); err != nil {
return nil, err
}
}
if resp.StatusCode == 429 {
return nil, &RateLimitError{}
}
err = json.NewDecoder(resp.Body).Decode(v)
r := newResponse(resp)
r.RequestID = req.Header.Get("X-Request-ID")
return r, err
}
func (c *Client) getTraceOutputWriter() io.Writer {
if c.tracingConfig == nil || c.tracingConfig.Output == nil {
return os.Stdout
} else {
return c.tracingConfig.Output
}
}
// getAccessToken return a valid access token
// we check if the access token is valid and if not then we generate a new one
// note: the nhs fhir api does not currently provide us with a way to get a refresh token
// instead it's advised to grab a new access token
// https://digital.nhs.uk/developer/guides-and-documentation/security-and-authorisation/application-restricted-restful-apis-signed-jwt-authentication#step-8-refresh-token
func (c *Client) getAccessToken(ctx context.Context) (string, error) {
if c.accessToken.AccessToken != "" && !c.accessToken.HasExpired() {
return c.accessToken.AccessToken, nil
}
if c.jwt == "" {
jwt, err := generateSecret(*c.authConfig)
if err != nil {
return c.accessToken.AccessToken, err
}
c.jwt = *jwt
}
token, _, err := c.generateAccessToken(ctx, c.jwt)
if err != nil {
return "", err
}
return token.AccessToken, err
}
func (c *Client) postForm(ctx context.Context, url string, data url.Values, v interface{}) (*Response, error) {
resp, err := c.httpClientGetter().PostForm(url, data)
// use the error stored in context as likely to be more informative
if err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
defer resp.Body.Close()
if c.tracingConfig != nil && c.tracingConfig.Enabled && !(c.tracingConfig.TraceErrorsOnly && resp.StatusCode == http.StatusOK) {
if err := c.dumpHTTP(nil, resp); err != nil {
return nil, err
}
}
if resp.StatusCode == 429 {
return nil, &RateLimitError{}
}
err = json.NewDecoder(resp.Body).Decode(v)
return newResponse(resp), err
}
// GenerateToken gets the access token using a signed token
func (c *Client) generateAccessToken(ctx context.Context, jwt string) (*AccessTokenResponse, *Response, error) {
path := "/oauth2/token"
opts := AccessTokenRequest{
GrantType: "client_credentials",
ClientAssertionType: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
JWT: jwt,
}
data, err := query.Values(opts)
if err != nil {
return nil, nil, err
}
tokenRes := &AccessTokenResponse{}
res, err := c.postForm(ctx, c.authConfig.BaseURL+path, data, tokenRes)
if err != nil {
return nil, res, fmt.Errorf("error generating access token: %v", err)
}
c.accessToken = *tokenRes
return tokenRes, res, err
}
// baseURL retrieves a baseURL, if not set then we return the default url
func (c *Client) baseURLGetter() *url.URL {
if c.BaseURL == nil {
return newDefaultBaseURL()
}
return c.BaseURL
}
// httpClientGetter provides a way to get the underlying http client
// if the client was initialized using a struct then this guarantees that the behaviour will be normal
func (c *Client) httpClientGetter() *http.Client {
if c.httpClient == nil {
return newDefaultHttpClient()
}
return c.httpClient
}