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 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
67 // PDH (even if it is a PDH with "+" replaced by " " or "-");
69 func parseCollectionIDFromURL(s string) string {
70 if arvadosclient.UUIDMatch(s) {
73 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
79 func (h *handler) setup() {
80 // Errors will be handled at the client pool.
81 arv, _ := arvados.NewClientFromConfig(h.Config.cluster)
82 h.clientPool = arvadosclient.MakeClientPoolWith(arv)
84 keepclient.RefreshServiceDiscoveryOnSIGHUP()
85 keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
87 h.healthHandler = &health.Handler{
88 Token: h.Config.cluster.ManagementToken,
92 // Even though we don't accept LOCK requests, every webdav
93 // handler must have a non-nil LockSystem.
94 h.webdavLS = &noLockSystem{}
97 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
98 json.NewEncoder(w).Encode(struct{ Version string }{version})
101 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
102 // sends an HTTP header indicating success, updateOnSuccess first
103 // calls the provided update func. If the update func fails, a 500
104 // response is sent, and the status code and body sent by the handler
105 // are ignored (all response writes return the update error).
106 type updateOnSuccess struct {
107 httpserver.ResponseWriter
108 logger logrus.FieldLogger
114 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
116 uos.WriteHeader(http.StatusOK)
121 return uos.ResponseWriter.Write(p)
124 func (uos *updateOnSuccess) WriteHeader(code int) {
126 uos.sentHeader = true
127 if code >= 200 && code < 400 {
128 if uos.err = uos.update(); uos.err != nil {
129 code := http.StatusInternalServerError
130 if err, ok := uos.err.(*arvados.TransactionError); ok {
131 code = err.StatusCode
133 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
134 http.Error(uos.ResponseWriter, uos.err.Error(), code)
139 uos.ResponseWriter.WriteHeader(code)
143 corsAllowHeadersHeader = strings.Join([]string{
144 "Authorization", "Content-Type", "Range",
145 // WebDAV request headers:
146 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
148 writeMethod = map[string]bool{
159 webdavMethod = map[string]bool{
172 browserMethod = map[string]bool{
177 // top-level dirs to serve with siteFS
178 siteFSDir = map[string]bool{
179 "": true, // root directory
185 // ServeHTTP implements http.Handler.
186 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
187 h.setupOnce.Do(h.setup)
189 remoteAddr := r.RemoteAddr
190 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
191 remoteAddr = xff + "," + remoteAddr
193 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
197 w := httpserver.WrapResponseWriter(wOrig)
199 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
200 h.healthHandler.ServeHTTP(w, r)
204 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
205 if !browserMethod[method] && !webdavMethod[method] {
206 w.WriteHeader(http.StatusMethodNotAllowed)
209 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
210 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
211 w.Header().Set("Access-Control-Allow-Origin", "*")
212 w.Header().Set("Access-Control-Max-Age", "86400")
216 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
217 w.WriteHeader(http.StatusMethodNotAllowed)
221 if r.Header.Get("Origin") != "" {
222 // Allow simple cross-origin requests without user
223 // credentials ("user credentials" as defined by CORS,
224 // i.e., cookies, HTTP authentication, and client-side
225 // SSL certificates. See
226 // http://www.w3.org/TR/cors/#user-credentials).
227 w.Header().Set("Access-Control-Allow-Origin", "*")
228 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
231 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
232 split := strings.SplitN(auth[4:], ":", 2)
234 w.WriteHeader(http.StatusUnauthorized)
237 h.serveS3(w, r, split[0])
239 } else if strings.HasPrefix(auth, "AWS4-HMAC-SHA256 ") {
240 w.WriteHeader(http.StatusBadRequest)
241 fmt.Println(w, "V4 signature is not supported")
245 pathParts := strings.Split(r.URL.Path[1:], "/")
248 var collectionID string
250 var reqTokens []string
254 credentialsOK := h.Config.cluster.Collections.TrustAllContent
256 if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
259 } else if r.FormValue("disposition") == "attachment" {
263 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
264 // http://ID.collections.example/PATH...
266 } else if r.URL.Path == "/status.json" {
269 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
270 h.MetricsAPI.ServeHTTP(w, r)
272 } else if siteFSDir[pathParts[0]] {
274 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
276 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
278 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
279 if len(pathParts) >= 4 && pathParts[1] == "download" {
280 // /collections/download/ID/TOKEN/PATH...
281 collectionID = parseCollectionIDFromURL(pathParts[2])
282 tokens = []string{pathParts[3]}
286 // /collections/ID/PATH...
287 collectionID = parseCollectionIDFromURL(pathParts[1])
289 // This path is only meant to work for public
290 // data. Tokens provided with the request are
292 credentialsOK = false
296 if collectionID == "" && !useSiteFS {
297 w.WriteHeader(http.StatusNotFound)
302 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
307 reqTokens = auth.CredentialsFromRequest(r).Tokens
310 formToken := r.FormValue("api_token")
311 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
312 // The client provided an explicit token in the POST
313 // body. The Origin header indicates this *might* be
314 // an AJAX request, in which case redirect-with-cookie
315 // won't work: we should just serve the content in the
316 // POST response. This is safe because:
318 // * We're supplying an attachment, not inline
319 // content, so we don't need to convert the POST to
320 // a GET and avoid the "really resubmit form?"
323 // * The token isn't embedded in the URL, so we don't
324 // need to worry about bookmarks and copy/paste.
325 reqTokens = append(reqTokens, formToken)
326 } else if formToken != "" && browserMethod[r.Method] {
327 // The client provided an explicit token in the query
328 // string, or a form in POST body. We must put the
329 // token in an HttpOnly cookie, and redirect to the
330 // same URL with the query param redacted and method =
332 h.seeOtherWithCookie(w, r, "", credentialsOK)
337 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
341 targetPath := pathParts[stripParts:]
342 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
343 // http://ID.example/t=TOKEN/PATH...
344 // /c=ID/t=TOKEN/PATH...
346 // This form must only be used to pass scoped tokens
347 // that give permission for a single collection. See
348 // FormValue case above.
349 tokens = []string{targetPath[0][2:]}
351 targetPath = targetPath[1:]
356 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
359 if len(targetPath) > 0 && targetPath[0] == "_" {
360 // If a collection has a directory called "t=foo" or
361 // "_", it can be served at
362 // //collections.example/_/t=foo/ or
363 // //collections.example/_/_/ respectively:
364 // //collections.example/t=foo/ won't work because
365 // t=foo will be interpreted as a token "foo".
366 targetPath = targetPath[1:]
370 arv := h.clientPool.Get()
372 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
375 defer h.clientPool.Put(arv)
377 var collection *arvados.Collection
378 tokenResult := make(map[string]int)
379 for _, arv.ApiToken = range tokens {
381 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
386 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
387 switch srvErr.HttpStatusCode {
389 // Token broken or insufficient to
390 // retrieve collection
391 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
395 // Something more serious is wrong
396 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
399 if collection == nil {
400 if pathToken || !credentialsOK {
401 // Either the URL is a "secret sharing link"
402 // that didn't work out (and asking the client
403 // for additional credentials would just be
404 // confusing), or we don't even accept
405 // credentials at this path.
406 w.WriteHeader(http.StatusNotFound)
409 for _, t := range reqTokens {
410 if tokenResult[t] == 404 {
411 // The client provided valid token(s), but the
412 // collection was not found.
413 w.WriteHeader(http.StatusNotFound)
417 // The client's token was invalid (e.g., expired), or
418 // the client didn't even provide one. Propagate the
419 // 401 to encourage the client to use a [different]
422 // TODO(TC): This response would be confusing to
423 // someone trying (anonymously) to download public
424 // data that has been deleted. Allow a referrer to
425 // provide this context somehow?
426 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
427 w.WriteHeader(http.StatusUnauthorized)
431 kc, err := keepclient.MakeKeepClient(arv)
433 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
436 kc.RequestID = r.Header.Get("X-Request-Id")
439 if len(targetPath) > 0 {
440 basename = targetPath[len(targetPath)-1]
442 applyContentDispositionHdr(w, r, basename, attachment)
444 client := (&arvados.Client{
445 APIHost: arv.ApiServer,
446 AuthToken: arv.ApiToken,
447 Insecure: arv.ApiInsecure,
448 }).WithRequestID(r.Header.Get("X-Request-Id"))
450 fs, err := collection.FileSystem(client, kc)
452 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
456 writefs, writeOK := fs.(arvados.CollectionFileSystem)
457 targetIsPDH := arvadosclient.PDHMatch(collectionID)
458 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
459 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
463 if webdavMethod[r.Method] {
464 if writeMethod[r.Method] {
465 // Save the collection only if/when all
466 // webdav->filesystem operations succeed --
467 // and send a 500 error if the modified
468 // collection can't be saved.
469 w = &updateOnSuccess{
471 logger: ctxlog.FromContext(r.Context()),
472 update: func() error {
473 return h.Config.Cache.Update(client, *collection, writefs)
477 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
478 FileSystem: &webdavFS{
480 writing: writeMethod[r.Method],
481 alwaysReadEOF: r.Method == "PROPFIND",
483 LockSystem: h.webdavLS,
484 Logger: func(_ *http.Request, err error) {
486 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
494 openPath := "/" + strings.Join(targetPath, "/")
495 if f, err := fs.Open(openPath); os.IsNotExist(err) {
496 // Requested non-existent path
497 w.WriteHeader(http.StatusNotFound)
498 } else if err != nil {
499 // Some other (unexpected) error
500 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
501 } else if stat, err := f.Stat(); err != nil {
502 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
503 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
504 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
505 // If client requests ".../dirname", redirect to
506 // ".../dirname/". This way, relative links in the
507 // listing for "dirname" can always be "fnm", never
509 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
510 } else if stat.IsDir() {
511 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
513 http.ServeContent(w, r, basename, stat.ModTime(), f)
514 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
515 // If we wrote fewer bytes than expected, it's
516 // too late to change the real response code
517 // or send an error message to the client, but
518 // at least we can try to put some useful
519 // debugging info in the logs.
520 n, err := f.Read(make([]byte, 1024))
521 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
527 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
528 arv = h.clientPool.Get()
530 return nil, nil, nil, nil, err
532 release = func() { h.clientPool.Put(arv) }
534 kc, err = keepclient.MakeKeepClient(arv)
540 client = (&arvados.Client{
541 APIHost: arv.ApiServer,
542 AuthToken: arv.ApiToken,
543 Insecure: arv.ApiInsecure,
544 }).WithRequestID(reqID)
548 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request, token string) {
549 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
551 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
556 r.URL.Path = "/by_id" + r.URL.Path
558 fs := client.SiteFileSystem(kc)
559 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
563 fi, err := fs.Stat(r.URL.Path)
564 if os.IsNotExist(err) {
565 http.Error(w, err.Error(), http.StatusNotFound)
567 } else if err != nil {
568 http.Error(w, err.Error(), http.StatusInternalServerError)
570 } else if fi.IsDir() {
571 http.Error(w, "not found", http.StatusNotFound)
573 http.FileServer(fs).ServeHTTP(w, r)
576 f, err := fs.OpenFile(r.URL.Path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
577 if os.IsNotExist(err) {
578 // create missing intermediate directories, then try again
579 for i, c := range r.URL.Path {
580 if i > 0 && c == '/' {
581 dir := r.URL.Path[:i]
582 err := fs.Mkdir(dir, 0755)
583 if err != nil && err != os.ErrExist {
584 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
585 http.Error(w, err.Error(), http.StatusInternalServerError)
590 f, err = fs.OpenFile(r.URL.Path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
593 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
594 http.Error(w, err.Error(), http.StatusBadRequest)
598 _, err = io.Copy(f, r.Body)
600 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
601 http.Error(w, err.Error(), http.StatusBadGateway)
606 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
607 http.Error(w, err.Error(), http.StatusBadGateway)
612 err = fmt.Errorf("sync failed: %w", err)
613 http.Error(w, err.Error(), http.StatusInternalServerError)
616 w.WriteHeader(http.StatusOK)
619 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
624 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
625 if len(tokens) == 0 {
626 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
627 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
630 if writeMethod[r.Method] {
631 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
634 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), tokens[0])
636 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
641 fs := client.SiteFileSystem(kc)
642 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
643 f, err := fs.Open(r.URL.Path)
644 if os.IsNotExist(err) {
645 http.Error(w, err.Error(), http.StatusNotFound)
647 } else if err != nil {
648 http.Error(w, err.Error(), http.StatusInternalServerError)
652 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
653 if !strings.HasSuffix(r.URL.Path, "/") {
654 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
656 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
660 if r.Method == "GET" {
661 _, basename := filepath.Split(r.URL.Path)
662 applyContentDispositionHdr(w, r, basename, attachment)
664 wh := webdav.Handler{
666 FileSystem: &webdavFS{
668 writing: writeMethod[r.Method],
669 alwaysReadEOF: r.Method == "PROPFIND",
671 LockSystem: h.webdavLS,
672 Logger: func(_ *http.Request, err error) {
674 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
681 var dirListingTemplate = `<!DOCTYPE HTML>
683 <META name="robots" content="NOINDEX">
684 <TITLE>{{ .CollectionName }}</TITLE>
685 <STYLE type="text/css">
690 background-color: #D9EDF7;
691 border-radius: .25em;
702 font-family: monospace;
709 <H1>{{ .CollectionName }}</H1>
711 <P>This collection of data files is being shared with you through
712 Arvados. You can download individual files listed below. To download
713 the entire directory tree with wget, try:</P>
715 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
717 <H2>File Listing</H2>
723 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
725 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
730 <P>(No files; this collection is empty.)</P>
737 Arvados is a free and open source software bioinformatics platform.
738 To learn more, visit arvados.org.
739 Arvados is not responsible for the files listed on this page.
746 type fileListEnt struct {
752 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
753 var files []fileListEnt
754 var walk func(string) error
755 if !strings.HasSuffix(base, "/") {
758 walk = func(path string) error {
759 dirname := base + path
761 dirname = strings.TrimSuffix(dirname, "/")
763 d, err := fs.Open(dirname)
767 ents, err := d.Readdir(-1)
771 for _, ent := range ents {
772 if recurse && ent.IsDir() {
773 err = walk(path + ent.Name() + "/")
778 files = append(files, fileListEnt{
779 Name: path + ent.Name(),
787 if err := walk(""); err != nil {
788 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
792 funcs := template.FuncMap{
793 "nbsp": func(s string) template.HTML {
794 return template.HTML(strings.Replace(s, " ", " ", -1))
797 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
799 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
802 sort.Slice(files, func(i, j int) bool {
803 return files[i].Name < files[j].Name
805 w.WriteHeader(http.StatusOK)
806 tmpl.Execute(w, map[string]interface{}{
807 "CollectionName": collectionName,
810 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
814 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
815 disposition := "inline"
817 disposition = "attachment"
819 if strings.ContainsRune(r.RequestURI, '?') {
820 // Help the UA realize that the filename is just
821 // "filename.txt", not
822 // "filename.txt?disposition=attachment".
824 // TODO(TC): Follow advice at RFC 6266 appendix D
825 disposition += "; filename=" + strconv.QuoteToASCII(filename)
827 if disposition != "inline" {
828 w.Header().Set("Content-Disposition", disposition)
832 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
833 if formToken := r.FormValue("api_token"); formToken != "" {
835 // It is not safe to copy the provided token
836 // into a cookie unless the current vhost
837 // (origin) serves only a single collection or
838 // we are in TrustAllContent mode.
839 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)
843 // The HttpOnly flag is necessary to prevent
844 // JavaScript code (included in, or loaded by, a page
845 // in the collection being served) from employing the
846 // user's token beyond reading other files in the same
847 // domain, i.e., same collection.
849 // The 303 redirect is necessary in the case of a GET
850 // request to avoid exposing the token in the Location
851 // bar, and in the case of a POST request to avoid
852 // raising warnings when the user refreshes the
854 http.SetCookie(w, &http.Cookie{
855 Name: "arvados_api_token",
856 Value: auth.EncodeTokenCookie([]byte(formToken)),
862 // Propagate query parameters (except api_token) from
863 // the original request.
864 redirQuery := r.URL.Query()
865 redirQuery.Del("api_token")
869 newu, err := u.Parse(location)
871 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
877 Scheme: r.URL.Scheme,
880 RawQuery: redirQuery.Encode(),
883 w.Header().Add("Location", redir)
884 w.WriteHeader(http.StatusSeeOther)
885 io.WriteString(w, `<A href="`)
886 io.WriteString(w, html.EscapeString(redir))
887 io.WriteString(w, `">Continue</A>`)