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