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