1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
14 type Credentials struct {
18 func NewCredentials() *Credentials {
19 return &Credentials{Tokens: []string{}}
22 func NewCredentialsFromHTTPRequest(r *http.Request) *Credentials {
24 c.LoadTokensFromHTTPRequest(r)
28 // EncodeTokenCookie accepts a token and returns a byte slice suitable
29 // for use as a cookie value, such that it will be decoded correctly
30 // by LoadTokensFromHTTPRequest.
31 var EncodeTokenCookie func([]byte) string = base64.URLEncoding.EncodeToString
33 // DecodeTokenCookie accepts a cookie value and returns the encoded
35 var DecodeTokenCookie func(string) ([]byte, error) = base64.URLEncoding.DecodeString
37 // LoadTokensFromHttpRequest loads all tokens it can find in the
38 // headers and query string of an http query.
39 func (a *Credentials) LoadTokensFromHTTPRequest(r *http.Request) {
40 // Load plain token from "Authorization: OAuth2 ..." header
41 // (typically used by smart API clients)
42 if toks := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(toks) == 2 && (toks[0] == "OAuth2" || toks[0] == "Bearer") {
43 a.Tokens = append(a.Tokens, toks[1])
46 // Load base64-encoded token from "Authorization: Basic ..."
47 // header (typically used by git via credential helper)
48 if _, password, ok := r.BasicAuth(); ok {
49 a.Tokens = append(a.Tokens, password)
52 // Load tokens from query string. It's generally not a good
53 // idea to pass tokens around this way, but passing a narrowly
54 // scoped token is a reasonable way to implement "secret link
55 // to an object" in a generic way.
57 // ParseQuery always returns a non-nil map which might have
58 // valid parameters, even when a decoding error causes it to
59 // return a non-nil err. We ignore err; hopefully the caller
60 // will also need to parse the query string for
61 // application-specific purposes and will therefore
62 // find/report decoding errors in a suitable way.
63 qvalues, _ := url.ParseQuery(r.URL.RawQuery)
64 if val, ok := qvalues["api_token"]; ok {
65 a.Tokens = append(a.Tokens, val...)
68 a.loadTokenFromCookie(r)
70 // TODO: Load token from Rails session cookie (if Rails site
74 func (a *Credentials) loadTokenFromCookie(r *http.Request) {
75 cookie, err := r.Cookie("arvados_api_token")
76 if err != nil || len(cookie.Value) == 0 {
79 token, err := DecodeTokenCookie(cookie.Value)
83 a.Tokens = append(a.Tokens, string(token))
86 // TODO: LoadTokensFromHttpRequestBody(). We can't assume in
87 // LoadTokensFromHttpRequest() that [or how] we should read and parse
88 // the request body. This has to be requested explicitly by the