c16f01a1c4facf4426256c8c229b0a479f35ea17
[arvados.git] / services / keep-web / handler.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package keepweb
6
7 import (
8         "encoding/json"
9         "errors"
10         "fmt"
11         "html"
12         "html/template"
13         "io"
14         "net/http"
15         "net/url"
16         "os"
17         "sort"
18         "strconv"
19         "strings"
20         "sync"
21
22         "git.arvados.org/arvados.git/lib/cmd"
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25         "git.arvados.org/arvados.git/sdk/go/auth"
26         "git.arvados.org/arvados.git/sdk/go/ctxlog"
27         "git.arvados.org/arvados.git/sdk/go/httpserver"
28         "git.arvados.org/arvados.git/sdk/go/keepclient"
29         "github.com/sirupsen/logrus"
30         "golang.org/x/net/webdav"
31 )
32
33 type handler struct {
34         Cache     cache
35         Cluster   *arvados.Cluster
36         setupOnce sync.Once
37         webdavLS  webdav.LockSystem
38 }
39
40 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
41
42 var notFoundMessage = "Not Found"
43 var unauthorizedMessage = "401 Unauthorized\r\n\r\nA valid Arvados token must be provided to access this resource.\r\n"
44
45 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
46 // PDH (even if it is a PDH with "+" replaced by " " or "-");
47 // otherwise "".
48 func parseCollectionIDFromURL(s string) string {
49         if arvadosclient.UUIDMatch(s) {
50                 return s
51         }
52         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
53                 return pdh
54         }
55         return ""
56 }
57
58 func (h *handler) setup() {
59         keepclient.DefaultBlockCache.MaxBlocks = h.Cluster.Collections.WebDAVCache.MaxBlockEntries
60
61         // Even though we don't accept LOCK requests, every webdav
62         // handler must have a non-nil LockSystem.
63         h.webdavLS = &noLockSystem{}
64 }
65
66 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
67         json.NewEncoder(w).Encode(struct{ Version string }{cmd.Version.String()})
68 }
69
70 type errorWithHTTPStatus interface {
71         HTTPStatus() int
72 }
73
74 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
75 // sends an HTTP header indicating success, updateOnSuccess first
76 // calls the provided update func. If the update func fails, an error
77 // response is sent (using the error's HTTP status or 500 if none),
78 // and the status code and body sent by the handler are ignored (all
79 // response writes return the update error).
80 type updateOnSuccess struct {
81         httpserver.ResponseWriter
82         logger     logrus.FieldLogger
83         update     func() error
84         sentHeader bool
85         err        error
86 }
87
88 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
89         if !uos.sentHeader {
90                 uos.WriteHeader(http.StatusOK)
91         }
92         if uos.err != nil {
93                 return 0, uos.err
94         }
95         return uos.ResponseWriter.Write(p)
96 }
97
98 func (uos *updateOnSuccess) WriteHeader(code int) {
99         if !uos.sentHeader {
100                 uos.sentHeader = true
101                 if code >= 200 && code < 400 {
102                         if uos.err = uos.update(); uos.err != nil {
103                                 code := http.StatusInternalServerError
104                                 if he := errorWithHTTPStatus(nil); errors.As(uos.err, &he) {
105                                         code = he.HTTPStatus()
106                                 }
107                                 uos.logger.WithError(uos.err).Errorf("update() returned %T error, changing response to HTTP %d", uos.err, code)
108                                 http.Error(uos.ResponseWriter, uos.err.Error(), code)
109                                 return
110                         }
111                 }
112         }
113         uos.ResponseWriter.WriteHeader(code)
114 }
115
116 var (
117         corsAllowHeadersHeader = strings.Join([]string{
118                 "Authorization", "Content-Type", "Range",
119                 // WebDAV request headers:
120                 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
121         }, ", ")
122         writeMethod = map[string]bool{
123                 "COPY":      true,
124                 "DELETE":    true,
125                 "LOCK":      true,
126                 "MKCOL":     true,
127                 "MOVE":      true,
128                 "PROPPATCH": true,
129                 "PUT":       true,
130                 "RMCOL":     true,
131                 "UNLOCK":    true,
132         }
133         webdavMethod = map[string]bool{
134                 "COPY":      true,
135                 "DELETE":    true,
136                 "LOCK":      true,
137                 "MKCOL":     true,
138                 "MOVE":      true,
139                 "OPTIONS":   true,
140                 "PROPFIND":  true,
141                 "PROPPATCH": true,
142                 "PUT":       true,
143                 "RMCOL":     true,
144                 "UNLOCK":    true,
145         }
146         browserMethod = map[string]bool{
147                 "GET":  true,
148                 "HEAD": true,
149                 "POST": true,
150         }
151         // top-level dirs to serve with siteFS
152         siteFSDir = map[string]bool{
153                 "":      true, // root directory
154                 "by_id": true,
155                 "users": true,
156         }
157 )
158
159 func stripDefaultPort(host string) string {
160         // Will consider port 80 and port 443 to be the same vhost.  I think that's fine.
161         u := &url.URL{Host: host}
162         if p := u.Port(); p == "80" || p == "443" {
163                 return strings.ToLower(u.Hostname())
164         } else {
165                 return strings.ToLower(host)
166         }
167 }
168
169 // CheckHealth implements service.Handler.
170 func (h *handler) CheckHealth() error {
171         return nil
172 }
173
174 // Done implements service.Handler.
175 func (h *handler) Done() <-chan struct{} {
176         return nil
177 }
178
179 // ServeHTTP implements http.Handler.
180 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
181         h.setupOnce.Do(h.setup)
182
183         if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
184                 r.URL.Scheme = xfp
185         }
186
187         w := httpserver.WrapResponseWriter(wOrig)
188
189         if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
190                 if !browserMethod[method] && !webdavMethod[method] {
191                         w.WriteHeader(http.StatusMethodNotAllowed)
192                         return
193                 }
194                 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
195                 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
196                 w.Header().Set("Access-Control-Allow-Origin", "*")
197                 w.Header().Set("Access-Control-Max-Age", "86400")
198                 return
199         }
200
201         if !browserMethod[r.Method] && !webdavMethod[r.Method] {
202                 w.WriteHeader(http.StatusMethodNotAllowed)
203                 return
204         }
205
206         if r.Header.Get("Origin") != "" {
207                 // Allow simple cross-origin requests without user
208                 // credentials ("user credentials" as defined by CORS,
209                 // i.e., cookies, HTTP authentication, and client-side
210                 // SSL certificates. See
211                 // http://www.w3.org/TR/cors/#user-credentials).
212                 w.Header().Set("Access-Control-Allow-Origin", "*")
213                 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
214         }
215
216         if h.serveS3(w, r) {
217                 return
218         }
219
220         pathParts := strings.Split(r.URL.Path[1:], "/")
221
222         var stripParts int
223         var collectionID string
224         var tokens []string
225         var reqTokens []string
226         var pathToken bool
227         var attachment bool
228         var useSiteFS bool
229         credentialsOK := h.Cluster.Collections.TrustAllContent
230         reasonNotAcceptingCredentials := ""
231
232         if r.Host != "" && stripDefaultPort(r.Host) == stripDefaultPort(h.Cluster.Services.WebDAVDownload.ExternalURL.Host) {
233                 credentialsOK = true
234                 attachment = true
235         } else if r.FormValue("disposition") == "attachment" {
236                 attachment = true
237         }
238
239         if !credentialsOK {
240                 reasonNotAcceptingCredentials = fmt.Sprintf("vhost %q does not specify a single collection ID or match Services.WebDAVDownload.ExternalURL %q, and Collections.TrustAllContent is false",
241                         r.Host, h.Cluster.Services.WebDAVDownload.ExternalURL)
242         }
243
244         if collectionID = arvados.CollectionIDFromDNSName(r.Host); collectionID != "" {
245                 // http://ID.collections.example/PATH...
246                 credentialsOK = true
247         } else if r.URL.Path == "/status.json" {
248                 h.serveStatus(w, r)
249                 return
250         } else if siteFSDir[pathParts[0]] {
251                 useSiteFS = true
252         } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
253                 // /c=ID[/PATH...]
254                 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
255                 stripParts = 1
256         } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
257                 if len(pathParts) >= 4 && pathParts[1] == "download" {
258                         // /collections/download/ID/TOKEN/PATH...
259                         collectionID = parseCollectionIDFromURL(pathParts[2])
260                         tokens = []string{pathParts[3]}
261                         stripParts = 4
262                         pathToken = true
263                 } else {
264                         // /collections/ID/PATH...
265                         collectionID = parseCollectionIDFromURL(pathParts[1])
266                         stripParts = 2
267                         // This path is only meant to work for public
268                         // data. Tokens provided with the request are
269                         // ignored.
270                         credentialsOK = false
271                         reasonNotAcceptingCredentials = "the '/collections/UUID/PATH' form only works for public data"
272                 }
273         }
274
275         forceReload := false
276         if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
277                 forceReload = true
278         }
279
280         if credentialsOK {
281                 reqTokens = auth.CredentialsFromRequest(r).Tokens
282         }
283
284         formToken := r.FormValue("api_token")
285         origin := r.Header.Get("Origin")
286         cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
287         safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
288         safeAttachment := attachment && r.URL.Query().Get("api_token") == ""
289         if formToken == "" {
290                 // No token to use or redact.
291         } else if safeAjax || safeAttachment {
292                 // If this is a cross-origin request, the URL won't
293                 // appear in the browser's address bar, so
294                 // substituting a clipboard-safe URL is pointless.
295                 // Redirect-with-cookie wouldn't work anyway, because
296                 // it's not safe to allow third-party use of our
297                 // cookie.
298                 //
299                 // If we're supplying an attachment, we don't need to
300                 // convert POST to GET to avoid the "really resubmit
301                 // form?" problem, so provided the token isn't
302                 // embedded in the URL, there's no reason to do
303                 // redirect-with-cookie in this case either.
304                 reqTokens = append(reqTokens, formToken)
305         } else if browserMethod[r.Method] {
306                 // If this is a page view, and the client provided a
307                 // token via query string or POST body, we must put
308                 // the token in an HttpOnly cookie, and redirect to an
309                 // equivalent URL with the query param redacted and
310                 // method = GET.
311                 h.seeOtherWithCookie(w, r, "", credentialsOK)
312                 return
313         }
314
315         targetPath := pathParts[stripParts:]
316         if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
317                 // http://ID.example/t=TOKEN/PATH...
318                 // /c=ID/t=TOKEN/PATH...
319                 //
320                 // This form must only be used to pass scoped tokens
321                 // that give permission for a single collection. See
322                 // FormValue case above.
323                 tokens = []string{targetPath[0][2:]}
324                 pathToken = true
325                 targetPath = targetPath[1:]
326                 stripParts++
327         }
328
329         fsprefix := ""
330         if useSiteFS {
331                 if writeMethod[r.Method] {
332                         http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
333                         return
334                 }
335                 if len(reqTokens) == 0 {
336                         w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
337                         http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
338                         return
339                 }
340                 tokens = reqTokens
341         } else if collectionID == "" {
342                 http.Error(w, notFoundMessage, http.StatusNotFound)
343                 return
344         } else {
345                 fsprefix = "by_id/" + collectionID + "/"
346         }
347
348         if tokens == nil {
349                 tokens = reqTokens
350                 if h.Cluster.Users.AnonymousUserToken != "" {
351                         tokens = append(tokens, h.Cluster.Users.AnonymousUserToken)
352                 }
353         }
354
355         if tokens == nil {
356                 if !credentialsOK {
357                         http.Error(w, fmt.Sprintf("Authorization tokens are not accepted here: %v, and no anonymous user token is configured.", reasonNotAcceptingCredentials), http.StatusUnauthorized)
358                 } else {
359                         http.Error(w, fmt.Sprintf("No authorization token in request, and no anonymous user token is configured."), http.StatusUnauthorized)
360                 }
361                 return
362         }
363
364         if len(targetPath) > 0 && targetPath[0] == "_" {
365                 // If a collection has a directory called "t=foo" or
366                 // "_", it can be served at
367                 // //collections.example/_/t=foo/ or
368                 // //collections.example/_/_/ respectively:
369                 // //collections.example/t=foo/ won't work because
370                 // t=foo will be interpreted as a token "foo".
371                 targetPath = targetPath[1:]
372                 stripParts++
373         }
374
375         dirOpenMode := os.O_RDONLY
376         if writeMethod[r.Method] {
377                 dirOpenMode = os.O_RDWR
378         }
379
380         validToken := make(map[string]bool)
381         var token string
382         var tokenUser *arvados.User
383         var sessionFS arvados.CustomFileSystem
384         var session *cachedSession
385         var collectionDir arvados.File
386         for _, token = range tokens {
387                 var statusErr errorWithHTTPStatus
388                 fs, sess, user, err := h.Cache.GetSession(token)
389                 if errors.As(err, &statusErr) && statusErr.HTTPStatus() == http.StatusUnauthorized {
390                         // bad token
391                         continue
392                 } else if err != nil {
393                         http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
394                         return
395                 }
396                 f, err := fs.OpenFile(fsprefix, dirOpenMode, 0)
397                 if errors.As(err, &statusErr) && statusErr.HTTPStatus() == http.StatusForbidden {
398                         // collection id is outside token scope
399                         validToken[token] = true
400                         continue
401                 }
402                 validToken[token] = true
403                 if os.IsNotExist(err) {
404                         // collection does not exist or is not
405                         // readable using this token
406                         continue
407                 } else if err != nil {
408                         http.Error(w, err.Error(), http.StatusInternalServerError)
409                         return
410                 }
411                 defer f.Close()
412
413                 collectionDir, sessionFS, session, tokenUser = f, fs, sess, user
414                 break
415         }
416         if forceReload && collectionDir != nil {
417                 err := collectionDir.Sync()
418                 if err != nil {
419                         if he := errorWithHTTPStatus(nil); errors.As(err, &he) {
420                                 http.Error(w, err.Error(), he.HTTPStatus())
421                         } else {
422                                 http.Error(w, err.Error(), http.StatusInternalServerError)
423                         }
424                         return
425                 }
426         }
427         if session == nil {
428                 if pathToken || !credentialsOK {
429                         // Either the URL is a "secret sharing link"
430                         // that didn't work out (and asking the client
431                         // for additional credentials would just be
432                         // confusing), or we don't even accept
433                         // credentials at this path.
434                         http.Error(w, notFoundMessage, http.StatusNotFound)
435                         return
436                 }
437                 for _, t := range reqTokens {
438                         if validToken[t] {
439                                 // The client provided valid token(s),
440                                 // but the collection was not found.
441                                 http.Error(w, notFoundMessage, http.StatusNotFound)
442                                 return
443                         }
444                 }
445                 // The client's token was invalid (e.g., expired), or
446                 // the client didn't even provide one.  Redirect to
447                 // workbench2's login-and-redirect-to-download url if
448                 // this is a browser navigation request. (The redirect
449                 // flow can't preserve the original method if it's not
450                 // GET, and doesn't make sense if the UA is a
451                 // command-line tool, is trying to load an inline
452                 // image, etc.; in these cases, there's nothing we can
453                 // do, so return 401 unauthorized.)
454                 //
455                 // Note Sec-Fetch-Mode is sent by all non-EOL
456                 // browsers, except Safari.
457                 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Mode
458                 //
459                 // TODO(TC): This response would be confusing to
460                 // someone trying (anonymously) to download public
461                 // data that has been deleted.  Allow a referrer to
462                 // provide this context somehow?
463                 if r.Method == http.MethodGet && r.Header.Get("Sec-Fetch-Mode") == "navigate" {
464                         target := url.URL(h.Cluster.Services.Workbench2.ExternalURL)
465                         redirkey := "redirectToPreview"
466                         if attachment {
467                                 redirkey = "redirectToDownload"
468                         }
469                         callback := "/c=" + collectionID + "/" + strings.Join(targetPath, "/")
470                         // target.RawQuery = url.Values{redirkey:
471                         // {target}}.Encode() would be the obvious
472                         // thing to do here, but wb2 doesn't decode
473                         // this as a query param -- it takes
474                         // everything after "${redirkey}=" as the
475                         // target URL. If we encode "/" as "%2F" etc.,
476                         // the redirect won't work.
477                         target.RawQuery = redirkey + "=" + callback
478                         w.Header().Add("Location", target.String())
479                         w.WriteHeader(http.StatusSeeOther)
480                 } else {
481                         w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
482                         http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
483                 }
484                 return
485         }
486
487         if r.Method == http.MethodGet || r.Method == http.MethodHead {
488                 targetfnm := fsprefix + strings.Join(pathParts[stripParts:], "/")
489                 if fi, err := sessionFS.Stat(targetfnm); err == nil && fi.IsDir() {
490                         if !strings.HasSuffix(r.URL.Path, "/") {
491                                 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
492                         } else {
493                                 h.serveDirectory(w, r, fi.Name(), sessionFS, targetfnm, !useSiteFS)
494                         }
495                         return
496                 }
497         }
498
499         var basename string
500         if len(targetPath) > 0 {
501                 basename = targetPath[len(targetPath)-1]
502         }
503         if arvadosclient.PDHMatch(collectionID) && writeMethod[r.Method] {
504                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
505                 return
506         }
507         if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
508                 http.Error(w, "Not permitted", http.StatusForbidden)
509                 return
510         }
511         h.logUploadOrDownload(r, session.arvadosclient, sessionFS, fsprefix+strings.Join(targetPath, "/"), nil, tokenUser)
512
513         if writeMethod[r.Method] {
514                 // Save the collection only if/when all
515                 // webdav->filesystem operations succeed --
516                 // and send a 500 error if the modified
517                 // collection can't be saved.
518                 //
519                 // Perform the write in a separate sitefs, so
520                 // concurrent read operations on the same
521                 // collection see the previous saved
522                 // state. After the write succeeds and the
523                 // collection record is updated, we reset the
524                 // session so the updates are visible in
525                 // subsequent read requests.
526                 client := session.client.WithRequestID(r.Header.Get("X-Request-Id"))
527                 sessionFS = client.SiteFileSystem(session.keepclient)
528                 writingDir, err := sessionFS.OpenFile(fsprefix, os.O_RDONLY, 0)
529                 if err != nil {
530                         http.Error(w, err.Error(), http.StatusInternalServerError)
531                         return
532                 }
533                 defer writingDir.Close()
534                 w = &updateOnSuccess{
535                         ResponseWriter: w,
536                         logger:         ctxlog.FromContext(r.Context()),
537                         update: func() error {
538                                 err := writingDir.Sync()
539                                 var te arvados.TransactionError
540                                 if errors.As(err, &te) {
541                                         err = te
542                                 }
543                                 if err != nil {
544                                         return err
545                                 }
546                                 // Sync the changes to the persistent
547                                 // sessionfs for this token.
548                                 snap, err := writingDir.Snapshot()
549                                 if err != nil {
550                                         return err
551                                 }
552                                 collectionDir.Splice(snap)
553                                 return nil
554                         }}
555         }
556         if r.Method == http.MethodGet {
557                 applyContentDispositionHdr(w, r, basename, attachment)
558         }
559         wh := webdav.Handler{
560                 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
561                 FileSystem: &webdavFS{
562                         collfs:        sessionFS,
563                         prefix:        fsprefix,
564                         writing:       writeMethod[r.Method],
565                         alwaysReadEOF: r.Method == "PROPFIND",
566                 },
567                 LockSystem: h.webdavLS,
568                 Logger: func(r *http.Request, err error) {
569                         if err != nil {
570                                 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
571                         }
572                 },
573         }
574         wh.ServeHTTP(w, r)
575         if r.Method == http.MethodGet && w.WroteStatus() == http.StatusOK {
576                 wrote := int64(w.WroteBodyBytes())
577                 fnm := strings.Join(pathParts[stripParts:], "/")
578                 fi, err := wh.FileSystem.Stat(r.Context(), fnm)
579                 if err == nil && fi.Size() != wrote {
580                         var n int
581                         f, err := wh.FileSystem.OpenFile(r.Context(), fnm, os.O_RDONLY, 0)
582                         if err == nil {
583                                 n, err = f.Read(make([]byte, 1024))
584                                 f.Close()
585                         }
586                         ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %v", fi.Size(), wrote, n, err)
587                 }
588         }
589 }
590
591 var dirListingTemplate = `<!DOCTYPE HTML>
592 <HTML><HEAD>
593   <META name="robots" content="NOINDEX">
594   <TITLE>{{ .CollectionName }}</TITLE>
595   <STYLE type="text/css">
596     body {
597       margin: 1.5em;
598     }
599     pre {
600       background-color: #D9EDF7;
601       border-radius: .25em;
602       padding: .75em;
603       overflow: auto;
604     }
605     .footer p {
606       font-size: 82%;
607     }
608     ul {
609       padding: 0;
610     }
611     ul li {
612       font-family: monospace;
613       list-style: none;
614     }
615   </STYLE>
616 </HEAD>
617 <BODY>
618
619 <H1>{{ .CollectionName }}</H1>
620
621 <P>This collection of data files is being shared with you through
622 Arvados.  You can download individual files listed below.  To download
623 the entire directory tree with wget, try:</P>
624
625 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
626
627 <H2>File Listing</H2>
628
629 {{if .Files}}
630 <UL>
631 {{range .Files}}
632 {{if .IsDir }}
633   <LI>{{" " | printf "%15s  " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
634 {{else}}
635   <LI>{{.Size | printf "%15d  " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
636 {{end}}
637 {{end}}
638 </UL>
639 {{else}}
640 <P>(No files; this collection is empty.)</P>
641 {{end}}
642
643 <HR noshade>
644 <DIV class="footer">
645   <P>
646     About Arvados:
647     Arvados is a free and open source software bioinformatics platform.
648     To learn more, visit arvados.org.
649     Arvados is not responsible for the files listed on this page.
650   </P>
651 </DIV>
652
653 </BODY>
654 `
655
656 type fileListEnt struct {
657         Name  string
658         Size  int64
659         IsDir bool
660 }
661
662 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
663         var files []fileListEnt
664         var walk func(string) error
665         if !strings.HasSuffix(base, "/") {
666                 base = base + "/"
667         }
668         walk = func(path string) error {
669                 dirname := base + path
670                 if dirname != "/" {
671                         dirname = strings.TrimSuffix(dirname, "/")
672                 }
673                 d, err := fs.Open(dirname)
674                 if err != nil {
675                         return err
676                 }
677                 ents, err := d.Readdir(-1)
678                 if err != nil {
679                         return err
680                 }
681                 for _, ent := range ents {
682                         if recurse && ent.IsDir() {
683                                 err = walk(path + ent.Name() + "/")
684                                 if err != nil {
685                                         return err
686                                 }
687                         } else {
688                                 files = append(files, fileListEnt{
689                                         Name:  path + ent.Name(),
690                                         Size:  ent.Size(),
691                                         IsDir: ent.IsDir(),
692                                 })
693                         }
694                 }
695                 return nil
696         }
697         if err := walk(""); err != nil {
698                 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
699                 return
700         }
701
702         funcs := template.FuncMap{
703                 "nbsp": func(s string) template.HTML {
704                         return template.HTML(strings.Replace(s, " ", "&nbsp;", -1))
705                 },
706         }
707         tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
708         if err != nil {
709                 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
710                 return
711         }
712         sort.Slice(files, func(i, j int) bool {
713                 return files[i].Name < files[j].Name
714         })
715         w.WriteHeader(http.StatusOK)
716         tmpl.Execute(w, map[string]interface{}{
717                 "CollectionName": collectionName,
718                 "Files":          files,
719                 "Request":        r,
720                 "StripParts":     strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
721         })
722 }
723
724 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
725         disposition := "inline"
726         if isAttachment {
727                 disposition = "attachment"
728         }
729         if strings.ContainsRune(r.RequestURI, '?') {
730                 // Help the UA realize that the filename is just
731                 // "filename.txt", not
732                 // "filename.txt?disposition=attachment".
733                 //
734                 // TODO(TC): Follow advice at RFC 6266 appendix D
735                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
736         }
737         if disposition != "inline" {
738                 w.Header().Set("Content-Disposition", disposition)
739         }
740 }
741
742 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
743         if formToken := r.FormValue("api_token"); formToken != "" {
744                 if !credentialsOK {
745                         // It is not safe to copy the provided token
746                         // into a cookie unless the current vhost
747                         // (origin) serves only a single collection or
748                         // we are in TrustAllContent mode.
749                         http.Error(w, "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)", http.StatusBadRequest)
750                         return
751                 }
752
753                 // The HttpOnly flag is necessary to prevent
754                 // JavaScript code (included in, or loaded by, a page
755                 // in the collection being served) from employing the
756                 // user's token beyond reading other files in the same
757                 // domain, i.e., same collection.
758                 //
759                 // The 303 redirect is necessary in the case of a GET
760                 // request to avoid exposing the token in the Location
761                 // bar, and in the case of a POST request to avoid
762                 // raising warnings when the user refreshes the
763                 // resulting page.
764                 http.SetCookie(w, &http.Cookie{
765                         Name:     "arvados_api_token",
766                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
767                         Path:     "/",
768                         HttpOnly: true,
769                         SameSite: http.SameSiteLaxMode,
770                 })
771         }
772
773         // Propagate query parameters (except api_token) from
774         // the original request.
775         redirQuery := r.URL.Query()
776         redirQuery.Del("api_token")
777
778         u := r.URL
779         if location != "" {
780                 newu, err := u.Parse(location)
781                 if err != nil {
782                         http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
783                         return
784                 }
785                 u = newu
786         }
787         redir := (&url.URL{
788                 Scheme:   r.URL.Scheme,
789                 Host:     r.Host,
790                 Path:     u.Path,
791                 RawQuery: redirQuery.Encode(),
792         }).String()
793
794         w.Header().Add("Location", redir)
795         w.WriteHeader(http.StatusSeeOther)
796         io.WriteString(w, `<A href="`)
797         io.WriteString(w, html.EscapeString(redir))
798         io.WriteString(w, `">Continue</A>`)
799 }
800
801 func (h *handler) userPermittedToUploadOrDownload(method string, tokenUser *arvados.User) bool {
802         var permitDownload bool
803         var permitUpload bool
804         if tokenUser != nil && tokenUser.IsAdmin {
805                 permitUpload = h.Cluster.Collections.WebDAVPermission.Admin.Upload
806                 permitDownload = h.Cluster.Collections.WebDAVPermission.Admin.Download
807         } else {
808                 permitUpload = h.Cluster.Collections.WebDAVPermission.User.Upload
809                 permitDownload = h.Cluster.Collections.WebDAVPermission.User.Download
810         }
811         if (method == "PUT" || method == "POST") && !permitUpload {
812                 // Disallow operations that upload new files.
813                 // Permit webdav operations that move existing files around.
814                 return false
815         } else if method == "GET" && !permitDownload {
816                 // Disallow downloading file contents.
817                 // Permit webdav operations like PROPFIND that retrieve metadata
818                 // but not file contents.
819                 return false
820         }
821         return true
822 }
823
824 func (h *handler) logUploadOrDownload(
825         r *http.Request,
826         client *arvadosclient.ArvadosClient,
827         fs arvados.CustomFileSystem,
828         filepath string,
829         collection *arvados.Collection,
830         user *arvados.User) {
831
832         log := ctxlog.FromContext(r.Context())
833         props := make(map[string]string)
834         props["reqPath"] = r.URL.Path
835         var useruuid string
836         if user != nil {
837                 log = log.WithField("user_uuid", user.UUID).
838                         WithField("user_full_name", user.FullName)
839                 useruuid = user.UUID
840         } else {
841                 useruuid = fmt.Sprintf("%s-tpzed-anonymouspublic", h.Cluster.ClusterID)
842         }
843         if collection == nil && fs != nil {
844                 collection, filepath = h.determineCollection(fs, filepath)
845         }
846         if collection != nil {
847                 log = log.WithField("collection_file_path", filepath)
848                 props["collection_file_path"] = filepath
849                 // h.determineCollection populates the collection_uuid
850                 // prop with the PDH, if this collection is being
851                 // accessed via PDH. For logging, we use a different
852                 // field depending on whether it's a UUID or PDH.
853                 if len(collection.UUID) > 32 {
854                         log = log.WithField("portable_data_hash", collection.UUID)
855                         props["portable_data_hash"] = collection.UUID
856                 } else {
857                         log = log.WithField("collection_uuid", collection.UUID)
858                         props["collection_uuid"] = collection.UUID
859                 }
860         }
861         if r.Method == "PUT" || r.Method == "POST" {
862                 log.Info("File upload")
863                 if h.Cluster.Collections.WebDAVLogEvents {
864                         go func() {
865                                 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
866                                         "object_uuid": useruuid,
867                                         "event_type":  "file_upload",
868                                         "properties":  props}}
869                                 err := client.Create("logs", lr, nil)
870                                 if err != nil {
871                                         log.WithError(err).Error("Failed to create upload log event on API server")
872                                 }
873                         }()
874                 }
875         } else if r.Method == "GET" {
876                 if collection != nil && collection.PortableDataHash != "" {
877                         log = log.WithField("portable_data_hash", collection.PortableDataHash)
878                         props["portable_data_hash"] = collection.PortableDataHash
879                 }
880                 log.Info("File download")
881                 if h.Cluster.Collections.WebDAVLogEvents {
882                         go func() {
883                                 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
884                                         "object_uuid": useruuid,
885                                         "event_type":  "file_download",
886                                         "properties":  props}}
887                                 err := client.Create("logs", lr, nil)
888                                 if err != nil {
889                                         log.WithError(err).Error("Failed to create download log event on API server")
890                                 }
891                         }()
892                 }
893         }
894 }
895
896 func (h *handler) determineCollection(fs arvados.CustomFileSystem, path string) (*arvados.Collection, string) {
897         target := strings.TrimSuffix(path, "/")
898         for cut := len(target); cut >= 0; cut = strings.LastIndexByte(target, '/') {
899                 target = target[:cut]
900                 fi, err := fs.Stat(target)
901                 if os.IsNotExist(err) {
902                         // creating a new file/dir, or download
903                         // destined to fail
904                         continue
905                 } else if err != nil {
906                         return nil, ""
907                 }
908                 switch src := fi.Sys().(type) {
909                 case *arvados.Collection:
910                         return src, strings.TrimPrefix(path[len(target):], "/")
911                 case *arvados.Group:
912                         return nil, ""
913                 default:
914                         if _, ok := src.(error); ok {
915                                 return nil, ""
916                         }
917                 }
918         }
919         return nil, ""
920 }