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