Merge branch '14198-fed-collection-list' refs #14198
[arvados.git] / lib / controller / federation.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "bytes"
9         "database/sql"
10         "encoding/json"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "net/http"
15         "net/url"
16         "regexp"
17         "strings"
18
19         "git.curoverse.com/arvados.git/sdk/go/arvados"
20         "git.curoverse.com/arvados.git/sdk/go/auth"
21         "github.com/jmcvetta/randutil"
22 )
23
24 var pathPattern = `^/arvados/v1/%s(/([0-9a-z]{5})-%s-[0-9a-z]{15})?(.*)$`
25 var wfRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "workflows", "7fd4e"))
26 var containersRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "containers", "dz642"))
27 var containerRequestsRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "container_requests", "xvhdp"))
28 var collectionsRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "collections", "4zz18"))
29 var collectionsByPDHRe = regexp.MustCompile(`^/arvados/v1/collections/([0-9a-fA-F]{32}\+[0-9]+)+$`)
30 var linksRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "links", "o0j2j"))
31
32 func (h *Handler) remoteClusterRequest(remoteID string, req *http.Request) (*http.Response, error) {
33         remote, ok := h.Cluster.RemoteClusters[remoteID]
34         if !ok {
35                 return nil, HTTPError{fmt.Sprintf("no proxy available for cluster %v", remoteID), http.StatusNotFound}
36         }
37         scheme := remote.Scheme
38         if scheme == "" {
39                 scheme = "https"
40         }
41         saltedReq, err := h.saltAuthToken(req, remoteID)
42         if err != nil {
43                 return nil, err
44         }
45         urlOut := &url.URL{
46                 Scheme:   scheme,
47                 Host:     remote.Host,
48                 Path:     saltedReq.URL.Path,
49                 RawPath:  saltedReq.URL.RawPath,
50                 RawQuery: saltedReq.URL.RawQuery,
51         }
52         client := h.secureClient
53         if remote.Insecure {
54                 client = h.insecureClient
55         }
56         return h.proxy.Do(saltedReq, urlOut, client)
57 }
58
59 // Buffer request body, parse form parameters in request, and then
60 // replace original body with the buffer so it can be re-read by
61 // downstream proxy steps.
62 func loadParamsFromForm(req *http.Request) error {
63         var postBody *bytes.Buffer
64         if req.Body != nil && req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
65                 var cl int64
66                 if req.ContentLength > 0 {
67                         cl = req.ContentLength
68                 }
69                 postBody = bytes.NewBuffer(make([]byte, 0, cl))
70                 originalBody := req.Body
71                 defer originalBody.Close()
72                 req.Body = ioutil.NopCloser(io.TeeReader(req.Body, postBody))
73         }
74
75         err := req.ParseForm()
76         if err != nil {
77                 return err
78         }
79
80         if req.Body != nil && postBody != nil {
81                 req.Body = ioutil.NopCloser(postBody)
82         }
83         return nil
84 }
85
86 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
87         mux := http.NewServeMux()
88
89         wfHandler := &genericFederatedRequestHandler{next, h, wfRe, nil}
90         containersHandler := &genericFederatedRequestHandler{next, h, containersRe, nil}
91         containerRequestsHandler := &genericFederatedRequestHandler{next, h, containerRequestsRe,
92                 []federatedRequestDelegate{remoteContainerRequestCreate}}
93         collectionsRequestsHandler := &genericFederatedRequestHandler{next, h, collectionsRe,
94                 []federatedRequestDelegate{fetchRemoteCollectionByUUID, fetchRemoteCollectionByPDH}}
95         linksRequestsHandler := &genericFederatedRequestHandler{next, h, linksRe, nil}
96
97         mux.Handle("/arvados/v1/workflows", wfHandler)
98         mux.Handle("/arvados/v1/workflows/", wfHandler)
99         mux.Handle("/arvados/v1/containers", containersHandler)
100         mux.Handle("/arvados/v1/containers/", containersHandler)
101         mux.Handle("/arvados/v1/container_requests", containerRequestsHandler)
102         mux.Handle("/arvados/v1/container_requests/", containerRequestsHandler)
103         mux.Handle("/arvados/v1/collections", collectionsRequestsHandler)
104         mux.Handle("/arvados/v1/collections/", collectionsRequestsHandler)
105         mux.Handle("/arvados/v1/links", linksRequestsHandler)
106         mux.Handle("/arvados/v1/links/", linksRequestsHandler)
107         mux.Handle("/", next)
108
109         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
110                 parts := strings.Split(req.Header.Get("Authorization"), "/")
111                 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
112
113                 if alreadySalted ||
114                         strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
115                         // The token is already salted, or this is a
116                         // request from another instance of
117                         // arvados-controller.  In either case, we
118                         // don't want to proxy this query, so just
119                         // continue down the instance handler stack.
120                         next.ServeHTTP(w, req)
121                         return
122                 }
123
124                 mux.ServeHTTP(w, req)
125         })
126
127         return mux
128 }
129
130 type CurrentUser struct {
131         Authorization arvados.APIClientAuthorization
132         UUID          string
133 }
134
135 // validateAPItoken extracts the token from the provided http request,
136 // checks it again api_client_authorizations table in the database,
137 // and fills in the token scope and user UUID.  Does not handle remote
138 // tokens unless they are already in the database and not expired.
139 func (h *Handler) validateAPItoken(req *http.Request, token string) (*CurrentUser, error) {
140         user := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: token}}
141         db, err := h.db(req)
142         if err != nil {
143                 return nil, err
144         }
145
146         var uuid string
147         if strings.HasPrefix(token, "v2/") {
148                 sp := strings.Split(token, "/")
149                 uuid = sp[1]
150                 token = sp[2]
151         }
152         user.Authorization.APIToken = token
153         var scopes string
154         err = db.QueryRowContext(req.Context(), `SELECT api_client_authorizations.uuid, api_client_authorizations.scopes, users.uuid FROM api_client_authorizations JOIN users on api_client_authorizations.user_id=users.id WHERE api_token=$1 AND (expires_at IS NULL OR expires_at > current_timestamp) LIMIT 1`, token).Scan(&user.Authorization.UUID, &scopes, &user.UUID)
155         if err != nil {
156                 return nil, err
157         }
158         if uuid != "" && user.Authorization.UUID != uuid {
159                 return nil, fmt.Errorf("UUID embedded in v2 token did not match record")
160         }
161         err = json.Unmarshal([]byte(scopes), &user.Authorization.Scopes)
162         if err != nil {
163                 return nil, err
164         }
165         return &user, nil
166 }
167
168 func (h *Handler) createAPItoken(req *http.Request, userUUID string, scopes []string) (*arvados.APIClientAuthorization, error) {
169         db, err := h.db(req)
170         if err != nil {
171                 return nil, err
172         }
173         rd, err := randutil.String(15, "abcdefghijklmnopqrstuvwxyz0123456789")
174         if err != nil {
175                 return nil, err
176         }
177         uuid := fmt.Sprintf("%v-gj3su-%v", h.Cluster.ClusterID, rd)
178         token, err := randutil.String(50, "abcdefghijklmnopqrstuvwxyz0123456789")
179         if err != nil {
180                 return nil, err
181         }
182         if len(scopes) == 0 {
183                 scopes = append(scopes, "all")
184         }
185         scopesjson, err := json.Marshal(scopes)
186         if err != nil {
187                 return nil, err
188         }
189         _, err = db.ExecContext(req.Context(),
190                 `INSERT INTO api_client_authorizations
191 (uuid, api_token, expires_at, scopes,
192 user_id,
193 api_client_id, created_at, updated_at)
194 VALUES ($1, $2, CURRENT_TIMESTAMP + INTERVAL '2 weeks', $3,
195 (SELECT id FROM users WHERE users.uuid=$4 LIMIT 1),
196 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`,
197                 uuid, token, string(scopesjson), userUUID)
198
199         if err != nil {
200                 return nil, err
201         }
202
203         return &arvados.APIClientAuthorization{
204                 UUID:      uuid,
205                 APIToken:  token,
206                 ExpiresAt: "",
207                 Scopes:    scopes}, nil
208 }
209
210 // Extract the auth token supplied in req, and replace it with a
211 // salted token for the remote cluster.
212 func (h *Handler) saltAuthToken(req *http.Request, remote string) (updatedReq *http.Request, err error) {
213         updatedReq = (&http.Request{
214                 Method:        req.Method,
215                 URL:           req.URL,
216                 Header:        req.Header,
217                 Body:          req.Body,
218                 ContentLength: req.ContentLength,
219                 Host:          req.Host,
220         }).WithContext(req.Context())
221
222         creds := auth.NewCredentials()
223         creds.LoadTokensFromHTTPRequest(updatedReq)
224         if len(creds.Tokens) == 0 && updatedReq.Header.Get("Content-Type") == "application/x-www-form-encoded" {
225                 // Override ParseForm's 10MiB limit by ensuring
226                 // req.Body is a *http.maxBytesReader.
227                 updatedReq.Body = http.MaxBytesReader(nil, updatedReq.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
228                 if err := creds.LoadTokensFromHTTPRequestBody(updatedReq); err != nil {
229                         return nil, err
230                 }
231                 // Replace req.Body with a buffer that re-encodes the
232                 // form without api_token, in case we end up
233                 // forwarding the request.
234                 if updatedReq.PostForm != nil {
235                         updatedReq.PostForm.Del("api_token")
236                 }
237                 updatedReq.Body = ioutil.NopCloser(bytes.NewBufferString(updatedReq.PostForm.Encode()))
238         }
239         if len(creds.Tokens) == 0 {
240                 return updatedReq, nil
241         }
242
243         token, err := auth.SaltToken(creds.Tokens[0], remote)
244
245         if err == auth.ErrObsoleteToken {
246                 // If the token exists in our own database, salt it
247                 // for the remote. Otherwise, assume it was issued by
248                 // the remote, and pass it through unmodified.
249                 currentUser, err := h.validateAPItoken(req, creds.Tokens[0])
250                 if err == sql.ErrNoRows {
251                         // Not ours; pass through unmodified.
252                         token = creds.Tokens[0]
253                 } else if err != nil {
254                         return nil, err
255                 } else {
256                         // Found; make V2 version and salt it.
257                         token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
258                         if err != nil {
259                                 return nil, err
260                         }
261                 }
262         } else if err != nil {
263                 return nil, err
264         }
265         updatedReq.Header = http.Header{}
266         for k, v := range req.Header {
267                 if k != "Authorization" {
268                         updatedReq.Header[k] = v
269                 }
270         }
271         updatedReq.Header.Set("Authorization", "Bearer "+token)
272
273         // Remove api_token=... from the the query string, in case we
274         // end up forwarding the request.
275         if values, err := url.ParseQuery(updatedReq.URL.RawQuery); err != nil {
276                 return nil, err
277         } else if _, ok := values["api_token"]; ok {
278                 delete(values, "api_token")
279                 updatedReq.URL = &url.URL{
280                         Scheme:   req.URL.Scheme,
281                         Host:     req.URL.Host,
282                         Path:     req.URL.Path,
283                         RawPath:  req.URL.RawPath,
284                         RawQuery: values.Encode(),
285                 }
286         }
287         return updatedReq, nil
288 }