Merge branch '16265-security-updates' into dependabot/bundler/apps/workbench/loofah...
[arvados.git] / sdk / go / arvadosclient / arvadosclient.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 /* Simple Arvados Go SDK for communicating with API server. */
6
7 package arvadosclient
8
9 import (
10         "bytes"
11         "crypto/tls"
12         "crypto/x509"
13         "encoding/json"
14         "errors"
15         "fmt"
16         "io"
17         "io/ioutil"
18         "log"
19         "net/http"
20         "net/url"
21         "os"
22         "regexp"
23         "strings"
24         "sync"
25         "time"
26
27         "git.arvados.org/arvados.git/sdk/go/arvados"
28 )
29
30 type StringMatcher func(string) bool
31
32 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
33 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
34
35 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
36 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
37 var ErrInvalidArgument = errors.New("Invalid argument")
38
39 // A common failure mode is to reuse a keepalive connection that has been
40 // terminated (in a way that we can't detect) for being idle too long.
41 // POST and DELETE are not safe to retry automatically, so we minimize
42 // such failures by always using a new or recently active socket.
43 var MaxIdleConnectionDuration = 30 * time.Second
44
45 var RetryDelay = 2 * time.Second
46
47 var (
48         defaultInsecureHTTPClient *http.Client
49         defaultSecureHTTPClient   *http.Client
50         defaultHTTPClientMtx      sync.Mutex
51 )
52
53 // Indicates an error that was returned by the API server.
54 type APIServerError struct {
55         // Address of server returning error, of the form "host:port".
56         ServerAddress string
57
58         // Components of server response.
59         HttpStatusCode    int
60         HttpStatusMessage string
61
62         // Additional error details from response body.
63         ErrorDetails []string
64 }
65
66 func (e APIServerError) Error() string {
67         if len(e.ErrorDetails) > 0 {
68                 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
69                         strings.Join(e.ErrorDetails, "; "),
70                         e.HttpStatusCode,
71                         e.HttpStatusMessage,
72                         e.ServerAddress)
73         } else {
74                 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
75                         e.HttpStatusCode,
76                         e.HttpStatusMessage,
77                         e.ServerAddress)
78         }
79 }
80
81 // StringBool tests whether s is suggestive of true. It returns true
82 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
83 func StringBool(s string) bool {
84         s = strings.ToLower(s)
85         return s == "1" || s == "yes" || s == "true"
86 }
87
88 // Helper type so we don't have to write out 'map[string]interface{}' every time.
89 type Dict map[string]interface{}
90
91 // Information about how to contact the Arvados server
92 type ArvadosClient struct {
93         // https
94         Scheme string
95
96         // Arvados API server, form "host:port"
97         ApiServer string
98
99         // Arvados API token for authentication
100         ApiToken string
101
102         // Whether to require a valid SSL certificate or not
103         ApiInsecure bool
104
105         // Client object shared by client requests.  Supports HTTP KeepAlive.
106         Client *http.Client
107
108         // If true, sets the X-External-Client header to indicate
109         // the client is outside the cluster.
110         External bool
111
112         // Base URIs of Keep services, e.g., {"https://host1:8443",
113         // "https://host2:8443"}.  If this is nil, Keep clients will
114         // use the arvados.v1.keep_services.accessible API to discover
115         // available services.
116         KeepServiceURIs []string
117
118         // Discovery document
119         DiscoveryDoc Dict
120
121         lastClosedIdlesAt time.Time
122
123         // Number of retries
124         Retries int
125
126         // X-Request-Id for outgoing requests
127         RequestID string
128 }
129
130 var CertFiles = []string{
131         "/etc/arvados/ca-certificates.crt",
132         "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
133         "/etc/pki/tls/certs/ca-bundle.crt",   // Fedora/RHEL
134 }
135
136 // MakeTLSConfig sets up TLS configuration for communicating with
137 // Arvados and Keep services.
138 func MakeTLSConfig(insecure bool) *tls.Config {
139         tlsconfig := tls.Config{InsecureSkipVerify: insecure}
140
141         if !insecure {
142                 // Use the first entry in CertFiles that we can read
143                 // certificates from. If none of those work out, use
144                 // the Go defaults.
145                 certs := x509.NewCertPool()
146                 for _, file := range CertFiles {
147                         data, err := ioutil.ReadFile(file)
148                         if err != nil {
149                                 if !os.IsNotExist(err) {
150                                         log.Printf("error reading %q: %s", file, err)
151                                 }
152                                 continue
153                         }
154                         if !certs.AppendCertsFromPEM(data) {
155                                 log.Printf("unable to load any certificates from %v", file)
156                                 continue
157                         }
158                         tlsconfig.RootCAs = certs
159                         break
160                 }
161         }
162
163         return &tlsconfig
164 }
165
166 // New returns an ArvadosClient using the given arvados.Client
167 // configuration. This is useful for callers who load arvados.Client
168 // fields from configuration files but still need to use the
169 // arvadosclient.ArvadosClient package.
170 func New(c *arvados.Client) (*ArvadosClient, error) {
171         ac := &ArvadosClient{
172                 Scheme:      "https",
173                 ApiServer:   c.APIHost,
174                 ApiToken:    c.AuthToken,
175                 ApiInsecure: c.Insecure,
176                 Client: &http.Client{
177                         Timeout: 5 * time.Minute,
178                         Transport: &http.Transport{
179                                 TLSClientConfig: MakeTLSConfig(c.Insecure)},
180                 },
181                 External:          false,
182                 Retries:           2,
183                 KeepServiceURIs:   c.KeepServiceURIs,
184                 lastClosedIdlesAt: time.Now(),
185         }
186
187         return ac, nil
188 }
189
190 // MakeArvadosClient creates a new ArvadosClient using the standard
191 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
192 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
193 // ARVADOS_KEEP_SERVICES.
194 func MakeArvadosClient() (ac *ArvadosClient, err error) {
195         ac, err = New(arvados.NewClientFromEnv())
196         if err != nil {
197                 return
198         }
199         ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
200         return
201 }
202
203 // CallRaw is the same as Call() but returns a Reader that reads the
204 // response body, instead of taking an output object.
205 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
206         scheme := c.Scheme
207         if scheme == "" {
208                 scheme = "https"
209         }
210         u := url.URL{
211                 Scheme: scheme,
212                 Host:   c.ApiServer}
213
214         if resourceType != API_DISCOVERY_RESOURCE {
215                 u.Path = "/arvados/v1"
216         }
217
218         if resourceType != "" {
219                 u.Path = u.Path + "/" + resourceType
220         }
221         if uuid != "" {
222                 u.Path = u.Path + "/" + uuid
223         }
224         if action != "" {
225                 u.Path = u.Path + "/" + action
226         }
227
228         if parameters == nil {
229                 parameters = make(Dict)
230         }
231
232         vals := make(url.Values)
233         for k, v := range parameters {
234                 if s, ok := v.(string); ok {
235                         vals.Set(k, s)
236                 } else if m, err := json.Marshal(v); err == nil {
237                         vals.Set(k, string(m))
238                 }
239         }
240
241         retryable := false
242         switch method {
243         case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
244                 retryable = true
245         }
246
247         // Non-retryable methods such as POST are not safe to retry automatically,
248         // so we minimize such failures by always using a new or recently active socket
249         if !retryable {
250                 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
251                         c.lastClosedIdlesAt = time.Now()
252                         c.Client.Transport.(*http.Transport).CloseIdleConnections()
253                 }
254         }
255
256         // Make the request
257         var req *http.Request
258         var resp *http.Response
259
260         for attempt := 0; attempt <= c.Retries; attempt++ {
261                 if method == "GET" || method == "HEAD" {
262                         u.RawQuery = vals.Encode()
263                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
264                                 return nil, err
265                         }
266                 } else {
267                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
268                                 return nil, err
269                         }
270                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
271                 }
272
273                 // Add api token header
274                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
275                 if c.RequestID != "" {
276                         req.Header.Add("X-Request-Id", c.RequestID)
277                 }
278                 if c.External {
279                         req.Header.Add("X-External-Client", "1")
280                 }
281
282                 resp, err = c.Client.Do(req)
283                 if err != nil {
284                         if retryable {
285                                 time.Sleep(RetryDelay)
286                                 continue
287                         } else {
288                                 return nil, err
289                         }
290                 }
291
292                 if resp.StatusCode == http.StatusOK {
293                         return resp.Body, nil
294                 }
295
296                 defer resp.Body.Close()
297
298                 switch resp.StatusCode {
299                 case 408, 409, 422, 423, 500, 502, 503, 504:
300                         time.Sleep(RetryDelay)
301                         continue
302                 default:
303                         return nil, newAPIServerError(c.ApiServer, resp)
304                 }
305         }
306
307         if resp != nil {
308                 return nil, newAPIServerError(c.ApiServer, resp)
309         }
310         return nil, err
311 }
312
313 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
314
315         ase := APIServerError{
316                 ServerAddress:     ServerAddress,
317                 HttpStatusCode:    resp.StatusCode,
318                 HttpStatusMessage: resp.Status}
319
320         // If the response body has {"errors":["reason1","reason2"]}
321         // then return those reasons.
322         var errInfo = Dict{}
323         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
324                 if errorList, ok := errInfo["errors"]; ok {
325                         if errArray, ok := errorList.([]interface{}); ok {
326                                 for _, errItem := range errArray {
327                                         // We expect an array of strings here.
328                                         // Non-strings will be passed along
329                                         // JSON-encoded.
330                                         if s, ok := errItem.(string); ok {
331                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
332                                         } else if j, err := json.Marshal(errItem); err == nil {
333                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
334                                         }
335                                 }
336                         }
337                 }
338         }
339         return ase
340 }
341
342 // Call an API endpoint and parse the JSON response into an object.
343 //
344 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
345 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
346 //   uuid - the uuid of the specific item to access. May be empty.
347 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
348 //   parameters - method parameters.
349 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
350 //
351 // Returns a non-nil error if an error occurs making the API call, the
352 // API responds with a non-successful HTTP status, or an error occurs
353 // parsing the response body.
354 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
355         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
356         if reader != nil {
357                 defer reader.Close()
358         }
359         if err != nil {
360                 return err
361         }
362
363         if output != nil {
364                 dec := json.NewDecoder(reader)
365                 if err = dec.Decode(output); err != nil {
366                         return err
367                 }
368         }
369         return nil
370 }
371
372 // Create a new resource. See Call for argument descriptions.
373 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
374         return c.Call("POST", resourceType, "", "", parameters, output)
375 }
376
377 // Delete a resource. See Call for argument descriptions.
378 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
379         return c.Call("DELETE", resource, uuid, "", parameters, output)
380 }
381
382 // Modify attributes of a resource. See Call for argument descriptions.
383 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
384         return c.Call("PUT", resourceType, uuid, "", parameters, output)
385 }
386
387 // Get a resource. See Call for argument descriptions.
388 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
389         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
390                 // No object has uuid == "": there is no need to make
391                 // an API call. Furthermore, the HTTP request for such
392                 // an API call would be "GET /arvados/v1/type/", which
393                 // is liable to be misinterpreted as the List API.
394                 return ErrInvalidArgument
395         }
396         return c.Call("GET", resourceType, uuid, "", parameters, output)
397 }
398
399 // List resources of a given type. See Call for argument descriptions.
400 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
401         return c.Call("GET", resource, "", "", parameters, output)
402 }
403
404 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
405
406 // Discovery returns the value of the given parameter in the discovery
407 // document. Returns a non-nil error if the discovery document cannot
408 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
409 // parameter is not found in the discovery document.
410 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
411         if len(c.DiscoveryDoc) == 0 {
412                 c.DiscoveryDoc = make(Dict)
413                 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
414                 if err != nil {
415                         return nil, err
416                 }
417         }
418
419         var found bool
420         value, found = c.DiscoveryDoc[parameter]
421         if found {
422                 return value, nil
423         } else {
424                 return value, ErrInvalidArgument
425         }
426 }
427
428 func (ac *ArvadosClient) httpClient() *http.Client {
429         if ac.Client != nil {
430                 return ac.Client
431         }
432         c := &defaultSecureHTTPClient
433         if ac.ApiInsecure {
434                 c = &defaultInsecureHTTPClient
435         }
436         if *c == nil {
437                 defaultHTTPClientMtx.Lock()
438                 defer defaultHTTPClientMtx.Unlock()
439                 *c = &http.Client{Transport: &http.Transport{
440                         TLSClientConfig: MakeTLSConfig(ac.ApiInsecure)}}
441         }
442         return *c
443 }