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