1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
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"))
34 func (h *Handler) remoteClusterRequest(remoteID string, req *http.Request) (*http.Response, error) {
35 remote, ok := h.Cluster.RemoteClusters[remoteID]
37 return nil, HTTPError{fmt.Sprintf("no proxy available for cluster %v", remoteID), http.StatusNotFound}
39 scheme := remote.Scheme
43 saltedReq, err := h.saltAuthToken(req, remoteID)
50 Path: saltedReq.URL.Path,
51 RawPath: saltedReq.URL.RawPath,
52 RawQuery: saltedReq.URL.RawQuery,
54 client := h.secureClient
56 client = h.insecureClient
58 return h.proxy.Do(saltedReq, urlOut, client)
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 {
70 } else if ct == "application/x-www-form-urlencoded" && req.Body != nil {
72 if req.ContentLength > 0 {
73 cl = req.ContentLength
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))
81 err := req.ParseForm()
86 if req.Body != nil && postBody != nil {
87 req.Body = ioutil.NopCloser(postBody)
92 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
93 mux := http.NewServeMux()
95 wfHandler := &genericFederatedRequestHandler{next, h, wfRe, nil}
96 containersHandler := &genericFederatedRequestHandler{next, h, containersRe, nil}
97 containerRequestsHandler := &genericFederatedRequestHandler{next, h, containerRequestsRe,
98 []federatedRequestDelegate{remoteContainerRequestCreate}}
99 collectionsRequestsHandler := &genericFederatedRequestHandler{next, h, collectionsRe,
100 []federatedRequestDelegate{fetchRemoteCollectionByUUID, fetchRemoteCollectionByPDH}}
101 linksRequestsHandler := &genericFederatedRequestHandler{next, h, linksRe, nil}
103 mux.Handle("/arvados/v1/workflows", wfHandler)
104 mux.Handle("/arvados/v1/workflows/", wfHandler)
105 mux.Handle("/arvados/v1/containers", containersHandler)
106 mux.Handle("/arvados/v1/containers/", containersHandler)
107 mux.Handle("/arvados/v1/container_requests", containerRequestsHandler)
108 mux.Handle("/arvados/v1/container_requests/", containerRequestsHandler)
109 mux.Handle("/arvados/v1/collections", collectionsRequestsHandler)
110 mux.Handle("/arvados/v1/collections/", collectionsRequestsHandler)
111 mux.Handle("/arvados/v1/links", linksRequestsHandler)
112 mux.Handle("/arvados/v1/links/", linksRequestsHandler)
113 mux.Handle("/", next)
115 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
116 parts := strings.Split(req.Header.Get("Authorization"), "/")
117 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
120 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
121 // The token is already salted, or this is a
122 // request from another instance of
123 // arvados-controller. In either case, we
124 // don't want to proxy this query, so just
125 // continue down the instance handler stack.
126 next.ServeHTTP(w, req)
130 mux.ServeHTTP(w, req)
136 type CurrentUser struct {
137 Authorization arvados.APIClientAuthorization
141 // validateAPItoken extracts the token from the provided http request,
142 // checks it again api_client_authorizations table in the database,
143 // and fills in the token scope and user UUID. Does not handle remote
144 // tokens unless they are already in the database and not expired.
146 // Return values are:
148 // nil, false, non-nil -- if there was an internal error
150 // nil, false, nil -- if the token is invalid
152 // non-nil, true, nil -- if the token is valid
153 func (h *Handler) validateAPItoken(req *http.Request, token string) (*CurrentUser, bool, error) {
154 user := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: token}}
155 db, err := h.db(req.Context())
157 ctxlog.FromContext(req.Context()).WithError(err).Debugf("validateAPItoken(%s): database error", token)
158 return nil, false, err
162 if strings.HasPrefix(token, "v2/") {
163 sp := strings.Split(token, "/")
167 user.Authorization.APIToken = token
169 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)
170 if err == sql.ErrNoRows {
171 ctxlog.FromContext(req.Context()).Debugf("validateAPItoken(%s): not found in database", token)
172 return nil, false, nil
173 } else if err != nil {
174 ctxlog.FromContext(req.Context()).WithError(err).Debugf("validateAPItoken(%s): database error", token)
175 return nil, false, err
177 if uuid != "" && user.Authorization.UUID != uuid {
178 // secret part matches, but UUID doesn't -- somewhat surprising
179 ctxlog.FromContext(req.Context()).Debugf("validateAPItoken(%s): secret part found, but with different UUID: %s", token, user.Authorization.UUID)
180 return nil, false, nil
182 err = json.Unmarshal([]byte(scopes), &user.Authorization.Scopes)
184 ctxlog.FromContext(req.Context()).WithError(err).Debugf("validateAPItoken(%s): error parsing scopes from db", token)
185 return nil, false, err
187 ctxlog.FromContext(req.Context()).Debugf("validateAPItoken(%s): ok", token)
188 return &user, true, nil
191 func (h *Handler) createAPItoken(req *http.Request, userUUID string, scopes []string) (*arvados.APIClientAuthorization, error) {
192 db, err := h.db(req.Context())
196 rd, err := randutil.String(15, "abcdefghijklmnopqrstuvwxyz0123456789")
200 uuid := fmt.Sprintf("%v-gj3su-%v", h.Cluster.ClusterID, rd)
201 token, err := randutil.String(50, "abcdefghijklmnopqrstuvwxyz0123456789")
205 if len(scopes) == 0 {
206 scopes = append(scopes, "all")
208 scopesjson, err := json.Marshal(scopes)
212 _, err = db.ExecContext(req.Context(),
213 `INSERT INTO api_client_authorizations
214 (uuid, api_token, expires_at, scopes,
216 api_client_id, created_at, updated_at)
217 VALUES ($1, $2, CURRENT_TIMESTAMP AT TIME ZONE 'UTC' + INTERVAL '2 weeks', $3,
218 (SELECT id FROM users WHERE users.uuid=$4 LIMIT 1),
219 0, CURRENT_TIMESTAMP AT TIME ZONE 'UTC', CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`,
220 uuid, token, string(scopesjson), userUUID)
226 return &arvados.APIClientAuthorization{
233 // Extract the auth token supplied in req, and replace it with a
234 // salted token for the remote cluster.
235 func (h *Handler) saltAuthToken(req *http.Request, remote string) (updatedReq *http.Request, err error) {
236 updatedReq = (&http.Request{
241 ContentLength: req.ContentLength,
243 }).WithContext(req.Context())
245 creds := auth.NewCredentials()
246 creds.LoadTokensFromHTTPRequest(updatedReq)
247 if len(creds.Tokens) == 0 && updatedReq.Header.Get("Content-Type") == "application/x-www-form-encoded" {
248 // Override ParseForm's 10MiB limit by ensuring
249 // req.Body is a *http.maxBytesReader.
250 updatedReq.Body = http.MaxBytesReader(nil, updatedReq.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
251 if err := creds.LoadTokensFromHTTPRequestBody(updatedReq); err != nil {
254 // Replace req.Body with a buffer that re-encodes the
255 // form without api_token, in case we end up
256 // forwarding the request.
257 if updatedReq.PostForm != nil {
258 updatedReq.PostForm.Del("api_token")
260 updatedReq.Body = ioutil.NopCloser(bytes.NewBufferString(updatedReq.PostForm.Encode()))
262 if len(creds.Tokens) == 0 {
263 return updatedReq, nil
266 ctxlog.FromContext(req.Context()).Infof("saltAuthToken: cluster %s token %s remote %s", h.Cluster.ClusterID, creds.Tokens[0], remote)
267 token, err := auth.SaltToken(creds.Tokens[0], remote)
269 if err == auth.ErrObsoleteToken {
270 // If the token exists in our own database for our own
271 // user, salt it for the remote. Otherwise, assume it
272 // was issued by the remote, and pass it through
274 currentUser, ok, err := h.validateAPItoken(req, creds.Tokens[0])
277 } else if !ok || strings.HasPrefix(currentUser.UUID, remote) {
278 // Unknown, or cached + belongs to remote;
279 // pass through unmodified.
280 token = creds.Tokens[0]
282 // Found; make V2 version and salt it.
283 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
288 } else if err != nil {
291 updatedReq.Header = http.Header{}
292 for k, v := range req.Header {
293 if k != "Authorization" {
294 updatedReq.Header[k] = v
297 updatedReq.Header.Set("Authorization", "Bearer "+token)
299 // Remove api_token=... from the query string, in case we
300 // end up forwarding the request.
301 if values, err := url.ParseQuery(updatedReq.URL.RawQuery); err != nil {
303 } else if _, ok := values["api_token"]; ok {
304 delete(values, "api_token")
305 updatedReq.URL = &url.URL{
306 Scheme: req.URL.Scheme,
309 RawPath: req.URL.RawPath,
310 RawQuery: values.Encode(),
313 return updatedReq, nil