Documentation: reflect the current state of anonymous token generation.
[arvados.git] / lib / controller / handler.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         "context"
9         "errors"
10         "fmt"
11         "net/http"
12         "net/url"
13         "strings"
14         "sync"
15         "time"
16
17         "git.arvados.org/arvados.git/lib/controller/api"
18         "git.arvados.org/arvados.git/lib/controller/federation"
19         "git.arvados.org/arvados.git/lib/controller/localdb"
20         "git.arvados.org/arvados.git/lib/controller/railsproxy"
21         "git.arvados.org/arvados.git/lib/controller/router"
22         "git.arvados.org/arvados.git/lib/ctrlctx"
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/ctxlog"
25         "git.arvados.org/arvados.git/sdk/go/health"
26         "git.arvados.org/arvados.git/sdk/go/httpserver"
27         "github.com/jmoiron/sqlx"
28         // sqlx needs lib/pq to talk to PostgreSQL
29         _ "github.com/lib/pq"
30 )
31
32 type Handler struct {
33         Cluster *arvados.Cluster
34
35         setupOnce      sync.Once
36         handlerStack   http.Handler
37         proxy          *proxy
38         secureClient   *http.Client
39         insecureClient *http.Client
40         pgdb           *sqlx.DB
41         pgdbMtx        sync.Mutex
42 }
43
44 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
45         h.setupOnce.Do(h.setup)
46         if req.Method != "GET" && req.Method != "HEAD" {
47                 // http.ServeMux returns 301 with a cleaned path if
48                 // the incoming request has a double slash. Some
49                 // clients (including the Go standard library) change
50                 // the request method to GET when following a 301
51                 // redirect if the original method was not HEAD
52                 // (RFC7231 6.4.2 specifically allows this in the case
53                 // of POST). Thus "POST //foo" gets misdirected to
54                 // "GET /foo". To avoid this, eliminate double slashes
55                 // before passing the request to ServeMux.
56                 for strings.Contains(req.URL.Path, "//") {
57                         req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
58                 }
59         }
60         if h.Cluster.API.RequestTimeout > 0 {
61                 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
62                 req = req.WithContext(ctx)
63                 defer cancel()
64         }
65
66         h.handlerStack.ServeHTTP(w, req)
67 }
68
69 func (h *Handler) CheckHealth() error {
70         h.setupOnce.Do(h.setup)
71         _, err := h.db(context.TODO())
72         if err != nil {
73                 return err
74         }
75         _, _, err = railsproxy.FindRailsAPI(h.Cluster)
76         return err
77 }
78
79 func (h *Handler) Done() <-chan struct{} {
80         return nil
81 }
82
83 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
84
85 func (h *Handler) setup() {
86         mux := http.NewServeMux()
87         mux.Handle("/_health/", &health.Handler{
88                 Token:  h.Cluster.ManagementToken,
89                 Prefix: "/_health/",
90                 Routes: health.Routes{"ping": func() error { _, err := h.db(context.TODO()); return err }},
91         })
92
93         oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.db)
94         rtr := router.New(federation.New(h.Cluster), api.ComposeWrappers(ctrlctx.WrapCallsInTransactions(h.db), oidcAuthorizer.WrapCalls))
95         mux.Handle("/arvados/v1/config", rtr)
96         mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr)
97
98         if !h.Cluster.ForceLegacyAPI14 {
99                 mux.Handle("/arvados/v1/collections", rtr)
100                 mux.Handle("/arvados/v1/collections/", rtr)
101                 mux.Handle("/arvados/v1/users", rtr)
102                 mux.Handle("/arvados/v1/users/", rtr)
103                 mux.Handle("/arvados/v1/container_requests", rtr)
104                 mux.Handle("/arvados/v1/container_requests/", rtr)
105                 mux.Handle("/login", rtr)
106                 mux.Handle("/logout", rtr)
107         }
108
109         hs := http.NotFoundHandler()
110         hs = prepend(hs, h.proxyRailsAPI)
111         hs = h.setupProxyRemoteCluster(hs)
112         hs = prepend(hs, oidcAuthorizer.Middleware)
113         mux.Handle("/", hs)
114         h.handlerStack = mux
115
116         sc := *arvados.DefaultSecureClient
117         sc.CheckRedirect = neverRedirect
118         h.secureClient = &sc
119
120         ic := *arvados.InsecureHTTPClient
121         ic.CheckRedirect = neverRedirect
122         h.insecureClient = &ic
123
124         h.proxy = &proxy{
125                 Name: "arvados-controller",
126         }
127 }
128
129 var errDBConnection = errors.New("database connection error")
130
131 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
132         h.pgdbMtx.Lock()
133         defer h.pgdbMtx.Unlock()
134         if h.pgdb != nil {
135                 return h.pgdb, nil
136         }
137
138         db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
139         if err != nil {
140                 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
141                 return nil, errDBConnection
142         }
143         if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
144                 db.SetMaxOpenConns(p)
145         }
146         if err := db.Ping(); err != nil {
147                 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
148                 return nil, errDBConnection
149         }
150         h.pgdb = db
151         return db, nil
152 }
153
154 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
155
156 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
157         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
158                 middleware(w, req, next)
159         })
160 }
161
162 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
163         urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
164         if err != nil {
165                 return nil, err
166         }
167         urlOut = &url.URL{
168                 Scheme:   urlOut.Scheme,
169                 Host:     urlOut.Host,
170                 Path:     req.URL.Path,
171                 RawPath:  req.URL.RawPath,
172                 RawQuery: req.URL.RawQuery,
173         }
174         client := h.secureClient
175         if insecure {
176                 client = h.insecureClient
177         }
178         return h.proxy.Do(req, urlOut, client)
179 }
180
181 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
182         resp, err := h.localClusterRequest(req)
183         n, err := h.proxy.ForwardResponse(w, resp, err)
184         if err != nil {
185                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
186         }
187 }
188
189 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
190 // present, otherwise choose an arbitrary entry.
191 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
192         var best *url.URL
193         for target := range cluster.Services.RailsAPI.InternalURLs {
194                 target := url.URL(target)
195                 best = &target
196                 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
197                         break
198                 }
199         }
200         if best == nil {
201                 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
202         }
203         return best, cluster.TLS.Insecure, nil
204 }