Merge branch '8784-dir-listings'
[arvados.git] / sdk / go / auth / auth.go
index 4a719e922dd8a98bdc88445f413ea88788b01a53..730989b3a371ebcb2874784bbd76f668c22a6db2 100644 (file)
@@ -1,6 +1,11 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: Apache-2.0
+
 package auth
 
 import (
+       "encoding/base64"
        "net/http"
        "net/url"
        "strings"
@@ -20,6 +25,15 @@ func NewCredentialsFromHTTPRequest(r *http.Request) *Credentials {
        return c
 }
 
+// EncodeTokenCookie accepts a token and returns a byte slice suitable
+// for use as a cookie value, such that it will be decoded correctly
+// by LoadTokensFromHTTPRequest.
+var EncodeTokenCookie func([]byte) string = base64.URLEncoding.EncodeToString
+
+// DecodeTokenCookie accepts a cookie value and returns the encoded
+// token.
+var DecodeTokenCookie func(string) ([]byte, error) = base64.URLEncoding.DecodeString
+
 // LoadTokensFromHttpRequest loads all tokens it can find in the
 // headers and query string of an http query.
 func (a *Credentials) LoadTokensFromHTTPRequest(r *http.Request) {
@@ -31,7 +45,7 @@ func (a *Credentials) LoadTokensFromHTTPRequest(r *http.Request) {
 
        // Load base64-encoded token from "Authorization: Basic ..."
        // header (typically used by git via credential helper)
-       if _, password, ok := BasicAuth(r); ok {
+       if _, password, ok := r.BasicAuth(); ok {
                a.Tokens = append(a.Tokens, password)
        }
 
@@ -51,10 +65,24 @@ func (a *Credentials) LoadTokensFromHTTPRequest(r *http.Request) {
                a.Tokens = append(a.Tokens, val...)
        }
 
+       a.loadTokenFromCookie(r)
+
        // TODO: Load token from Rails session cookie (if Rails site
        // secret is known)
 }
 
+func (a *Credentials) loadTokenFromCookie(r *http.Request) {
+       cookie, err := r.Cookie("arvados_api_token")
+       if err != nil || len(cookie.Value) == 0 {
+               return
+       }
+       token, err := DecodeTokenCookie(cookie.Value)
+       if err != nil {
+               return
+       }
+       a.Tokens = append(a.Tokens, string(token))
+}
+
 // TODO: LoadTokensFromHttpRequestBody(). We can't assume in
 // LoadTokensFromHttpRequest() that [or how] we should read and parse
 // the request body. This has to be requested explicitly by the