18790: Fix range used for checking file size.
[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         "fmt"
10         "net/http"
11         "net/http/httptest"
12         "net/url"
13         "strings"
14         "sync"
15
16         "git.arvados.org/arvados.git/lib/controller/api"
17         "git.arvados.org/arvados.git/lib/controller/federation"
18         "git.arvados.org/arvados.git/lib/controller/localdb"
19         "git.arvados.org/arvados.git/lib/controller/railsproxy"
20         "git.arvados.org/arvados.git/lib/controller/router"
21         "git.arvados.org/arvados.git/lib/ctrlctx"
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         "git.arvados.org/arvados.git/sdk/go/health"
24         "git.arvados.org/arvados.git/sdk/go/httpserver"
25
26         // sqlx needs lib/pq to talk to PostgreSQL
27         _ "github.com/lib/pq"
28 )
29
30 type Handler struct {
31         Cluster           *arvados.Cluster
32         BackgroundContext context.Context
33
34         setupOnce      sync.Once
35         federation     *federation.Conn
36         handlerStack   http.Handler
37         proxy          *proxy
38         secureClient   *http.Client
39         insecureClient *http.Client
40         dbConnector    ctrlctx.DBConnector
41         limitLogCreate chan struct{}
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         h.handlerStack.ServeHTTP(w, req)
61 }
62
63 func (h *Handler) CheckHealth() error {
64         h.setupOnce.Do(h.setup)
65         _, err := h.dbConnector.GetDB(context.TODO())
66         if err != nil {
67                 return err
68         }
69         _, _, err = railsproxy.FindRailsAPI(h.Cluster)
70         if err != nil {
71                 return err
72         }
73         if h.Cluster.API.VocabularyPath != "" {
74                 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
75                 if err != nil {
76                         return err
77                 }
78                 var resp httptest.ResponseRecorder
79                 h.handlerStack.ServeHTTP(&resp, req)
80                 if resp.Result().StatusCode != http.StatusOK {
81                         return fmt.Errorf("%d %s", resp.Result().StatusCode, resp.Result().Status)
82                 }
83         }
84         return nil
85 }
86
87 func (h *Handler) Done() <-chan struct{} {
88         return nil
89 }
90
91 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
92
93 func (h *Handler) setup() {
94         mux := http.NewServeMux()
95         healthFuncs := make(map[string]health.Func)
96
97         h.dbConnector = ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
98         go func() {
99                 <-h.BackgroundContext.Done()
100                 h.dbConnector.Close()
101         }()
102         oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.dbConnector.GetDB)
103         h.federation = federation.New(h.BackgroundContext, h.Cluster, &healthFuncs, h.dbConnector.GetDB)
104         rtr := router.New(h.federation, router.Config{
105                 MaxRequestSize: h.Cluster.API.MaxRequestSize,
106                 WrapCalls: api.ComposeWrappers(
107                         ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
108                         oidcAuthorizer.WrapCalls,
109                         ctrlctx.WrapCallsWithAuth(h.Cluster)),
110         })
111
112         healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
113         for name, f := range healthFuncs {
114                 healthRoutes[name] = f
115         }
116         mux.Handle("/_health/", &health.Handler{
117                 Token:  h.Cluster.ManagementToken,
118                 Prefix: "/_health/",
119                 Routes: healthRoutes,
120         })
121         mux.Handle("/arvados/v1/config", rtr)
122         mux.Handle("/arvados/v1/vocabulary", rtr)
123         mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr) // must come before .../users/
124         mux.Handle("/arvados/v1/collections", rtr)
125         mux.Handle("/arvados/v1/collections/", rtr)
126         mux.Handle("/arvados/v1/users", rtr)
127         mux.Handle("/arvados/v1/users/", rtr)
128         mux.Handle("/arvados/v1/connect/", rtr)
129         mux.Handle("/arvados/v1/container_requests", rtr)
130         mux.Handle("/arvados/v1/container_requests/", rtr)
131         mux.Handle("/arvados/v1/groups", rtr)
132         mux.Handle("/arvados/v1/groups/", rtr)
133         mux.Handle("/arvados/v1/links", rtr)
134         mux.Handle("/arvados/v1/links/", rtr)
135         mux.Handle("/login", rtr)
136         mux.Handle("/logout", rtr)
137         mux.Handle("/arvados/v1/api_client_authorizations", rtr)
138         mux.Handle("/arvados/v1/api_client_authorizations/", rtr)
139
140         hs := http.NotFoundHandler()
141         hs = prepend(hs, h.proxyRailsAPI)
142         hs = prepend(hs, h.routeContainerEndpoints(rtr))
143         hs = prepend(hs, h.limitLogCreateRequests)
144         hs = h.setupProxyRemoteCluster(hs)
145         hs = prepend(hs, oidcAuthorizer.Middleware)
146         mux.Handle("/", hs)
147         h.handlerStack = mux
148
149         sc := *arvados.DefaultSecureClient
150         sc.CheckRedirect = neverRedirect
151         h.secureClient = &sc
152
153         ic := *arvados.InsecureHTTPClient
154         ic.CheckRedirect = neverRedirect
155         h.insecureClient = &ic
156
157         logCreateLimit := int(float64(h.Cluster.API.MaxConcurrentRequests) * h.Cluster.API.LogCreateRequestFraction)
158         if logCreateLimit == 0 && h.Cluster.API.LogCreateRequestFraction > 0 {
159                 logCreateLimit = 1
160         }
161         h.limitLogCreate = make(chan struct{}, logCreateLimit)
162
163         h.proxy = &proxy{
164                 Name: "arvados-controller",
165         }
166
167         go h.trashSweepWorker()
168         go h.containerLogSweepWorker()
169 }
170
171 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
172
173 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
174         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
175                 middleware(w, req, next)
176         })
177 }
178
179 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
180         urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
181         if err != nil {
182                 return nil, err
183         }
184         urlOut = &url.URL{
185                 Scheme:   urlOut.Scheme,
186                 Host:     urlOut.Host,
187                 Path:     req.URL.Path,
188                 RawPath:  req.URL.RawPath,
189                 RawQuery: req.URL.RawQuery,
190         }
191         client := h.secureClient
192         if insecure {
193                 client = h.insecureClient
194         }
195         return h.proxy.Do(req, urlOut, client)
196 }
197
198 // Route /arvados/v1/containers/{uuid}/log*, .../ssh, and
199 // .../gateway_tunnel to rtr, pass everything else to next.
200 //
201 // (http.ServeMux doesn't let us route these without also routing
202 // everything under /containers/, which we don't want yet.)
203 func (h *Handler) routeContainerEndpoints(rtr http.Handler) middlewareFunc {
204         return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
205                 trim := strings.TrimPrefix(req.URL.Path, "/arvados/v1/containers/")
206                 if trim != req.URL.Path && (strings.Index(trim, "/log") == 27 ||
207                         strings.Index(trim, "/ssh") == 27 ||
208                         strings.Index(trim, "/gateway_tunnel") == 27) {
209                         rtr.ServeHTTP(w, req)
210                 } else {
211                         next.ServeHTTP(w, req)
212                 }
213         }
214 }
215
216 func (h *Handler) limitLogCreateRequests(w http.ResponseWriter, req *http.Request, next http.Handler) {
217         if cap(h.limitLogCreate) > 0 && req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/logs") {
218                 select {
219                 case h.limitLogCreate <- struct{}{}:
220                         defer func() { <-h.limitLogCreate }()
221                         next.ServeHTTP(w, req)
222                 default:
223                         http.Error(w, "Excess log messages", http.StatusServiceUnavailable)
224                 }
225                 return
226         }
227         next.ServeHTTP(w, req)
228 }
229
230 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
231         resp, err := h.localClusterRequest(req)
232         n, err := h.proxy.ForwardResponse(w, resp, err)
233         if err != nil {
234                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
235         }
236 }
237
238 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
239 // present, otherwise choose an arbitrary entry.
240 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
241         var best *url.URL
242         for target := range cluster.Services.RailsAPI.InternalURLs {
243                 target := url.URL(target)
244                 best = &target
245                 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
246                         break
247                 }
248         }
249         if best == nil {
250                 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
251         }
252         return best, cluster.TLS.Insecure, nil
253 }