13146: Projects shared with me WIP
[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         "io/ioutil"
11         "net/http"
12         "net/url"
13         "regexp"
14
15         "git.curoverse.com/arvados.git/sdk/go/arvados"
16         "git.curoverse.com/arvados.git/sdk/go/auth"
17         "git.curoverse.com/arvados.git/sdk/go/httpserver"
18 )
19
20 var wfRe = regexp.MustCompile(`^/arvados/v1/workflows/([0-9a-z]{5})-[^/]+$`)
21
22 func (h *Handler) proxyRemoteCluster(w http.ResponseWriter, req *http.Request, next http.Handler) {
23         m := wfRe.FindStringSubmatch(req.URL.Path)
24         if len(m) < 2 || m[1] == h.Cluster.ClusterID {
25                 next.ServeHTTP(w, req)
26                 return
27         }
28         remoteID := m[1]
29         remote, ok := h.Cluster.RemoteClusters[remoteID]
30         if !ok {
31                 httpserver.Error(w, "no proxy available for cluster "+remoteID, http.StatusNotFound)
32                 return
33         }
34         scheme := remote.Scheme
35         if scheme == "" {
36                 scheme = "https"
37         }
38         err := h.saltAuthToken(req, remoteID)
39         if err != nil {
40                 httpserver.Error(w, err.Error(), http.StatusBadRequest)
41                 return
42         }
43         urlOut := &url.URL{
44                 Scheme:   scheme,
45                 Host:     remote.Host,
46                 Path:     req.URL.Path,
47                 RawPath:  req.URL.RawPath,
48                 RawQuery: req.URL.RawQuery,
49         }
50         client := h.secureClient
51         if remote.Insecure {
52                 client = h.insecureClient
53         }
54         h.proxy.Do(w, req, urlOut, client)
55 }
56
57 type CurrentUser struct {
58         Authorization arvados.APIClientAuthorization
59         UUID          string
60 }
61
62 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
63         db, err := h.db(req)
64         if err != nil {
65                 return err
66         }
67         return db.QueryRowContext(req.Context(), `SELECT api_client_authorizations.uuid, 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`, user.Authorization.APIToken).Scan(&user.Authorization.UUID, &user.UUID)
68 }
69
70 // Extract the auth token supplied in req, and replace it with a
71 // salted token for the remote cluster.
72 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
73         creds := auth.NewCredentials()
74         creds.LoadTokensFromHTTPRequest(req)
75         if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
76                 // Override ParseForm's 10MiB limit by ensuring
77                 // req.Body is a *http.maxBytesReader.
78                 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
79                 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
80                         return err
81                 }
82                 // Replace req.Body with a buffer that re-encodes the
83                 // form without api_token, in case we end up
84                 // forwarding the request.
85                 if req.PostForm != nil {
86                         req.PostForm.Del("api_token")
87                 }
88                 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
89         }
90         if len(creds.Tokens) == 0 {
91                 return nil
92         }
93         token, err := auth.SaltToken(creds.Tokens[0], remote)
94         if err == auth.ErrObsoleteToken {
95                 // If the token exists in our own database, salt it
96                 // for the remote. Otherwise, assume it was issued by
97                 // the remote, and pass it through unmodified.
98                 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
99                 err = h.validateAPItoken(req, &currentUser)
100                 if err == sql.ErrNoRows {
101                         // Not ours; pass through unmodified.
102                         token = currentUser.Authorization.APIToken
103                 } else if err != nil {
104                         return err
105                 } else {
106                         // Found; make V2 version and salt it.
107                         token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
108                         if err != nil {
109                                 return err
110                         }
111                 }
112         } else if err != nil {
113                 return err
114         }
115         req.Header.Set("Authorization", "Bearer "+token)
116
117         // Remove api_token=... from the the query string, in case we
118         // end up forwarding the request.
119         if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
120                 return err
121         } else if _, ok := values["api_token"]; ok {
122                 delete(values, "api_token")
123                 req.URL.RawQuery = values.Encode()
124         }
125         return nil
126 }