1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 "git.curoverse.com/arvados.git/sdk/go/auth"
22 "github.com/jmcvetta/randutil"
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 collectionRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "collections", "4zz18"))
30 var collectionByPDHRe = regexp.MustCompile(`^/arvados/v1/collections/([0-9a-fA-F]{32}\+[0-9]+)+$`)
32 func (h *Handler) remoteClusterRequest(remoteID string, req *http.Request) (*http.Response, context.CancelFunc, error) {
33 remote, ok := h.Cluster.RemoteClusters[remoteID]
35 return nil, nil, HTTPError{fmt.Sprintf("no proxy available for cluster %v", remoteID), http.StatusNotFound}
37 scheme := remote.Scheme
41 saltedReq, err := h.saltAuthToken(req, remoteID)
48 Path: saltedReq.URL.Path,
49 RawPath: saltedReq.URL.RawPath,
50 RawQuery: saltedReq.URL.RawQuery,
52 client := h.secureClient
54 client = h.insecureClient
56 return h.proxy.Do(saltedReq, urlOut, client)
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" {
66 if req.ContentLength > 0 {
67 cl = req.ContentLength
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))
75 err := req.ParseForm()
80 if req.Body != nil && postBody != nil {
81 req.Body = ioutil.NopCloser(postBody)
86 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
87 mux := http.NewServeMux()
89 wfHandler := &genericFederatedRequestHandler{next, h, wfRe, nil}
90 containersHandler := &genericFederatedRequestHandler{next, h, containersRe, nil}
91 containerRequestsHandler := &genericFederatedRequestHandler{next, h, containerRequestsRe,
92 []federatedRequestDelegate{remoteContainerRequestCreate}}
94 mux.Handle("/arvados/v1/workflows", wfHandler)
95 mux.Handle("/arvados/v1/workflows/", wfHandler)
96 mux.Handle("/arvados/v1/containers", containersHandler)
97 mux.Handle("/arvados/v1/containers/", containersHandler)
98 mux.Handle("/arvados/v1/container_requests", containerRequestsHandler)
99 mux.Handle("/arvados/v1/container_requests/", containerRequestsHandler)
100 mux.Handle("/arvados/v1/collections", next)
101 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
102 mux.Handle("/", next)
104 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
105 parts := strings.Split(req.Header.Get("Authorization"), "/")
106 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
109 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
110 // The token is already salted, or this is a
111 // request from another instance of
112 // arvados-controller. In either case, we
113 // don't want to proxy this query, so just
114 // continue down the instance handler stack.
115 next.ServeHTTP(w, req)
119 mux.ServeHTTP(w, req)
125 type CurrentUser struct {
126 Authorization arvados.APIClientAuthorization
130 // validateAPItoken extracts the token from the provided http request,
131 // checks it again api_client_authorizations table in the database,
132 // and fills in the token scope and user UUID. Does not handle remote
133 // tokens unless they are already in the database and not expired.
134 func (h *Handler) validateAPItoken(req *http.Request, token string) (*CurrentUser, error) {
135 user := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: token}}
142 if strings.HasPrefix(token, "v2/") {
143 sp := strings.Split(token, "/")
147 user.Authorization.APIToken = token
149 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)
153 if uuid != "" && user.Authorization.UUID != uuid {
154 return nil, fmt.Errorf("UUID embedded in v2 token did not match record")
156 err = json.Unmarshal([]byte(scopes), &user.Authorization.Scopes)
163 func (h *Handler) createAPItoken(req *http.Request, userUUID string, scopes []string) (*arvados.APIClientAuthorization, error) {
168 rd, err := randutil.String(15, "abcdefghijklmnopqrstuvwxyz0123456789")
172 uuid := fmt.Sprintf("%v-gj3su-%v", h.Cluster.ClusterID, rd)
173 token, err := randutil.String(50, "abcdefghijklmnopqrstuvwxyz0123456789")
177 if len(scopes) == 0 {
178 scopes = append(scopes, "all")
180 scopesjson, err := json.Marshal(scopes)
184 _, err = db.ExecContext(req.Context(),
185 `INSERT INTO api_client_authorizations
186 (uuid, api_token, expires_at, scopes,
188 api_client_id, created_at, updated_at)
189 VALUES ($1, $2, CURRENT_TIMESTAMP + INTERVAL '2 weeks', $3,
190 (SELECT id FROM users WHERE users.uuid=$4 LIMIT 1),
191 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`,
192 uuid, token, string(scopesjson), userUUID)
198 return &arvados.APIClientAuthorization{
205 // Extract the auth token supplied in req, and replace it with a
206 // salted token for the remote cluster.
207 func (h *Handler) saltAuthToken(req *http.Request, remote string) (updatedReq *http.Request, err error) {
208 updatedReq = (&http.Request{
213 ContentLength: req.ContentLength,
215 }).WithContext(req.Context())
217 creds := auth.NewCredentials()
218 creds.LoadTokensFromHTTPRequest(updatedReq)
219 if len(creds.Tokens) == 0 && updatedReq.Header.Get("Content-Type") == "application/x-www-form-encoded" {
220 // Override ParseForm's 10MiB limit by ensuring
221 // req.Body is a *http.maxBytesReader.
222 updatedReq.Body = http.MaxBytesReader(nil, updatedReq.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
223 if err := creds.LoadTokensFromHTTPRequestBody(updatedReq); err != nil {
226 // Replace req.Body with a buffer that re-encodes the
227 // form without api_token, in case we end up
228 // forwarding the request.
229 if updatedReq.PostForm != nil {
230 updatedReq.PostForm.Del("api_token")
232 updatedReq.Body = ioutil.NopCloser(bytes.NewBufferString(updatedReq.PostForm.Encode()))
234 if len(creds.Tokens) == 0 {
235 return updatedReq, nil
238 token, err := auth.SaltToken(creds.Tokens[0], remote)
240 if err == auth.ErrObsoleteToken {
241 // If the token exists in our own database, salt it
242 // for the remote. Otherwise, assume it was issued by
243 // the remote, and pass it through unmodified.
244 currentUser, err := h.validateAPItoken(req, creds.Tokens[0])
245 if err == sql.ErrNoRows {
246 // Not ours; pass through unmodified.
247 token = creds.Tokens[0]
248 } else if err != nil {
251 // Found; make V2 version and salt it.
252 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
257 } else if err != nil {
260 updatedReq.Header = http.Header{}
261 for k, v := range req.Header {
262 if k != "Authorization" {
263 updatedReq.Header[k] = v
266 updatedReq.Header.Set("Authorization", "Bearer "+token)
268 // Remove api_token=... from the the query string, in case we
269 // end up forwarding the request.
270 if values, err := url.ParseQuery(updatedReq.URL.RawQuery); err != nil {
272 } else if _, ok := values["api_token"]; ok {
273 delete(values, "api_token")
274 updatedReq.URL = &url.URL{
275 Scheme: req.URL.Scheme,
278 RawPath: req.URL.RawPath,
279 RawQuery: values.Encode(),
282 return updatedReq, nil