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/health"
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"
35 MetricsAPI http.Handler
36 clientPool *arvadosclient.ClientPool
38 healthHandler http.Handler
39 webdavLS webdav.LockSystem
42 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
43 // a UUID or URL-encoded PDH; otherwise "".
44 func parseCollectionIDFromDNSName(s string) string {
46 if i := strings.IndexRune(s, '.'); i >= 0 {
49 // Names like {uuid}--collections.example.com serve the same
50 // purpose as {uuid}.collections.example.com but can reduce
51 // cost/effort of using [additional] wildcard certificates.
52 if i := strings.Index(s, "--"); i >= 0 {
55 if arvadosclient.UUIDMatch(s) {
58 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
64 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
66 var notFoundMessage = "404 Not found\r\n\r\nThe requested path was not found, or you do not have permission to access it.\r"
67 var unauthorizedMessage = "401 Unauthorized\r\n\r\nA valid Arvados token must be provided to access this resource.\r"
69 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
70 // PDH (even if it is a PDH with "+" replaced by " " or "-");
72 func parseCollectionIDFromURL(s string) string {
73 if arvadosclient.UUIDMatch(s) {
76 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
82 func (h *handler) setup() {
83 // Errors will be handled at the client pool.
84 arv, _ := arvados.NewClientFromConfig(h.Config.cluster)
85 h.clientPool = arvadosclient.MakeClientPoolWith(arv)
87 keepclient.RefreshServiceDiscoveryOnSIGHUP()
88 keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
90 h.healthHandler = &health.Handler{
91 Token: h.Config.cluster.ManagementToken,
95 // Even though we don't accept LOCK requests, every webdav
96 // handler must have a non-nil LockSystem.
97 h.webdavLS = &noLockSystem{}
100 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
101 json.NewEncoder(w).Encode(struct{ Version string }{version})
104 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
105 // sends an HTTP header indicating success, updateOnSuccess first
106 // calls the provided update func. If the update func fails, a 500
107 // response is sent, and the status code and body sent by the handler
108 // are ignored (all response writes return the update error).
109 type updateOnSuccess struct {
110 httpserver.ResponseWriter
111 logger logrus.FieldLogger
117 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
119 uos.WriteHeader(http.StatusOK)
124 return uos.ResponseWriter.Write(p)
127 func (uos *updateOnSuccess) WriteHeader(code int) {
129 uos.sentHeader = true
130 if code >= 200 && code < 400 {
131 if uos.err = uos.update(); uos.err != nil {
132 code := http.StatusInternalServerError
133 if err, ok := uos.err.(*arvados.TransactionError); ok {
134 code = err.StatusCode
136 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
137 http.Error(uos.ResponseWriter, uos.err.Error(), code)
142 uos.ResponseWriter.WriteHeader(code)
146 corsAllowHeadersHeader = strings.Join([]string{
147 "Authorization", "Content-Type", "Range",
148 // WebDAV request headers:
149 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
151 writeMethod = map[string]bool{
162 webdavMethod = map[string]bool{
175 browserMethod = map[string]bool{
180 // top-level dirs to serve with siteFS
181 siteFSDir = map[string]bool{
182 "": true, // root directory
188 func stripDefaultPort(host string) string {
189 // Will consider port 80 and port 443 to be the same vhost. I think that's fine.
190 u := &url.URL{Host: host}
191 if p := u.Port(); p == "80" || p == "443" {
192 return strings.ToLower(u.Hostname())
194 return strings.ToLower(host)
198 // ServeHTTP implements http.Handler.
199 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
200 h.setupOnce.Do(h.setup)
202 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
206 w := httpserver.WrapResponseWriter(wOrig)
208 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
209 h.healthHandler.ServeHTTP(w, r)
213 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
214 if !browserMethod[method] && !webdavMethod[method] {
215 w.WriteHeader(http.StatusMethodNotAllowed)
218 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
219 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
220 w.Header().Set("Access-Control-Allow-Origin", "*")
221 w.Header().Set("Access-Control-Max-Age", "86400")
225 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
226 w.WriteHeader(http.StatusMethodNotAllowed)
230 if r.Header.Get("Origin") != "" {
231 // Allow simple cross-origin requests without user
232 // credentials ("user credentials" as defined by CORS,
233 // i.e., cookies, HTTP authentication, and client-side
234 // SSL certificates. See
235 // http://www.w3.org/TR/cors/#user-credentials).
236 w.Header().Set("Access-Control-Allow-Origin", "*")
237 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
244 pathParts := strings.Split(r.URL.Path[1:], "/")
247 var collectionID string
249 var reqTokens []string
253 credentialsOK := h.Config.cluster.Collections.TrustAllContent
254 reasonNotAcceptingCredentials := ""
256 if r.Host != "" && stripDefaultPort(r.Host) == stripDefaultPort(h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host) {
259 } else if r.FormValue("disposition") == "attachment" {
264 reasonNotAcceptingCredentials = fmt.Sprintf("vhost %q does not specify a single collection ID or match Services.WebDAVDownload.ExternalURL %q, and Collections.TrustAllContent is false",
265 r.Host, h.Config.cluster.Services.WebDAVDownload.ExternalURL)
268 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
269 // http://ID.collections.example/PATH...
271 } else if r.URL.Path == "/status.json" {
274 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
275 h.MetricsAPI.ServeHTTP(w, r)
277 } else if siteFSDir[pathParts[0]] {
279 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
281 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
283 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
284 if len(pathParts) >= 4 && pathParts[1] == "download" {
285 // /collections/download/ID/TOKEN/PATH...
286 collectionID = parseCollectionIDFromURL(pathParts[2])
287 tokens = []string{pathParts[3]}
291 // /collections/ID/PATH...
292 collectionID = parseCollectionIDFromURL(pathParts[1])
294 // This path is only meant to work for public
295 // data. Tokens provided with the request are
297 credentialsOK = false
298 reasonNotAcceptingCredentials = "the '/collections/UUID/PATH' form only works for public data"
302 if collectionID == "" && !useSiteFS {
303 http.Error(w, notFoundMessage, http.StatusNotFound)
308 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
313 reqTokens = auth.CredentialsFromRequest(r).Tokens
316 formToken := r.FormValue("api_token")
317 origin := r.Header.Get("Origin")
318 cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
319 safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
320 safeAttachment := attachment && r.URL.Query().Get("api_token") == ""
322 // No token to use or redact.
323 } else if safeAjax || safeAttachment {
324 // If this is a cross-origin request, the URL won't
325 // appear in the browser's address bar, so
326 // substituting a clipboard-safe URL is pointless.
327 // Redirect-with-cookie wouldn't work anyway, because
328 // it's not safe to allow third-party use of our
331 // If we're supplying an attachment, we don't need to
332 // convert POST to GET to avoid the "really resubmit
333 // form?" problem, so provided the token isn't
334 // embedded in the URL, there's no reason to do
335 // redirect-with-cookie in this case either.
336 reqTokens = append(reqTokens, formToken)
337 } else if browserMethod[r.Method] {
338 // If this is a page view, and the client provided a
339 // token via query string or POST body, we must put
340 // the token in an HttpOnly cookie, and redirect to an
341 // equivalent URL with the query param redacted and
343 h.seeOtherWithCookie(w, r, "", credentialsOK)
348 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
352 targetPath := pathParts[stripParts:]
353 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
354 // http://ID.example/t=TOKEN/PATH...
355 // /c=ID/t=TOKEN/PATH...
357 // This form must only be used to pass scoped tokens
358 // that give permission for a single collection. See
359 // FormValue case above.
360 tokens = []string{targetPath[0][2:]}
362 targetPath = targetPath[1:]
368 if h.Config.cluster.Users.AnonymousUserToken != "" {
369 tokens = append(tokens, h.Config.cluster.Users.AnonymousUserToken)
375 http.Error(w, fmt.Sprintf("Authorization tokens are not accepted here: %v, and no anonymous user token is configured.", reasonNotAcceptingCredentials), http.StatusUnauthorized)
377 http.Error(w, fmt.Sprintf("No authorization token in request, and no anonymous user token is configured."), http.StatusUnauthorized)
382 if len(targetPath) > 0 && targetPath[0] == "_" {
383 // If a collection has a directory called "t=foo" or
384 // "_", it can be served at
385 // //collections.example/_/t=foo/ or
386 // //collections.example/_/_/ respectively:
387 // //collections.example/t=foo/ won't work because
388 // t=foo will be interpreted as a token "foo".
389 targetPath = targetPath[1:]
393 arv := h.clientPool.Get()
395 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
398 defer h.clientPool.Put(arv)
400 var collection *arvados.Collection
401 var tokenUser *arvados.User
402 tokenResult := make(map[string]int)
403 for _, arv.ApiToken = range tokens {
405 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
410 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
411 switch srvErr.HttpStatusCode {
413 // Token broken or insufficient to
414 // retrieve collection
415 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
419 // Something more serious is wrong
420 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
423 if collection == nil {
424 if pathToken || !credentialsOK {
425 // Either the URL is a "secret sharing link"
426 // that didn't work out (and asking the client
427 // for additional credentials would just be
428 // confusing), or we don't even accept
429 // credentials at this path.
430 http.Error(w, notFoundMessage, http.StatusNotFound)
433 for _, t := range reqTokens {
434 if tokenResult[t] == 404 {
435 // The client provided valid token(s), but the
436 // collection was not found.
437 http.Error(w, notFoundMessage, http.StatusNotFound)
441 // The client's token was invalid (e.g., expired), or
442 // the client didn't even provide one. Propagate the
443 // 401 to encourage the client to use a [different]
446 // TODO(TC): This response would be confusing to
447 // someone trying (anonymously) to download public
448 // data that has been deleted. Allow a referrer to
449 // provide this context somehow?
450 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
451 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.Config.Cache.GetSession(arv.ApiToken)
489 tokenUser, err = h.Config.Cache.GetTokenUser(arv.ApiToken)
491 if webdavMethod[r.Method] {
492 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
493 http.Error(w, "Not permitted", http.StatusForbidden)
496 h.logUploadOrDownload(r, sess.arvadosclient, nil, strings.Join(targetPath, "/"), collection, tokenUser)
498 if writeMethod[r.Method] {
499 // Save the collection only if/when all
500 // webdav->filesystem operations succeed --
501 // and send a 500 error if the modified
502 // collection can't be saved.
503 w = &updateOnSuccess{
505 logger: ctxlog.FromContext(r.Context()),
506 update: func() error {
507 return h.Config.Cache.Update(client, *collection, writefs)
511 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
512 FileSystem: &webdavFS{
514 writing: writeMethod[r.Method],
515 alwaysReadEOF: r.Method == "PROPFIND",
517 LockSystem: h.webdavLS,
518 Logger: func(_ *http.Request, err error) {
520 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
528 openPath := "/" + strings.Join(targetPath, "/")
529 f, err := fs.Open(openPath)
530 if os.IsNotExist(err) {
531 // Requested non-existent path
532 http.Error(w, notFoundMessage, http.StatusNotFound)
534 } else if err != nil {
535 // Some other (unexpected) error
536 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
540 if stat, err := f.Stat(); err != nil {
541 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
542 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
543 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
544 // If client requests ".../dirname", redirect to
545 // ".../dirname/". This way, relative links in the
546 // listing for "dirname" can always be "fnm", never
548 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
549 } else if stat.IsDir() {
550 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
552 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
553 http.Error(w, "Not permitted", http.StatusForbidden)
556 h.logUploadOrDownload(r, sess.arvadosclient, nil, strings.Join(targetPath, "/"), collection, tokenUser)
558 http.ServeContent(w, r, basename, stat.ModTime(), f)
559 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && w.WroteStatus() == http.StatusOK {
560 // If we wrote fewer bytes than expected, it's
561 // too late to change the real response code
562 // or send an error message to the client, but
563 // at least we can try to put some useful
564 // debugging info in the logs.
565 n, err := f.Read(make([]byte, 1024))
566 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %v", stat.Size(), wrote, n, err)
571 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
572 arv = h.clientPool.Get()
574 err = h.clientPool.Err()
577 release = func() { h.clientPool.Put(arv) }
579 kc, err = keepclient.MakeKeepClient(arv)
585 client = (&arvados.Client{
586 APIHost: arv.ApiServer,
587 AuthToken: arv.ApiToken,
588 Insecure: arv.ApiInsecure,
589 }).WithRequestID(reqID)
593 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
594 if len(tokens) == 0 {
595 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
596 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
599 if writeMethod[r.Method] {
600 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
604 fs, sess, err := h.Config.Cache.GetSession(tokens[0])
606 http.Error(w, err.Error(), http.StatusInternalServerError)
609 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
610 f, err := fs.Open(r.URL.Path)
611 if os.IsNotExist(err) {
612 http.Error(w, err.Error(), http.StatusNotFound)
614 } else if err != nil {
615 http.Error(w, err.Error(), http.StatusInternalServerError)
619 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
620 if !strings.HasSuffix(r.URL.Path, "/") {
621 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
623 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
628 tokenUser, err := h.Config.Cache.GetTokenUser(tokens[0])
629 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
630 http.Error(w, "Not permitted", http.StatusForbidden)
633 h.logUploadOrDownload(r, sess.arvadosclient, fs, r.URL.Path, nil, tokenUser)
635 if r.Method == "GET" {
636 _, basename := filepath.Split(r.URL.Path)
637 applyContentDispositionHdr(w, r, basename, attachment)
639 wh := webdav.Handler{
641 FileSystem: &webdavFS{
643 writing: writeMethod[r.Method],
644 alwaysReadEOF: r.Method == "PROPFIND",
646 LockSystem: h.webdavLS,
647 Logger: func(_ *http.Request, err error) {
649 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
656 var dirListingTemplate = `<!DOCTYPE HTML>
658 <META name="robots" content="NOINDEX">
659 <TITLE>{{ .CollectionName }}</TITLE>
660 <STYLE type="text/css">
665 background-color: #D9EDF7;
666 border-radius: .25em;
677 font-family: monospace;
684 <H1>{{ .CollectionName }}</H1>
686 <P>This collection of data files is being shared with you through
687 Arvados. You can download individual files listed below. To download
688 the entire directory tree with wget, try:</P>
690 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
692 <H2>File Listing</H2>
698 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
700 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
705 <P>(No files; this collection is empty.)</P>
712 Arvados is a free and open source software bioinformatics platform.
713 To learn more, visit arvados.org.
714 Arvados is not responsible for the files listed on this page.
721 type fileListEnt struct {
727 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
728 var files []fileListEnt
729 var walk func(string) error
730 if !strings.HasSuffix(base, "/") {
733 walk = func(path string) error {
734 dirname := base + path
736 dirname = strings.TrimSuffix(dirname, "/")
738 d, err := fs.Open(dirname)
742 ents, err := d.Readdir(-1)
746 for _, ent := range ents {
747 if recurse && ent.IsDir() {
748 err = walk(path + ent.Name() + "/")
753 files = append(files, fileListEnt{
754 Name: path + ent.Name(),
762 if err := walk(""); err != nil {
763 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
767 funcs := template.FuncMap{
768 "nbsp": func(s string) template.HTML {
769 return template.HTML(strings.Replace(s, " ", " ", -1))
772 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
774 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
777 sort.Slice(files, func(i, j int) bool {
778 return files[i].Name < files[j].Name
780 w.WriteHeader(http.StatusOK)
781 tmpl.Execute(w, map[string]interface{}{
782 "CollectionName": collectionName,
785 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
789 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
790 disposition := "inline"
792 disposition = "attachment"
794 if strings.ContainsRune(r.RequestURI, '?') {
795 // Help the UA realize that the filename is just
796 // "filename.txt", not
797 // "filename.txt?disposition=attachment".
799 // TODO(TC): Follow advice at RFC 6266 appendix D
800 disposition += "; filename=" + strconv.QuoteToASCII(filename)
802 if disposition != "inline" {
803 w.Header().Set("Content-Disposition", disposition)
807 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
808 if formToken := r.FormValue("api_token"); formToken != "" {
810 // It is not safe to copy the provided token
811 // into a cookie unless the current vhost
812 // (origin) serves only a single collection or
813 // we are in TrustAllContent mode.
814 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)
818 // The HttpOnly flag is necessary to prevent
819 // JavaScript code (included in, or loaded by, a page
820 // in the collection being served) from employing the
821 // user's token beyond reading other files in the same
822 // domain, i.e., same collection.
824 // The 303 redirect is necessary in the case of a GET
825 // request to avoid exposing the token in the Location
826 // bar, and in the case of a POST request to avoid
827 // raising warnings when the user refreshes the
829 http.SetCookie(w, &http.Cookie{
830 Name: "arvados_api_token",
831 Value: auth.EncodeTokenCookie([]byte(formToken)),
834 SameSite: http.SameSiteLaxMode,
838 // Propagate query parameters (except api_token) from
839 // the original request.
840 redirQuery := r.URL.Query()
841 redirQuery.Del("api_token")
845 newu, err := u.Parse(location)
847 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
853 Scheme: r.URL.Scheme,
856 RawQuery: redirQuery.Encode(),
859 w.Header().Add("Location", redir)
860 w.WriteHeader(http.StatusSeeOther)
861 io.WriteString(w, `<A href="`)
862 io.WriteString(w, html.EscapeString(redir))
863 io.WriteString(w, `">Continue</A>`)
866 func (h *handler) userPermittedToUploadOrDownload(method string, tokenUser *arvados.User) bool {
867 var permitDownload bool
868 var permitUpload bool
869 if tokenUser != nil && tokenUser.IsAdmin {
870 permitUpload = h.Config.cluster.Collections.WebDAVPermission.Admin.Upload
871 permitDownload = h.Config.cluster.Collections.WebDAVPermission.Admin.Download
873 permitUpload = h.Config.cluster.Collections.WebDAVPermission.User.Upload
874 permitDownload = h.Config.cluster.Collections.WebDAVPermission.User.Download
876 if (method == "PUT" || method == "POST") && !permitUpload {
877 // Disallow operations that upload new files.
878 // Permit webdav operations that move existing files around.
880 } else if method == "GET" && !permitDownload {
881 // Disallow downloading file contents.
882 // Permit webdav operations like PROPFIND that retrieve metadata
883 // but not file contents.
889 func (h *handler) logUploadOrDownload(
891 client *arvadosclient.ArvadosClient,
892 fs arvados.CustomFileSystem,
894 collection *arvados.Collection,
895 user *arvados.User) {
897 log := ctxlog.FromContext(r.Context())
898 props := make(map[string]string)
899 props["reqPath"] = r.URL.Path
902 log = log.WithField("user_uuid", user.UUID).
903 WithField("user_full_name", user.FullName)
906 useruuid = fmt.Sprintf("%s-tpzed-anonymouspublic", h.Config.cluster.ClusterID)
908 if collection == nil && fs != nil {
909 collection, filepath = h.determineCollection(fs, filepath)
911 if collection != nil {
912 log = log.WithField("collection_uuid", collection.UUID).
913 WithField("collection_file_path", filepath)
914 props["collection_uuid"] = collection.UUID
915 props["collection_file_path"] = filepath
917 if r.Method == "PUT" || r.Method == "POST" {
918 log.Info("File upload")
919 if h.Config.cluster.Collections.WebDAVLogEvents {
921 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
922 "object_uuid": useruuid,
923 "event_type": "file_upload",
924 "properties": props}}
925 err := client.Create("logs", lr, nil)
927 log.WithError(err).Error("Failed to create upload log event on API server")
931 } else if r.Method == "GET" {
932 if collection != nil && collection.PortableDataHash != "" {
933 log = log.WithField("portable_data_hash", collection.PortableDataHash)
934 props["portable_data_hash"] = collection.PortableDataHash
936 log.Info("File download")
937 if h.Config.cluster.Collections.WebDAVLogEvents {
939 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
940 "object_uuid": useruuid,
941 "event_type": "file_download",
942 "properties": props}}
943 err := client.Create("logs", lr, nil)
945 log.WithError(err).Error("Failed to create download log event on API server")
952 func (h *handler) determineCollection(fs arvados.CustomFileSystem, path string) (*arvados.Collection, string) {
953 segments := strings.Split(path, "/")
955 for i = 0; i < len(segments); i++ {
956 dir := append([]string{}, segments[0:i]...)
957 dir = append(dir, ".arvados#collection")
958 f, err := fs.OpenFile(strings.Join(dir, "/"), os.O_RDONLY, 0)
963 if !os.IsNotExist(err) {
968 // err is nil so we found it.
969 decoder := json.NewDecoder(f)
970 var collection arvados.Collection
971 err = decoder.Decode(&collection)
975 return &collection, strings.Join(segments[i:], "/")