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