Merge branch 'jszlenk/create_new_subproject' refs #21937
[arvados.git] / lib / controller / rpc / conn.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package rpc
6
7 import (
8         "bufio"
9         "bytes"
10         "context"
11         "crypto/tls"
12         "encoding/json"
13         "errors"
14         "fmt"
15         "io"
16         "io/ioutil"
17         "net"
18         "net/http"
19         "net/http/httputil"
20         "net/url"
21         "strconv"
22         "strings"
23         "sync"
24         "time"
25
26         "git.arvados.org/arvados.git/sdk/go/arvados"
27         "git.arvados.org/arvados.git/sdk/go/auth"
28         "git.arvados.org/arvados.git/sdk/go/ctxlog"
29         "git.arvados.org/arvados.git/sdk/go/httpserver"
30 )
31
32 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
33
34 type TokenProvider func(context.Context) ([]string, error)
35
36 func PassthroughTokenProvider(ctx context.Context) ([]string, error) {
37         incoming, ok := auth.FromContext(ctx)
38         if !ok {
39                 return nil, errors.New("no token provided")
40         }
41         return incoming.Tokens, nil
42 }
43
44 type Conn struct {
45         SendHeader         http.Header
46         RedactHostInErrors bool
47
48         clusterID                string
49         httpClient               http.Client
50         baseURL                  url.URL
51         tokenProvider            TokenProvider
52         discoveryDocument        *arvados.DiscoveryDocument
53         discoveryDocumentMtx     sync.Mutex
54         discoveryDocumentExpires time.Time
55 }
56
57 func NewConn(clusterID string, url *url.URL, insecure bool, tp TokenProvider) *Conn {
58         transport := http.DefaultTransport
59         if insecure {
60                 // It's not safe to copy *http.DefaultTransport
61                 // because it has a mutex (which might be locked)
62                 // protecting a private map (which might not be nil).
63                 // So we build our own, using the Go 1.12 default
64                 // values, ignoring any changes the application has
65                 // made to http.DefaultTransport.
66                 transport = &http.Transport{
67                         DialContext: (&net.Dialer{
68                                 Timeout:   30 * time.Second,
69                                 KeepAlive: 30 * time.Second,
70                                 DualStack: true,
71                         }).DialContext,
72                         MaxIdleConns:          100,
73                         IdleConnTimeout:       90 * time.Second,
74                         TLSHandshakeTimeout:   10 * time.Second,
75                         ExpectContinueTimeout: 1 * time.Second,
76                         TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
77                 }
78         }
79         return &Conn{
80                 clusterID: clusterID,
81                 httpClient: http.Client{
82                         CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse },
83                         Transport:     transport,
84                 },
85                 baseURL:       *url,
86                 tokenProvider: tp,
87         }
88 }
89
90 func (conn *Conn) requestAndDecode(ctx context.Context, dst interface{}, ep arvados.APIEndpoint, body io.Reader, opts interface{}) error {
91         aClient := arvados.Client{
92                 Client:     &conn.httpClient,
93                 Scheme:     conn.baseURL.Scheme,
94                 APIHost:    conn.baseURL.Host,
95                 SendHeader: conn.SendHeader,
96                 // Disable auto-retry
97                 Timeout: 0,
98         }
99         tokens, err := conn.tokenProvider(ctx)
100         if err != nil {
101                 return err
102         } else if len(tokens) > 0 {
103                 ctx = arvados.ContextWithAuthorization(ctx, "Bearer "+tokens[0])
104         } else {
105                 // Use a non-empty auth string to ensure we override
106                 // any default token set on aClient -- and to avoid
107                 // having the remote prompt us to send a token by
108                 // responding 401.
109                 ctx = arvados.ContextWithAuthorization(ctx, "Bearer -")
110         }
111
112         // Encode opts to JSON and decode from there to a
113         // map[string]interface{}, so we can munge the query params
114         // using the JSON key names specified by opts' struct tags.
115         j, err := json.Marshal(opts)
116         if err != nil {
117                 return fmt.Errorf("%T: requestAndDecode: Marshal opts: %s", conn, err)
118         }
119         var params map[string]interface{}
120         dec := json.NewDecoder(bytes.NewBuffer(j))
121         dec.UseNumber()
122         err = dec.Decode(&params)
123         if err != nil {
124                 return fmt.Errorf("%T: requestAndDecode: Decode opts: %s", conn, err)
125         }
126         if attrs, ok := params["attrs"]; ok && ep.AttrsKey != "" {
127                 params[ep.AttrsKey] = attrs
128                 delete(params, "attrs")
129         }
130         if limitStr, ok := params["limit"]; ok {
131                 if limit, err := strconv.ParseInt(string(limitStr.(json.Number)), 10, 64); err == nil && limit < 0 {
132                         // Negative limit means "not specified" here, but some
133                         // servers/versions do not accept that, so we need to
134                         // remove it entirely.
135                         delete(params, "limit")
136                 }
137         }
138
139         if authinfo, ok := params["auth_info"]; ok {
140                 if tmp, ok2 := authinfo.(map[string]interface{}); ok2 {
141                         for k, v := range tmp {
142                                 if strings.HasSuffix(k, "_at") {
143                                         // Change zero times values to nil
144                                         if v, ok3 := v.(string); ok3 && (strings.HasPrefix(v, "0001-01-01T00:00:00") || v == "") {
145                                                 tmp[k] = nil
146                                         }
147                                 }
148                         }
149                 }
150         }
151
152         if len(tokens) > 1 {
153                 if params == nil {
154                         params = make(map[string]interface{})
155                 }
156                 params["reader_tokens"] = tokens[1:]
157         }
158         path := ep.Path
159         if strings.Contains(ep.Path, "/{uuid}") && params != nil {
160                 uuid, _ := params["uuid"].(string)
161                 path = strings.Replace(path, "/{uuid}", "/"+uuid, 1)
162                 delete(params, "uuid")
163         }
164         err = aClient.RequestAndDecodeContext(ctx, dst, ep.Method, path, body, params)
165         if err != nil && conn.RedactHostInErrors {
166                 redacted := strings.Replace(err.Error(), strings.TrimSuffix(conn.baseURL.String(), "/"), "//railsapi.internal", -1)
167                 if strings.HasPrefix(redacted, "request failed: ") {
168                         redacted = strings.Replace(redacted, "request failed: ", "", -1)
169                 }
170                 if redacted != err.Error() {
171                         if err, ok := err.(httpStatusError); ok {
172                                 return wrapHTTPStatusError(err, redacted)
173                         } else {
174                                 return errors.New(redacted)
175                         }
176                 }
177         }
178         return err
179 }
180
181 func (conn *Conn) BaseURL() url.URL {
182         return conn.baseURL
183 }
184
185 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
186         ep := arvados.EndpointConfigGet
187         var resp json.RawMessage
188         err := conn.requestAndDecode(ctx, &resp, ep, nil, nil)
189         return resp, err
190 }
191
192 func (conn *Conn) VocabularyGet(ctx context.Context) (arvados.Vocabulary, error) {
193         ep := arvados.EndpointVocabularyGet
194         var resp arvados.Vocabulary
195         err := conn.requestAndDecode(ctx, &resp, ep, nil, nil)
196         return resp, err
197 }
198
199 func (conn *Conn) DiscoveryDocument(ctx context.Context) (arvados.DiscoveryDocument, error) {
200         conn.discoveryDocumentMtx.Lock()
201         defer conn.discoveryDocumentMtx.Unlock()
202         if conn.discoveryDocument != nil && time.Now().Before(conn.discoveryDocumentExpires) {
203                 return *conn.discoveryDocument, nil
204         }
205         var dd arvados.DiscoveryDocument
206         err := conn.requestAndDecode(ctx, &dd, arvados.EndpointDiscoveryDocument, nil, nil)
207         if err != nil {
208                 return dd, err
209         }
210         conn.discoveryDocument = &dd
211         conn.discoveryDocumentExpires = time.Now().Add(time.Hour)
212         return *conn.discoveryDocument, nil
213 }
214
215 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
216         ep := arvados.EndpointLogin
217         var resp arvados.LoginResponse
218         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
219         resp.RedirectLocation = conn.relativeToBaseURL(resp.RedirectLocation)
220         return resp, err
221 }
222
223 func (conn *Conn) Logout(ctx context.Context, options arvados.LogoutOptions) (arvados.LogoutResponse, error) {
224         ep := arvados.EndpointLogout
225         var resp arvados.LogoutResponse
226         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
227         resp.RedirectLocation = conn.relativeToBaseURL(resp.RedirectLocation)
228         return resp, err
229 }
230
231 // If the given location is a valid URL and its origin is the same as
232 // conn.baseURL, return it as a relative URL. Otherwise, return it
233 // unmodified.
234 func (conn *Conn) relativeToBaseURL(location string) string {
235         u, err := url.Parse(location)
236         if err == nil && u.Scheme == conn.baseURL.Scheme && strings.ToLower(u.Host) == strings.ToLower(conn.baseURL.Host) {
237                 u.Opaque = ""
238                 u.Scheme = ""
239                 u.User = nil
240                 u.Host = ""
241                 return u.String()
242         }
243         return location
244 }
245
246 func (conn *Conn) AuthorizedKeyCreate(ctx context.Context, options arvados.CreateOptions) (arvados.AuthorizedKey, error) {
247         ep := arvados.EndpointAuthorizedKeyCreate
248         var resp arvados.AuthorizedKey
249         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
250         return resp, err
251 }
252
253 func (conn *Conn) AuthorizedKeyUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.AuthorizedKey, error) {
254         ep := arvados.EndpointAuthorizedKeyUpdate
255         var resp arvados.AuthorizedKey
256         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
257         return resp, err
258 }
259
260 func (conn *Conn) AuthorizedKeyGet(ctx context.Context, options arvados.GetOptions) (arvados.AuthorizedKey, error) {
261         ep := arvados.EndpointAuthorizedKeyGet
262         var resp arvados.AuthorizedKey
263         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
264         return resp, err
265 }
266
267 func (conn *Conn) AuthorizedKeyList(ctx context.Context, options arvados.ListOptions) (arvados.AuthorizedKeyList, error) {
268         ep := arvados.EndpointAuthorizedKeyList
269         var resp arvados.AuthorizedKeyList
270         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
271         return resp, err
272 }
273
274 func (conn *Conn) AuthorizedKeyDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.AuthorizedKey, error) {
275         ep := arvados.EndpointAuthorizedKeyDelete
276         var resp arvados.AuthorizedKey
277         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
278         return resp, err
279 }
280
281 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
282         ep := arvados.EndpointCollectionCreate
283         var resp arvados.Collection
284         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
285         return resp, err
286 }
287
288 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
289         ep := arvados.EndpointCollectionUpdate
290         var resp arvados.Collection
291         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
292         return resp, err
293 }
294
295 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
296         ep := arvados.EndpointCollectionGet
297         var resp arvados.Collection
298         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
299         return resp, err
300 }
301
302 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
303         ep := arvados.EndpointCollectionList
304         var resp arvados.CollectionList
305         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
306         return resp, err
307 }
308
309 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
310         ep := arvados.EndpointCollectionProvenance
311         var resp map[string]interface{}
312         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
313         return resp, err
314 }
315
316 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
317         ep := arvados.EndpointCollectionUsedBy
318         var resp map[string]interface{}
319         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
320         return resp, err
321 }
322
323 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
324         ep := arvados.EndpointCollectionDelete
325         var resp arvados.Collection
326         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
327         return resp, err
328 }
329
330 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
331         ep := arvados.EndpointCollectionTrash
332         var resp arvados.Collection
333         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
334         return resp, err
335 }
336
337 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
338         ep := arvados.EndpointCollectionUntrash
339         var resp arvados.Collection
340         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
341         return resp, err
342 }
343
344 func (conn *Conn) ComputedPermissionList(ctx context.Context, options arvados.ListOptions) (arvados.ComputedPermissionList, error) {
345         ep := arvados.EndpointComputedPermissionList
346         var resp arvados.ComputedPermissionList
347         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
348         return resp, err
349 }
350
351 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
352         ep := arvados.EndpointContainerCreate
353         var resp arvados.Container
354         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
355         return resp, err
356 }
357
358 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
359         ep := arvados.EndpointContainerUpdate
360         var resp arvados.Container
361         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
362         return resp, err
363 }
364
365 func (conn *Conn) ContainerPriorityUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
366         ep := arvados.EndpointContainerPriorityUpdate
367         var resp arvados.Container
368         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
369         return resp, err
370 }
371
372 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
373         ep := arvados.EndpointContainerGet
374         var resp arvados.Container
375         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
376         return resp, err
377 }
378
379 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
380         ep := arvados.EndpointContainerList
381         var resp arvados.ContainerList
382         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
383         return resp, err
384 }
385
386 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
387         ep := arvados.EndpointContainerDelete
388         var resp arvados.Container
389         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
390         return resp, err
391 }
392
393 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
394         ep := arvados.EndpointContainerLock
395         var resp arvados.Container
396         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
397         return resp, err
398 }
399
400 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
401         ep := arvados.EndpointContainerUnlock
402         var resp arvados.Container
403         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
404         return resp, err
405 }
406
407 // ContainerSSH returns a connection to the out-of-band SSH server for
408 // a running container. If the returned error is nil, the caller is
409 // responsible for closing sshconn.Conn.
410 func (conn *Conn) ContainerSSH(ctx context.Context, options arvados.ContainerSSHOptions) (sshconn arvados.ConnectionResponse, err error) {
411         u, err := conn.baseURL.Parse("/" + strings.Replace(arvados.EndpointContainerSSHCompat.Path, "{uuid}", options.UUID, -1))
412         if err != nil {
413                 err = fmt.Errorf("url.Parse: %w", err)
414                 return
415         }
416         return conn.socket(ctx, u, "ssh", url.Values{
417                 "detach_keys":    {options.DetachKeys},
418                 "login_username": {options.LoginUsername},
419                 "no_forward":     {fmt.Sprintf("%v", options.NoForward)},
420         })
421 }
422
423 // ContainerGatewayTunnel returns a connection to a yamux session on
424 // the controller. The caller should connect the returned resp.Conn to
425 // a client-side yamux session.
426 func (conn *Conn) ContainerGatewayTunnel(ctx context.Context, options arvados.ContainerGatewayTunnelOptions) (tunnelconn arvados.ConnectionResponse, err error) {
427         u, err := conn.baseURL.Parse("/" + strings.Replace(arvados.EndpointContainerGatewayTunnelCompat.Path, "{uuid}", options.UUID, -1))
428         if err != nil {
429                 err = fmt.Errorf("url.Parse: %w", err)
430                 return
431         }
432         return conn.socket(ctx, u, "tunnel", url.Values{
433                 "auth_secret": {options.AuthSecret},
434         })
435 }
436
437 // socket sets up a socket using the specified API endpoint and
438 // upgrade header.
439 func (conn *Conn) socket(ctx context.Context, u *url.URL, upgradeHeader string, postform url.Values) (connresp arvados.ConnectionResponse, err error) {
440         addr := conn.baseURL.Host
441         if strings.Index(addr, ":") < 1 || (strings.Contains(addr, "::") && addr[0] != '[') {
442                 // hostname or ::1 or 1::1
443                 addr = net.JoinHostPort(addr, "https")
444         }
445         insecure := false
446         if tlsconf := conn.httpClient.Transport.(*http.Transport).TLSClientConfig; tlsconf != nil && tlsconf.InsecureSkipVerify {
447                 insecure = true
448         }
449         netconn, err := tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: insecure})
450         if err != nil {
451                 return connresp, fmt.Errorf("tls.Dial: %w", err)
452         }
453         defer func() {
454                 if err != nil {
455                         netconn.Close()
456                 }
457         }()
458         bufr := bufio.NewReader(netconn)
459         bufw := bufio.NewWriter(netconn)
460
461         tokens, err := conn.tokenProvider(ctx)
462         if err != nil {
463                 return connresp, err
464         } else if len(tokens) < 1 {
465                 return connresp, httpserver.ErrorWithStatus(errors.New("unauthorized"), http.StatusUnauthorized)
466         }
467         postdata := postform.Encode()
468         bufw.WriteString("POST " + u.String() + " HTTP/1.1\r\n")
469         bufw.WriteString("Authorization: Bearer " + tokens[0] + "\r\n")
470         bufw.WriteString("Host: " + u.Host + "\r\n")
471         bufw.WriteString("Upgrade: " + upgradeHeader + "\r\n")
472         bufw.WriteString("Content-Type: application/x-www-form-urlencoded\r\n")
473         fmt.Fprintf(bufw, "Content-Length: %d\r\n", len(postdata))
474         bufw.WriteString("\r\n")
475         bufw.WriteString(postdata)
476         bufw.Flush()
477         resp, err := http.ReadResponse(bufr, &http.Request{Method: "POST"})
478         if err != nil {
479                 return connresp, fmt.Errorf("http.ReadResponse: %w", err)
480         }
481         defer resp.Body.Close()
482         if resp.StatusCode != http.StatusSwitchingProtocols {
483                 ctxlog.FromContext(ctx).Infof("rpc.Conn.socket: server %s did not switch protocols, got status %s", u.String(), resp.Status)
484                 body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 10000))
485                 var message string
486                 var errDoc httpserver.ErrorResponse
487                 if err := json.Unmarshal(body, &errDoc); err == nil {
488                         message = strings.Join(errDoc.Errors, "; ")
489                 } else {
490                         message = fmt.Sprintf("%q", body)
491                 }
492                 return connresp, httpserver.ErrorWithStatus(fmt.Errorf("server did not provide a tunnel: %s: %s", resp.Status, message), resp.StatusCode)
493         }
494         if strings.ToLower(resp.Header.Get("Upgrade")) != upgradeHeader ||
495                 strings.ToLower(resp.Header.Get("Connection")) != "upgrade" {
496                 return connresp, httpserver.ErrorWithStatus(fmt.Errorf("bad response from server: Upgrade %q Connection %q", resp.Header.Get("Upgrade"), resp.Header.Get("Connection")), http.StatusBadGateway)
497         }
498         connresp.Conn = netconn
499         connresp.Bufrw = &bufio.ReadWriter{Reader: bufr, Writer: bufw}
500         connresp.Header = resp.Header
501         return connresp, nil
502 }
503
504 func (conn *Conn) ContainerRequestCreate(ctx context.Context, options arvados.CreateOptions) (arvados.ContainerRequest, error) {
505         ep := arvados.EndpointContainerRequestCreate
506         var resp arvados.ContainerRequest
507         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
508         return resp, err
509 }
510
511 func (conn *Conn) ContainerRequestUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.ContainerRequest, error) {
512         ep := arvados.EndpointContainerRequestUpdate
513         var resp arvados.ContainerRequest
514         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
515         return resp, err
516 }
517
518 func (conn *Conn) ContainerRequestGet(ctx context.Context, options arvados.GetOptions) (arvados.ContainerRequest, error) {
519         ep := arvados.EndpointContainerRequestGet
520         var resp arvados.ContainerRequest
521         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
522         return resp, err
523 }
524
525 func (conn *Conn) ContainerRequestList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerRequestList, error) {
526         ep := arvados.EndpointContainerRequestList
527         var resp arvados.ContainerRequestList
528         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
529         return resp, err
530 }
531
532 func (conn *Conn) ContainerRequestDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.ContainerRequest, error) {
533         ep := arvados.EndpointContainerRequestDelete
534         var resp arvados.ContainerRequest
535         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
536         return resp, err
537 }
538
539 func (conn *Conn) ContainerRequestContainerStatus(ctx context.Context, options arvados.GetOptions) (arvados.ContainerStatus, error) {
540         ep := arvados.EndpointContainerRequestContainerStatus
541         var resp arvados.ContainerStatus
542         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
543         return resp, err
544 }
545
546 func (conn *Conn) ContainerRequestLog(ctx context.Context, options arvados.ContainerLogOptions) (resp http.Handler, err error) {
547         proxy := &httputil.ReverseProxy{
548                 Transport: conn.httpClient.Transport,
549                 Director: func(r *http.Request) {
550                         u := conn.baseURL
551                         u.Path = r.URL.Path
552                         u.RawQuery = fmt.Sprintf("no_forward=%v", options.NoForward)
553                         r.URL = &u
554                 },
555         }
556         return proxy, nil
557 }
558
559 func (conn *Conn) GroupCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Group, error) {
560         ep := arvados.EndpointGroupCreate
561         var resp arvados.Group
562         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
563         return resp, err
564 }
565
566 func (conn *Conn) GroupUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Group, error) {
567         ep := arvados.EndpointGroupUpdate
568         var resp arvados.Group
569         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
570         return resp, err
571 }
572
573 func (conn *Conn) GroupGet(ctx context.Context, options arvados.GetOptions) (arvados.Group, error) {
574         ep := arvados.EndpointGroupGet
575         var resp arvados.Group
576         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
577         return resp, err
578 }
579
580 func (conn *Conn) GroupList(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
581         ep := arvados.EndpointGroupList
582         var resp arvados.GroupList
583         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
584         return resp, err
585 }
586
587 func (conn *Conn) GroupContents(ctx context.Context, options arvados.GroupContentsOptions) (arvados.ObjectList, error) {
588         ep := arvados.EndpointGroupContents
589         var resp arvados.ObjectList
590         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
591         return resp, err
592 }
593
594 func (conn *Conn) GroupShared(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
595         ep := arvados.EndpointGroupShared
596         var resp arvados.GroupList
597         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
598         return resp, err
599 }
600
601 func (conn *Conn) GroupDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
602         ep := arvados.EndpointGroupDelete
603         var resp arvados.Group
604         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
605         return resp, err
606 }
607
608 func (conn *Conn) GroupTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
609         ep := arvados.EndpointGroupTrash
610         var resp arvados.Group
611         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
612         return resp, err
613 }
614
615 func (conn *Conn) GroupUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Group, error) {
616         ep := arvados.EndpointGroupUntrash
617         var resp arvados.Group
618         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
619         return resp, err
620 }
621
622 func (conn *Conn) LinkCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Link, error) {
623         ep := arvados.EndpointLinkCreate
624         var resp arvados.Link
625         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
626         return resp, err
627 }
628
629 func (conn *Conn) LinkUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Link, error) {
630         ep := arvados.EndpointLinkUpdate
631         var resp arvados.Link
632         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
633         return resp, err
634 }
635
636 func (conn *Conn) LinkGet(ctx context.Context, options arvados.GetOptions) (arvados.Link, error) {
637         ep := arvados.EndpointLinkGet
638         var resp arvados.Link
639         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
640         return resp, err
641 }
642
643 func (conn *Conn) LinkList(ctx context.Context, options arvados.ListOptions) (arvados.LinkList, error) {
644         ep := arvados.EndpointLinkList
645         var resp arvados.LinkList
646         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
647         return resp, err
648 }
649
650 func (conn *Conn) LinkDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Link, error) {
651         ep := arvados.EndpointLinkDelete
652         var resp arvados.Link
653         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
654         return resp, err
655 }
656
657 func (conn *Conn) LogCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Log, error) {
658         ep := arvados.EndpointLogCreate
659         var resp arvados.Log
660         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
661         return resp, err
662 }
663
664 func (conn *Conn) LogUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Log, error) {
665         ep := arvados.EndpointLogUpdate
666         var resp arvados.Log
667         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
668         return resp, err
669 }
670
671 func (conn *Conn) LogGet(ctx context.Context, options arvados.GetOptions) (arvados.Log, error) {
672         ep := arvados.EndpointLogGet
673         var resp arvados.Log
674         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
675         return resp, err
676 }
677
678 func (conn *Conn) LogList(ctx context.Context, options arvados.ListOptions) (arvados.LogList, error) {
679         ep := arvados.EndpointLogList
680         var resp arvados.LogList
681         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
682         return resp, err
683 }
684
685 func (conn *Conn) LogDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Log, error) {
686         ep := arvados.EndpointLogDelete
687         var resp arvados.Log
688         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
689         return resp, err
690 }
691
692 func (conn *Conn) SysTrashSweep(ctx context.Context, options struct{}) (struct{}, error) {
693         ep := arvados.EndpointSysTrashSweep
694         var resp struct{}
695         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
696         return resp, err
697 }
698
699 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
700         ep := arvados.EndpointUserCreate
701         var resp arvados.User
702         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
703         return resp, err
704 }
705 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
706         ep := arvados.EndpointUserUpdate
707         var resp arvados.User
708         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
709         return resp, err
710 }
711 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
712         ep := arvados.EndpointUserMerge
713         var resp arvados.User
714         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
715         return resp, err
716 }
717 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
718         ep := arvados.EndpointUserActivate
719         var resp arvados.User
720         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
721         return resp, err
722 }
723 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
724         ep := arvados.EndpointUserSetup
725         var resp map[string]interface{}
726         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
727         return resp, err
728 }
729 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
730         ep := arvados.EndpointUserUnsetup
731         var resp arvados.User
732         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
733         return resp, err
734 }
735 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
736         ep := arvados.EndpointUserGet
737         var resp arvados.User
738         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
739         return resp, err
740 }
741 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
742         ep := arvados.EndpointUserGetCurrent
743         var resp arvados.User
744         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
745         return resp, err
746 }
747 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
748         ep := arvados.EndpointUserGetSystem
749         var resp arvados.User
750         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
751         return resp, err
752 }
753 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
754         ep := arvados.EndpointUserList
755         var resp arvados.UserList
756         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
757         return resp, err
758 }
759 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
760         ep := arvados.EndpointUserDelete
761         var resp arvados.User
762         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
763         return resp, err
764 }
765
766 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
767         ep := arvados.EndpointAPIClientAuthorizationCurrent
768         var resp arvados.APIClientAuthorization
769         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
770         return resp, err
771 }
772 func (conn *Conn) APIClientAuthorizationCreate(ctx context.Context, options arvados.CreateOptions) (arvados.APIClientAuthorization, error) {
773         ep := arvados.EndpointAPIClientAuthorizationCreate
774         var resp arvados.APIClientAuthorization
775         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
776         return resp, err
777 }
778 func (conn *Conn) APIClientAuthorizationUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.APIClientAuthorization, error) {
779         ep := arvados.EndpointAPIClientAuthorizationUpdate
780         var resp arvados.APIClientAuthorization
781         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
782         return resp, err
783 }
784 func (conn *Conn) APIClientAuthorizationDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.APIClientAuthorization, error) {
785         ep := arvados.EndpointAPIClientAuthorizationDelete
786         var resp arvados.APIClientAuthorization
787         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
788         return resp, err
789 }
790 func (conn *Conn) APIClientAuthorizationList(ctx context.Context, options arvados.ListOptions) (arvados.APIClientAuthorizationList, error) {
791         ep := arvados.EndpointAPIClientAuthorizationList
792         var resp arvados.APIClientAuthorizationList
793         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
794         return resp, err
795 }
796 func (conn *Conn) APIClientAuthorizationGet(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
797         ep := arvados.EndpointAPIClientAuthorizationGet
798         var resp arvados.APIClientAuthorization
799         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
800         return resp, err
801 }
802
803 type UserSessionAuthInfo struct {
804         UserUUID        string    `json:"user_uuid"`
805         Email           string    `json:"email"`
806         AlternateEmails []string  `json:"alternate_emails"`
807         FirstName       string    `json:"first_name"`
808         LastName        string    `json:"last_name"`
809         Username        string    `json:"username"`
810         ExpiresAt       time.Time `json:"expires_at"`
811 }
812
813 type UserSessionCreateOptions struct {
814         AuthInfo UserSessionAuthInfo `json:"auth_info"`
815         ReturnTo string              `json:"return_to"`
816 }
817
818 func (conn *Conn) UserSessionCreate(ctx context.Context, options UserSessionCreateOptions) (arvados.LoginResponse, error) {
819         ep := arvados.APIEndpoint{Method: "POST", Path: "auth/controller/callback"}
820         var resp arvados.LoginResponse
821         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
822         return resp, err
823 }
824
825 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
826         ep := arvados.EndpointUserBatchUpdate
827         var resp arvados.UserList
828         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
829         return resp, err
830 }
831
832 func (conn *Conn) UserAuthenticate(ctx context.Context, options arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
833         ep := arvados.EndpointUserAuthenticate
834         var resp arvados.APIClientAuthorization
835         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
836         return resp, err
837 }
838
839 // httpStatusError is an error with an HTTP status code that can be
840 // propagated by lib/controller/router, etc.
841 type httpStatusError interface {
842         error
843         HTTPStatus() int
844 }
845
846 // wrappedHTTPStatusError is used to augment/replace an error message
847 // while preserving the HTTP status code indicated by the original
848 // error.
849 type wrappedHTTPStatusError struct {
850         httpStatusError
851         message string
852 }
853
854 func wrapHTTPStatusError(err httpStatusError, message string) httpStatusError {
855         return wrappedHTTPStatusError{err, message}
856 }
857
858 func (err wrappedHTTPStatusError) Error() string {
859         return err.message
860 }