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