17344: Ensure server-to-controller traffic stays local.
[arvados.git] / sdk / go / arvados / client.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "context"
10         "crypto/tls"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "io/fs"
16         "io/ioutil"
17         "log"
18         "net"
19         "net/http"
20         "net/url"
21         "os"
22         "regexp"
23         "strings"
24         "time"
25
26         "git.arvados.org/arvados.git/sdk/go/httpserver"
27 )
28
29 // A Client is an HTTP client with an API endpoint and a set of
30 // Arvados credentials.
31 //
32 // It offers methods for accessing individual Arvados APIs, and
33 // methods that implement common patterns like fetching multiple pages
34 // of results using List APIs.
35 type Client struct {
36         // HTTP client used to make requests. If nil,
37         // DefaultSecureClient or InsecureHTTPClient will be used.
38         Client *http.Client `json:"-"`
39
40         // Protocol scheme: "http", "https", or "" (https)
41         Scheme string
42
43         // Hostname (or host:port) of Arvados API server.
44         APIHost string
45
46         // User authentication token.
47         AuthToken string
48
49         // Accept unverified certificates. This works only if the
50         // Client field is nil: otherwise, it has no effect.
51         Insecure bool
52
53         // Override keep service discovery with a list of base
54         // URIs. (Currently there are no Client methods for
55         // discovering keep services so this is just a convenience for
56         // callers who use a Client to initialize an
57         // arvadosclient.ArvadosClient.)
58         KeepServiceURIs []string `json:",omitempty"`
59
60         // HTTP headers to add/override in outgoing requests.
61         SendHeader http.Header
62
63         // Timeout for requests. NewClientFromConfig and
64         // NewClientFromEnv return a Client with a default 5 minute
65         // timeout.  To disable this timeout and rely on each
66         // http.Request's context deadline instead, set Timeout to
67         // zero.
68         Timeout time.Duration
69
70         dd *DiscoveryDocument
71
72         defaultRequestID string
73
74         // APIHost and AuthToken were loaded from ARVADOS_* env vars
75         // (used to customize "no host/token" error messages)
76         loadedFromEnv bool
77 }
78
79 // InsecureHTTPClient is the default http.Client used by a Client with
80 // Insecure==true and Client==nil.
81 var InsecureHTTPClient = &http.Client{
82         Transport: &http.Transport{
83                 TLSClientConfig: &tls.Config{
84                         InsecureSkipVerify: true}}}
85
86 // DefaultSecureClient is the default http.Client used by a Client otherwise.
87 var DefaultSecureClient = &http.Client{}
88
89 // NewClientFromConfig creates a new Client that uses the endpoints in
90 // the given cluster.
91 //
92 // AuthToken is left empty for the caller to populate.
93 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
94         ctrlURL := cluster.Services.Controller.ExternalURL
95         if ctrlURL.Host == "" {
96                 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
97         }
98         var hc *http.Client
99         if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
100                 // When this client is used to make a request to
101                 // https://{ctrlhost}:port/ (any port), it dials the
102                 // indicated port on ARVADOS_SERVER_ADDRESS instead.
103                 //
104                 // This is invoked by arvados-server boot to ensure
105                 // that server->server traffic (e.g.,
106                 // keepproxy->controller) only hits local interfaces,
107                 // even if the Controller.ExternalURL host is a load
108                 // balancer / gateway and not a local interface
109                 // address (e.g., when running on a cloud VM).
110                 //
111                 // This avoids unnecessary delay/cost of routing
112                 // external traffic, and also allows controller to
113                 // recognize other services as internal clients based
114                 // on the connection source address.
115                 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
116                 var dialer net.Dialer
117                 hc = &http.Client{
118                         Transport: &http.Transport{
119                                 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
120                                 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
121                                         host, port, err := net.SplitHostPort(addr)
122                                         if err == nil && network == "tcp" && host == divertedHost {
123                                                 addr = net.JoinHostPort(srvaddr, port)
124                                         }
125                                         return dialer.DialContext(ctx, network, addr)
126                                 },
127                         },
128                 }
129         }
130         return &Client{
131                 Client:   hc,
132                 Scheme:   ctrlURL.Scheme,
133                 APIHost:  ctrlURL.Host,
134                 Insecure: cluster.TLS.Insecure,
135                 Timeout:  5 * time.Minute,
136         }, nil
137 }
138
139 // NewClientFromEnv creates a new Client that uses the default HTTP
140 // client, and loads API endpoint and credentials from ARVADOS_*
141 // environment variables (if set) and
142 // $HOME/.config/arvados/settings.conf (if readable).
143 //
144 // If a config exists in both locations, the environment variable is
145 // used.
146 //
147 // If there is an error (other than ENOENT) reading settings.conf,
148 // NewClientFromEnv logs the error to log.Default(), then proceeds as
149 // if settings.conf did not exist.
150 //
151 // Space characters are trimmed when reading the settings file, so
152 // these are equivalent:
153 //
154 //   ARVADOS_API_HOST=localhost\n
155 //   ARVADOS_API_HOST=localhost\r\n
156 //   ARVADOS_API_HOST = localhost \n
157 //   \tARVADOS_API_HOST = localhost\n
158 func NewClientFromEnv() *Client {
159         vars := map[string]string{}
160         home := os.Getenv("HOME")
161         conffile := home + "/.config/arvados/settings.conf"
162         if home == "" {
163                 // no $HOME => just use env vars
164         } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
165                 // no config file => just use env vars
166         } else if err != nil {
167                 // config file unreadable => log message, then use env vars
168                 log.Printf("continuing without loading %s: %s", conffile, err)
169         } else {
170                 for _, line := range bytes.Split(settings, []byte{'\n'}) {
171                         kv := bytes.SplitN(line, []byte{'='}, 2)
172                         k := string(bytes.TrimSpace(kv[0]))
173                         if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
174                                 // Same behavior as python sdk:
175                                 // silently skip leading # (comments),
176                                 // blank lines, typos, and non-Arvados
177                                 // vars.
178                                 continue
179                         }
180                         vars[k] = string(bytes.TrimSpace(kv[1]))
181                 }
182         }
183         for _, env := range os.Environ() {
184                 if !strings.HasPrefix(env, "ARVADOS_") {
185                         continue
186                 }
187                 kv := strings.SplitN(env, "=", 2)
188                 if len(kv) == 2 {
189                         vars[kv[0]] = kv[1]
190                 }
191         }
192         var svcs []string
193         for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
194                 if s == "" {
195                         continue
196                 } else if u, err := url.Parse(s); err != nil {
197                         log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
198                 } else if !u.IsAbs() {
199                         log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
200                 } else {
201                         svcs = append(svcs, s)
202                 }
203         }
204         var insecure bool
205         if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
206                 insecure = true
207         }
208         return &Client{
209                 Scheme:          "https",
210                 APIHost:         vars["ARVADOS_API_HOST"],
211                 AuthToken:       vars["ARVADOS_API_TOKEN"],
212                 Insecure:        insecure,
213                 KeepServiceURIs: svcs,
214                 Timeout:         5 * time.Minute,
215                 loadedFromEnv:   true,
216         }
217 }
218
219 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
220
221 // Do adds Authorization and X-Request-Id headers and then calls
222 // (*http.Client)Do().
223 func (c *Client) Do(req *http.Request) (*http.Response, error) {
224         if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
225                 req.Header.Add("Authorization", auth)
226         } else if c.AuthToken != "" {
227                 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
228         }
229
230         if req.Header.Get("X-Request-Id") == "" {
231                 var reqid string
232                 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
233                         reqid = ctxreqid
234                 } else if c.defaultRequestID != "" {
235                         reqid = c.defaultRequestID
236                 } else {
237                         reqid = reqIDGen.Next()
238                 }
239                 if req.Header == nil {
240                         req.Header = http.Header{"X-Request-Id": {reqid}}
241                 } else {
242                         req.Header.Set("X-Request-Id", reqid)
243                 }
244         }
245         var cancel context.CancelFunc
246         if c.Timeout > 0 {
247                 ctx := req.Context()
248                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
249                 req = req.WithContext(ctx)
250         }
251         resp, err := c.httpClient().Do(req)
252         if err == nil && cancel != nil {
253                 // We need to call cancel() eventually, but we can't
254                 // use "defer cancel()" because the context has to
255                 // stay alive until the caller has finished reading
256                 // the response body.
257                 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
258         } else if cancel != nil {
259                 cancel()
260         }
261         return resp, err
262 }
263
264 // cancelOnClose calls a provided CancelFunc when its wrapped
265 // ReadCloser's Close() method is called.
266 type cancelOnClose struct {
267         io.ReadCloser
268         cancel context.CancelFunc
269 }
270
271 func (coc cancelOnClose) Close() error {
272         err := coc.ReadCloser.Close()
273         coc.cancel()
274         return err
275 }
276
277 func isRedirectStatus(code int) bool {
278         switch code {
279         case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
280                 return true
281         default:
282                 return false
283         }
284 }
285
286 // DoAndDecode performs req and unmarshals the response (which must be
287 // JSON) into dst. Use this instead of RequestAndDecode if you need
288 // more control of the http.Request object.
289 //
290 // If the response status indicates an HTTP redirect, the Location
291 // header value is unmarshalled to dst as a RedirectLocation
292 // key/field.
293 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
294         resp, err := c.Do(req)
295         if err != nil {
296                 return err
297         }
298         defer resp.Body.Close()
299         buf, err := ioutil.ReadAll(resp.Body)
300         if err != nil {
301                 return err
302         }
303         switch {
304         case resp.StatusCode == http.StatusNoContent:
305                 return nil
306         case resp.StatusCode == http.StatusOK && dst == nil:
307                 return nil
308         case resp.StatusCode == http.StatusOK:
309                 return json.Unmarshal(buf, dst)
310
311         // If the caller uses a client with a custom CheckRedirect
312         // func, Do() might return the 3xx response instead of
313         // following it.
314         case isRedirectStatus(resp.StatusCode) && dst == nil:
315                 return nil
316         case isRedirectStatus(resp.StatusCode):
317                 // Copy the redirect target URL to dst.RedirectLocation.
318                 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
319                 if err != nil {
320                         return err
321                 }
322                 return json.Unmarshal(buf, dst)
323
324         default:
325                 return newTransactionError(req, resp, buf)
326         }
327 }
328
329 // Convert an arbitrary struct to url.Values. For example,
330 //
331 //     Foo{Bar: []int{1,2,3}, Baz: "waz"}
332 //
333 // becomes
334 //
335 //     url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
336 //
337 // params itself is returned if it is already an url.Values.
338 func anythingToValues(params interface{}) (url.Values, error) {
339         if v, ok := params.(url.Values); ok {
340                 return v, nil
341         }
342         // TODO: Do this more efficiently, possibly using
343         // json.Decode/Encode, so the whole thing doesn't have to get
344         // encoded, decoded, and re-encoded.
345         j, err := json.Marshal(params)
346         if err != nil {
347                 return nil, err
348         }
349         var generic map[string]interface{}
350         dec := json.NewDecoder(bytes.NewBuffer(j))
351         dec.UseNumber()
352         err = dec.Decode(&generic)
353         if err != nil {
354                 return nil, err
355         }
356         urlValues := url.Values{}
357         for k, v := range generic {
358                 if v, ok := v.(string); ok {
359                         urlValues.Set(k, v)
360                         continue
361                 }
362                 if v, ok := v.(json.Number); ok {
363                         urlValues.Set(k, v.String())
364                         continue
365                 }
366                 if v, ok := v.(bool); ok {
367                         if v {
368                                 urlValues.Set(k, "true")
369                         } else {
370                                 // "foo=false", "foo=0", and "foo="
371                                 // are all taken as true strings, so
372                                 // don't send false values at all --
373                                 // rely on the default being false.
374                         }
375                         continue
376                 }
377                 j, err := json.Marshal(v)
378                 if err != nil {
379                         return nil, err
380                 }
381                 if bytes.Equal(j, []byte("null")) {
382                         // don't add it to urlValues at all
383                         continue
384                 }
385                 urlValues.Set(k, string(j))
386         }
387         return urlValues, nil
388 }
389
390 // RequestAndDecode performs an API request and unmarshals the
391 // response (which must be JSON) into dst. Method and body arguments
392 // are the same as for http.NewRequest(). The given path is added to
393 // the server's scheme/host/port to form the request URL. The given
394 // params are passed via POST form or query string.
395 //
396 // path must not contain a query string.
397 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
398         return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
399 }
400
401 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
402 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
403         if body, ok := body.(io.Closer); ok {
404                 // Ensure body is closed even if we error out early
405                 defer body.Close()
406         }
407         if c.APIHost == "" {
408                 if c.loadedFromEnv {
409                         return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
410                 }
411                 return errors.New("arvados.Client cannot perform request: APIHost is not set")
412         }
413         urlString := c.apiURL(path)
414         urlValues, err := anythingToValues(params)
415         if err != nil {
416                 return err
417         }
418         if urlValues == nil {
419                 // Nothing to send
420         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
421                 // Send params in query part of URL
422                 u, err := url.Parse(urlString)
423                 if err != nil {
424                         return err
425                 }
426                 u.RawQuery = urlValues.Encode()
427                 urlString = u.String()
428         } else {
429                 body = strings.NewReader(urlValues.Encode())
430         }
431         req, err := http.NewRequest(method, urlString, body)
432         if err != nil {
433                 return err
434         }
435         if (method == "GET" || method == "HEAD") && body != nil {
436                 req.Header.Set("X-Http-Method-Override", method)
437                 req.Method = "POST"
438         }
439         req = req.WithContext(ctx)
440         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
441         for k, v := range c.SendHeader {
442                 req.Header[k] = v
443         }
444         return c.DoAndDecode(dst, req)
445 }
446
447 type resource interface {
448         resourceName() string
449 }
450
451 // UpdateBody returns an io.Reader suitable for use as an http.Request
452 // Body for a create or update API call.
453 func (c *Client) UpdateBody(rsc resource) io.Reader {
454         j, err := json.Marshal(rsc)
455         if err != nil {
456                 // Return a reader that returns errors.
457                 r, w := io.Pipe()
458                 w.CloseWithError(err)
459                 return r
460         }
461         v := url.Values{rsc.resourceName(): {string(j)}}
462         return bytes.NewBufferString(v.Encode())
463 }
464
465 // WithRequestID returns a new shallow copy of c that sends the given
466 // X-Request-Id value (instead of a new randomly generated one) with
467 // each subsequent request that doesn't provide its own via context or
468 // header.
469 func (c *Client) WithRequestID(reqid string) *Client {
470         cc := *c
471         cc.defaultRequestID = reqid
472         return &cc
473 }
474
475 func (c *Client) httpClient() *http.Client {
476         switch {
477         case c.Client != nil:
478                 return c.Client
479         case c.Insecure:
480                 return InsecureHTTPClient
481         default:
482                 return DefaultSecureClient
483         }
484 }
485
486 func (c *Client) apiURL(path string) string {
487         scheme := c.Scheme
488         if scheme == "" {
489                 scheme = "https"
490         }
491         return scheme + "://" + c.APIHost + "/" + path
492 }
493
494 // DiscoveryDocument is the Arvados server's description of itself.
495 type DiscoveryDocument struct {
496         BasePath                     string              `json:"basePath"`
497         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
498         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
499         GitURL                       string              `json:"gitUrl"`
500         Schemas                      map[string]Schema   `json:"schemas"`
501         Resources                    map[string]Resource `json:"resources"`
502 }
503
504 type Resource struct {
505         Methods map[string]ResourceMethod `json:"methods"`
506 }
507
508 type ResourceMethod struct {
509         HTTPMethod string         `json:"httpMethod"`
510         Path       string         `json:"path"`
511         Response   MethodResponse `json:"response"`
512 }
513
514 type MethodResponse struct {
515         Ref string `json:"$ref"`
516 }
517
518 type Schema struct {
519         UUIDPrefix string `json:"uuidPrefix"`
520 }
521
522 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
523 // should not be modified: the same object may be returned by
524 // subsequent calls.
525 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
526         if c.dd != nil {
527                 return c.dd, nil
528         }
529         var dd DiscoveryDocument
530         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
531         if err != nil {
532                 return nil, err
533         }
534         c.dd = &dd
535         return c.dd, nil
536 }
537
538 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
539
540 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
541         if pdhRegexp.MatchString(uuid) {
542                 return "Collection", nil
543         }
544         if len(uuid) != 27 {
545                 return "", fmt.Errorf("invalid UUID: %q", uuid)
546         }
547         infix := uuid[6:11]
548         var model string
549         for m, s := range dd.Schemas {
550                 if s.UUIDPrefix == infix {
551                         model = m
552                         break
553                 }
554         }
555         if model == "" {
556                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
557         }
558         return model, nil
559 }
560
561 func (c *Client) KindForUUID(uuid string) (string, error) {
562         dd, err := c.DiscoveryDocument()
563         if err != nil {
564                 return "", err
565         }
566         model, err := c.modelForUUID(dd, uuid)
567         if err != nil {
568                 return "", err
569         }
570         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
571 }
572
573 func (c *Client) PathForUUID(method, uuid string) (string, error) {
574         dd, err := c.DiscoveryDocument()
575         if err != nil {
576                 return "", err
577         }
578         model, err := c.modelForUUID(dd, uuid)
579         if err != nil {
580                 return "", err
581         }
582         var resource string
583         for r, rsc := range dd.Resources {
584                 if rsc.Methods["get"].Response.Ref == model {
585                         resource = r
586                         break
587                 }
588         }
589         if resource == "" {
590                 return "", fmt.Errorf("no resource for model: %q", model)
591         }
592         m, ok := dd.Resources[resource].Methods[method]
593         if !ok {
594                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
595         }
596         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
597         if path[0] == '/' {
598                 path = path[1:]
599         }
600         return path, nil
601 }