1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
24 "git.arvados.org/arvados.git/sdk/go/auth"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 "git.arvados.org/arvados.git/sdk/go/keepclient"
28 "github.com/sirupsen/logrus"
29 "golang.org/x/net/webdav"
34 Cluster *arvados.Cluster
35 clientPool *arvadosclient.ClientPool
37 webdavLS webdav.LockSystem
40 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
42 var notFoundMessage = "404 Not found\r\n\r\nThe requested path was not found, or you do not have permission to access it.\r"
43 var unauthorizedMessage = "401 Unauthorized\r\n\r\nA valid Arvados token must be provided to access this resource.\r"
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 "-");
48 func parseCollectionIDFromURL(s string) string {
49 if arvadosclient.UUIDMatch(s) {
52 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
58 func (h *handler) setup() {
59 // Errors will be handled at the client pool.
60 arv, _ := arvados.NewClientFromConfig(h.Cluster)
61 h.clientPool = arvadosclient.MakeClientPoolWith(arv)
63 keepclient.DefaultBlockCache.MaxBlocks = h.Cluster.Collections.WebDAVCache.MaxBlockEntries
65 // Even though we don't accept LOCK requests, every webdav
66 // handler must have a non-nil LockSystem.
67 h.webdavLS = &noLockSystem{}
70 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
71 json.NewEncoder(w).Encode(struct{ Version string }{version})
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, a 500
77 // response is sent, and the status code and body sent by the handler
78 // are ignored (all response writes return the update error).
79 type updateOnSuccess struct {
80 httpserver.ResponseWriter
81 logger logrus.FieldLogger
87 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
89 uos.WriteHeader(http.StatusOK)
94 return uos.ResponseWriter.Write(p)
97 func (uos *updateOnSuccess) WriteHeader(code int) {
100 if code >= 200 && code < 400 {
101 if uos.err = uos.update(); uos.err != nil {
102 code := http.StatusInternalServerError
103 if err, ok := uos.err.(*arvados.TransactionError); ok {
104 code = err.StatusCode
106 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
107 http.Error(uos.ResponseWriter, uos.err.Error(), code)
112 uos.ResponseWriter.WriteHeader(code)
116 corsAllowHeadersHeader = strings.Join([]string{
117 "Authorization", "Content-Type", "Range",
118 // WebDAV request headers:
119 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
121 writeMethod = map[string]bool{
132 webdavMethod = map[string]bool{
145 browserMethod = map[string]bool{
150 // top-level dirs to serve with siteFS
151 siteFSDir = map[string]bool{
152 "": true, // root directory
158 func stripDefaultPort(host string) string {
159 // Will consider port 80 and port 443 to be the same vhost. I think that's fine.
160 u := &url.URL{Host: host}
161 if p := u.Port(); p == "80" || p == "443" {
162 return strings.ToLower(u.Hostname())
164 return strings.ToLower(host)
168 // CheckHealth implements service.Handler.
169 func (h *handler) CheckHealth() error {
173 // Done implements service.Handler.
174 func (h *handler) Done() <-chan struct{} {
178 // ServeHTTP implements http.Handler.
179 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
180 h.setupOnce.Do(h.setup)
182 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
186 w := httpserver.WrapResponseWriter(wOrig)
188 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
189 if !browserMethod[method] && !webdavMethod[method] {
190 w.WriteHeader(http.StatusMethodNotAllowed)
193 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
194 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
195 w.Header().Set("Access-Control-Allow-Origin", "*")
196 w.Header().Set("Access-Control-Max-Age", "86400")
200 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
201 w.WriteHeader(http.StatusMethodNotAllowed)
205 if r.Header.Get("Origin") != "" {
206 // Allow simple cross-origin requests without user
207 // credentials ("user credentials" as defined by CORS,
208 // i.e., cookies, HTTP authentication, and client-side
209 // SSL certificates. See
210 // http://www.w3.org/TR/cors/#user-credentials).
211 w.Header().Set("Access-Control-Allow-Origin", "*")
212 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
219 pathParts := strings.Split(r.URL.Path[1:], "/")
222 var collectionID string
224 var reqTokens []string
228 credentialsOK := h.Cluster.Collections.TrustAllContent
229 reasonNotAcceptingCredentials := ""
231 if r.Host != "" && stripDefaultPort(r.Host) == stripDefaultPort(h.Cluster.Services.WebDAVDownload.ExternalURL.Host) {
234 } else if r.FormValue("disposition") == "attachment" {
239 reasonNotAcceptingCredentials = fmt.Sprintf("vhost %q does not specify a single collection ID or match Services.WebDAVDownload.ExternalURL %q, and Collections.TrustAllContent is false",
240 r.Host, h.Cluster.Services.WebDAVDownload.ExternalURL)
243 if collectionID = arvados.CollectionIDFromDNSName(r.Host); collectionID != "" {
244 // http://ID.collections.example/PATH...
246 } else if r.URL.Path == "/status.json" {
249 } else if siteFSDir[pathParts[0]] {
251 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
253 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
255 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
256 if len(pathParts) >= 4 && pathParts[1] == "download" {
257 // /collections/download/ID/TOKEN/PATH...
258 collectionID = parseCollectionIDFromURL(pathParts[2])
259 tokens = []string{pathParts[3]}
263 // /collections/ID/PATH...
264 collectionID = parseCollectionIDFromURL(pathParts[1])
266 // This path is only meant to work for public
267 // data. Tokens provided with the request are
269 credentialsOK = false
270 reasonNotAcceptingCredentials = "the '/collections/UUID/PATH' form only works for public data"
274 if collectionID == "" && !useSiteFS {
275 http.Error(w, notFoundMessage, http.StatusNotFound)
280 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
285 reqTokens = auth.CredentialsFromRequest(r).Tokens
288 formToken := r.FormValue("api_token")
289 origin := r.Header.Get("Origin")
290 cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
291 safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
292 safeAttachment := attachment && r.URL.Query().Get("api_token") == ""
294 // No token to use or redact.
295 } else if safeAjax || safeAttachment {
296 // If this is a cross-origin request, the URL won't
297 // appear in the browser's address bar, so
298 // substituting a clipboard-safe URL is pointless.
299 // Redirect-with-cookie wouldn't work anyway, because
300 // it's not safe to allow third-party use of our
303 // If we're supplying an attachment, we don't need to
304 // convert POST to GET to avoid the "really resubmit
305 // form?" problem, so provided the token isn't
306 // embedded in the URL, there's no reason to do
307 // redirect-with-cookie in this case either.
308 reqTokens = append(reqTokens, formToken)
309 } else if browserMethod[r.Method] {
310 // If this is a page view, and the client provided a
311 // token via query string or POST body, we must put
312 // the token in an HttpOnly cookie, and redirect to an
313 // equivalent URL with the query param redacted and
315 h.seeOtherWithCookie(w, r, "", credentialsOK)
320 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
324 targetPath := pathParts[stripParts:]
325 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
326 // http://ID.example/t=TOKEN/PATH...
327 // /c=ID/t=TOKEN/PATH...
329 // This form must only be used to pass scoped tokens
330 // that give permission for a single collection. See
331 // FormValue case above.
332 tokens = []string{targetPath[0][2:]}
334 targetPath = targetPath[1:]
340 if h.Cluster.Users.AnonymousUserToken != "" {
341 tokens = append(tokens, h.Cluster.Users.AnonymousUserToken)
347 http.Error(w, fmt.Sprintf("Authorization tokens are not accepted here: %v, and no anonymous user token is configured.", reasonNotAcceptingCredentials), http.StatusUnauthorized)
349 http.Error(w, fmt.Sprintf("No authorization token in request, and no anonymous user token is configured."), http.StatusUnauthorized)
354 if len(targetPath) > 0 && targetPath[0] == "_" {
355 // If a collection has a directory called "t=foo" or
356 // "_", it can be served at
357 // //collections.example/_/t=foo/ or
358 // //collections.example/_/_/ respectively:
359 // //collections.example/t=foo/ won't work because
360 // t=foo will be interpreted as a token "foo".
361 targetPath = targetPath[1:]
365 arv := h.clientPool.Get()
367 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
370 defer h.clientPool.Put(arv)
372 var collection *arvados.Collection
373 var tokenUser *arvados.User
374 tokenResult := make(map[string]int)
375 for _, arv.ApiToken = range tokens {
377 collection, err = h.Cache.Get(arv, collectionID, forceReload)
382 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
383 switch srvErr.HttpStatusCode {
385 // Token broken or insufficient to
386 // retrieve collection
387 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
391 // Something more serious is wrong
392 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
395 if collection == nil {
396 if pathToken || !credentialsOK {
397 // Either the URL is a "secret sharing link"
398 // that didn't work out (and asking the client
399 // for additional credentials would just be
400 // confusing), or we don't even accept
401 // credentials at this path.
402 http.Error(w, notFoundMessage, http.StatusNotFound)
405 for _, t := range reqTokens {
406 if tokenResult[t] == 404 {
407 // The client provided valid token(s), but the
408 // collection was not found.
409 http.Error(w, notFoundMessage, http.StatusNotFound)
413 // The client's token was invalid (e.g., expired), or
414 // the client didn't even provide one. Redirect to
415 // workbench2's login-and-redirect-to-download url if
416 // this is a browser navigation request. (The redirect
417 // flow can't preserve the original method if it's not
418 // GET, and doesn't make sense if the UA is a
419 // command-line tool, is trying to load an inline
420 // image, etc.; in these cases, there's nothing we can
421 // do, so return 401 unauthorized.)
423 // Note Sec-Fetch-Mode is sent by all non-EOL
424 // browsers, except Safari.
425 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Mode
427 // TODO(TC): This response would be confusing to
428 // someone trying (anonymously) to download public
429 // data that has been deleted. Allow a referrer to
430 // provide this context somehow?
431 if r.Method == http.MethodGet && r.Header.Get("Sec-Fetch-Mode") == "navigate" {
432 target := url.URL(h.Cluster.Services.Workbench2.ExternalURL)
433 redirkey := "redirectToPreview"
435 redirkey = "redirectToDownload"
437 callback := "/c=" + collectionID + "/" + strings.Join(targetPath, "/")
438 // target.RawQuery = url.Values{redirkey:
439 // {target}}.Encode() would be the obvious
440 // thing to do here, but wb2 doesn't decode
441 // this as a query param -- it takes
442 // everything after "${redirkey}=" as the
443 // target URL. If we encode "/" as "%2F" etc.,
444 // the redirect won't work.
445 target.RawQuery = redirkey + "=" + callback
446 w.Header().Add("Location", target.String())
447 w.WriteHeader(http.StatusSeeOther)
449 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
450 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
455 kc, err := keepclient.MakeKeepClient(arv)
457 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
460 kc.RequestID = r.Header.Get("X-Request-Id")
463 if len(targetPath) > 0 {
464 basename = targetPath[len(targetPath)-1]
466 applyContentDispositionHdr(w, r, basename, attachment)
468 client := (&arvados.Client{
469 APIHost: arv.ApiServer,
470 AuthToken: arv.ApiToken,
471 Insecure: arv.ApiInsecure,
472 }).WithRequestID(r.Header.Get("X-Request-Id"))
474 fs, err := collection.FileSystem(client, kc)
476 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
480 writefs, writeOK := fs.(arvados.CollectionFileSystem)
481 targetIsPDH := arvadosclient.PDHMatch(collectionID)
482 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
483 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
487 // Check configured permission
488 _, sess, err := h.Cache.GetSession(arv.ApiToken)
490 http.Error(w, "session cache: "+err.Error(), http.StatusInternalServerError)
492 tokenUser, err = h.Cache.GetTokenUser(arv.ApiToken)
494 http.Error(w, "user lookup: "+err.Error(), http.StatusInternalServerError)
497 if webdavMethod[r.Method] {
498 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
499 http.Error(w, "Not permitted", http.StatusForbidden)
502 h.logUploadOrDownload(r, sess.arvadosclient, nil, strings.Join(targetPath, "/"), collection, tokenUser)
504 if writeMethod[r.Method] {
505 // Save the collection only if/when all
506 // webdav->filesystem operations succeed --
507 // and send a 500 error if the modified
508 // collection can't be saved.
509 w = &updateOnSuccess{
511 logger: ctxlog.FromContext(r.Context()),
512 update: func() error {
513 return h.Cache.Update(client, *collection, writefs)
517 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
518 FileSystem: &webdavFS{
520 writing: writeMethod[r.Method],
521 alwaysReadEOF: r.Method == "PROPFIND",
523 LockSystem: h.webdavLS,
524 Logger: func(_ *http.Request, err error) {
526 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
534 openPath := "/" + strings.Join(targetPath, "/")
535 f, err := fs.Open(openPath)
536 if os.IsNotExist(err) {
537 // Requested non-existent path
538 http.Error(w, notFoundMessage, http.StatusNotFound)
540 } else if err != nil {
541 // Some other (unexpected) error
542 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
546 if stat, err := f.Stat(); err != nil {
547 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
548 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
549 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
550 // If client requests ".../dirname", redirect to
551 // ".../dirname/". This way, relative links in the
552 // listing for "dirname" can always be "fnm", never
554 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
555 } else if stat.IsDir() {
556 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
558 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
559 http.Error(w, "Not permitted", http.StatusForbidden)
562 h.logUploadOrDownload(r, sess.arvadosclient, nil, strings.Join(targetPath, "/"), collection, tokenUser)
564 http.ServeContent(w, r, basename, stat.ModTime(), f)
565 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && w.WroteStatus() == http.StatusOK {
566 // If we wrote fewer bytes than expected, it's
567 // too late to change the real response code
568 // or send an error message to the client, but
569 // at least we can try to put some useful
570 // debugging info in the logs.
571 n, err := f.Read(make([]byte, 1024))
572 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %v", stat.Size(), wrote, n, err)
577 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
578 arv = h.clientPool.Get()
580 err = h.clientPool.Err()
583 release = func() { h.clientPool.Put(arv) }
585 kc, err = keepclient.MakeKeepClient(arv)
591 client = (&arvados.Client{
592 APIHost: arv.ApiServer,
593 AuthToken: arv.ApiToken,
594 Insecure: arv.ApiInsecure,
595 }).WithRequestID(reqID)
599 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
600 if len(tokens) == 0 {
601 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
602 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
605 if writeMethod[r.Method] {
606 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
610 fs, sess, err := h.Cache.GetSession(tokens[0])
612 http.Error(w, err.Error(), http.StatusInternalServerError)
615 fs.ForwardSlashNameSubstitution(h.Cluster.Collections.ForwardSlashNameSubstitution)
616 f, err := fs.Open(r.URL.Path)
617 if os.IsNotExist(err) {
618 http.Error(w, err.Error(), http.StatusNotFound)
620 } else if err != nil {
621 http.Error(w, err.Error(), http.StatusInternalServerError)
625 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
626 if !strings.HasSuffix(r.URL.Path, "/") {
627 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
629 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
634 tokenUser, err := h.Cache.GetTokenUser(tokens[0])
635 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
636 http.Error(w, "Not permitted", http.StatusForbidden)
639 h.logUploadOrDownload(r, sess.arvadosclient, fs, r.URL.Path, nil, tokenUser)
641 if r.Method == "GET" {
642 _, basename := filepath.Split(r.URL.Path)
643 applyContentDispositionHdr(w, r, basename, attachment)
645 wh := webdav.Handler{
647 FileSystem: &webdavFS{
649 writing: writeMethod[r.Method],
650 alwaysReadEOF: r.Method == "PROPFIND",
652 LockSystem: h.webdavLS,
653 Logger: func(_ *http.Request, err error) {
655 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
662 var dirListingTemplate = `<!DOCTYPE HTML>
664 <META name="robots" content="NOINDEX">
665 <TITLE>{{ .CollectionName }}</TITLE>
666 <STYLE type="text/css">
671 background-color: #D9EDF7;
672 border-radius: .25em;
683 font-family: monospace;
690 <H1>{{ .CollectionName }}</H1>
692 <P>This collection of data files is being shared with you through
693 Arvados. You can download individual files listed below. To download
694 the entire directory tree with wget, try:</P>
696 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
698 <H2>File Listing</H2>
704 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
706 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
711 <P>(No files; this collection is empty.)</P>
718 Arvados is a free and open source software bioinformatics platform.
719 To learn more, visit arvados.org.
720 Arvados is not responsible for the files listed on this page.
727 type fileListEnt struct {
733 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
734 var files []fileListEnt
735 var walk func(string) error
736 if !strings.HasSuffix(base, "/") {
739 walk = func(path string) error {
740 dirname := base + path
742 dirname = strings.TrimSuffix(dirname, "/")
744 d, err := fs.Open(dirname)
748 ents, err := d.Readdir(-1)
752 for _, ent := range ents {
753 if recurse && ent.IsDir() {
754 err = walk(path + ent.Name() + "/")
759 files = append(files, fileListEnt{
760 Name: path + ent.Name(),
768 if err := walk(""); err != nil {
769 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
773 funcs := template.FuncMap{
774 "nbsp": func(s string) template.HTML {
775 return template.HTML(strings.Replace(s, " ", " ", -1))
778 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
780 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
783 sort.Slice(files, func(i, j int) bool {
784 return files[i].Name < files[j].Name
786 w.WriteHeader(http.StatusOK)
787 tmpl.Execute(w, map[string]interface{}{
788 "CollectionName": collectionName,
791 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
795 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
796 disposition := "inline"
798 disposition = "attachment"
800 if strings.ContainsRune(r.RequestURI, '?') {
801 // Help the UA realize that the filename is just
802 // "filename.txt", not
803 // "filename.txt?disposition=attachment".
805 // TODO(TC): Follow advice at RFC 6266 appendix D
806 disposition += "; filename=" + strconv.QuoteToASCII(filename)
808 if disposition != "inline" {
809 w.Header().Set("Content-Disposition", disposition)
813 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
814 if formToken := r.FormValue("api_token"); formToken != "" {
816 // It is not safe to copy the provided token
817 // into a cookie unless the current vhost
818 // (origin) serves only a single collection or
819 // we are in TrustAllContent mode.
820 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)
824 // The HttpOnly flag is necessary to prevent
825 // JavaScript code (included in, or loaded by, a page
826 // in the collection being served) from employing the
827 // user's token beyond reading other files in the same
828 // domain, i.e., same collection.
830 // The 303 redirect is necessary in the case of a GET
831 // request to avoid exposing the token in the Location
832 // bar, and in the case of a POST request to avoid
833 // raising warnings when the user refreshes the
835 http.SetCookie(w, &http.Cookie{
836 Name: "arvados_api_token",
837 Value: auth.EncodeTokenCookie([]byte(formToken)),
840 SameSite: http.SameSiteLaxMode,
844 // Propagate query parameters (except api_token) from
845 // the original request.
846 redirQuery := r.URL.Query()
847 redirQuery.Del("api_token")
851 newu, err := u.Parse(location)
853 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
859 Scheme: r.URL.Scheme,
862 RawQuery: redirQuery.Encode(),
865 w.Header().Add("Location", redir)
866 w.WriteHeader(http.StatusSeeOther)
867 io.WriteString(w, `<A href="`)
868 io.WriteString(w, html.EscapeString(redir))
869 io.WriteString(w, `">Continue</A>`)
872 func (h *handler) userPermittedToUploadOrDownload(method string, tokenUser *arvados.User) bool {
873 var permitDownload bool
874 var permitUpload bool
875 if tokenUser != nil && tokenUser.IsAdmin {
876 permitUpload = h.Cluster.Collections.WebDAVPermission.Admin.Upload
877 permitDownload = h.Cluster.Collections.WebDAVPermission.Admin.Download
879 permitUpload = h.Cluster.Collections.WebDAVPermission.User.Upload
880 permitDownload = h.Cluster.Collections.WebDAVPermission.User.Download
882 if (method == "PUT" || method == "POST") && !permitUpload {
883 // Disallow operations that upload new files.
884 // Permit webdav operations that move existing files around.
886 } else if method == "GET" && !permitDownload {
887 // Disallow downloading file contents.
888 // Permit webdav operations like PROPFIND that retrieve metadata
889 // but not file contents.
895 func (h *handler) logUploadOrDownload(
897 client *arvadosclient.ArvadosClient,
898 fs arvados.CustomFileSystem,
900 collection *arvados.Collection,
901 user *arvados.User) {
903 log := ctxlog.FromContext(r.Context())
904 props := make(map[string]string)
905 props["reqPath"] = r.URL.Path
908 log = log.WithField("user_uuid", user.UUID).
909 WithField("user_full_name", user.FullName)
912 useruuid = fmt.Sprintf("%s-tpzed-anonymouspublic", h.Cluster.ClusterID)
914 if collection == nil && fs != nil {
915 collection, filepath = h.determineCollection(fs, filepath)
917 if collection != nil {
918 log = log.WithField("collection_file_path", filepath)
919 props["collection_file_path"] = filepath
920 // h.determineCollection populates the collection_uuid
921 // prop with the PDH, if this collection is being
922 // accessed via PDH. For logging, we use a different
923 // field depending on whether it's a UUID or PDH.
924 if len(collection.UUID) > 32 {
925 log = log.WithField("portable_data_hash", collection.UUID)
926 props["portable_data_hash"] = collection.UUID
928 log = log.WithField("collection_uuid", collection.UUID)
929 props["collection_uuid"] = collection.UUID
932 if r.Method == "PUT" || r.Method == "POST" {
933 log.Info("File upload")
934 if h.Cluster.Collections.WebDAVLogEvents {
936 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
937 "object_uuid": useruuid,
938 "event_type": "file_upload",
939 "properties": props}}
940 err := client.Create("logs", lr, nil)
942 log.WithError(err).Error("Failed to create upload log event on API server")
946 } else if r.Method == "GET" {
947 if collection != nil && collection.PortableDataHash != "" {
948 log = log.WithField("portable_data_hash", collection.PortableDataHash)
949 props["portable_data_hash"] = collection.PortableDataHash
951 log.Info("File download")
952 if h.Cluster.Collections.WebDAVLogEvents {
954 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
955 "object_uuid": useruuid,
956 "event_type": "file_download",
957 "properties": props}}
958 err := client.Create("logs", lr, nil)
960 log.WithError(err).Error("Failed to create download log event on API server")
967 func (h *handler) determineCollection(fs arvados.CustomFileSystem, path string) (*arvados.Collection, string) {
968 target := strings.TrimSuffix(path, "/")
970 fi, err := fs.Stat(target)
974 switch src := fi.Sys().(type) {
975 case *arvados.Collection:
976 return src, strings.TrimPrefix(path[len(target):], "/")
980 if _, ok := src.(error); ok {
985 cut := strings.LastIndexByte(target, '/')
989 target = target[:cut]