21700: Install Bundler system-wide in Rails postinst
[arvados.git] / sdk / go / auth / auth.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package auth
6
7 import (
8         "context"
9         "encoding/base64"
10         "net/http"
11         "net/url"
12         "strings"
13 )
14
15 type Credentials struct {
16         Tokens []string
17 }
18
19 func NewCredentials(tokens ...string) *Credentials {
20         return &Credentials{Tokens: tokens}
21 }
22
23 func NewContext(ctx context.Context, c *Credentials) context.Context {
24         return context.WithValue(ctx, contextKeyCredentials{}, c)
25 }
26
27 func FromContext(ctx context.Context) (*Credentials, bool) {
28         c, ok := ctx.Value(contextKeyCredentials{}).(*Credentials)
29         return c, ok
30 }
31
32 func CredentialsFromRequest(r *http.Request) *Credentials {
33         if c, ok := FromContext(r.Context()); ok {
34                 // preloaded by middleware
35                 return c
36         }
37         c := NewCredentials()
38         c.LoadTokensFromHTTPRequest(r)
39         return c
40 }
41
42 // EncodeTokenCookie accepts a token and returns a byte slice suitable
43 // for use as a cookie value, such that it will be decoded correctly
44 // by LoadTokensFromHTTPRequest.
45 var EncodeTokenCookie func([]byte) string = base64.URLEncoding.EncodeToString
46
47 // DecodeTokenCookie accepts a cookie value and returns the encoded
48 // token.
49 var DecodeTokenCookie func(string) ([]byte, error) = base64.URLEncoding.DecodeString
50
51 // LoadTokensFromHTTPRequest loads all tokens it can find in the
52 // headers and query string of an http query.
53 func (a *Credentials) LoadTokensFromHTTPRequest(r *http.Request) {
54         // Load plain token from "Authorization: OAuth2 ..." header
55         // (typically used by smart API clients)
56         if toks := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(toks) == 2 && (toks[0] == "OAuth2" || toks[0] == "Bearer") {
57                 a.Tokens = append(a.Tokens, strings.TrimSpace(toks[1]))
58         }
59
60         // Load base64-encoded token from "Authorization: Basic ..."
61         // header (typically used by git via credential helper)
62         if _, password, ok := r.BasicAuth(); ok {
63                 a.Tokens = append(a.Tokens, strings.TrimSpace(password))
64         }
65
66         // Load tokens from query string. It's generally not a good
67         // idea to pass tokens around this way, but passing a narrowly
68         // scoped token is a reasonable way to implement "secret link
69         // to an object" in a generic way.
70         //
71         // ParseQuery always returns a non-nil map which might have
72         // valid parameters, even when a decoding error causes it to
73         // return a non-nil err. We ignore err; hopefully the caller
74         // will also need to parse the query string for
75         // application-specific purposes and will therefore
76         // find/report decoding errors in a suitable way.
77         qvalues, _ := url.ParseQuery(r.URL.RawQuery)
78         if val, ok := qvalues["api_token"]; ok {
79                 for _, token := range val {
80                         a.Tokens = append(a.Tokens, strings.TrimSpace(token))
81                 }
82         }
83
84         a.loadTokenFromCookie(r)
85
86         // TODO: Load token from Rails session cookie (if Rails site
87         // secret is known)
88 }
89
90 func (a *Credentials) loadTokenFromCookie(r *http.Request) {
91         cookie, err := r.Cookie("arvados_api_token")
92         if err != nil || len(cookie.Value) == 0 {
93                 return
94         }
95         token, err := DecodeTokenCookie(cookie.Value)
96         if err != nil {
97                 return
98         }
99         a.Tokens = append(a.Tokens, strings.TrimSpace(string(token)))
100 }
101
102 // LoadTokensFromHTTPRequestBody loads credentials from the request
103 // body.
104 //
105 // This is separate from LoadTokensFromHTTPRequest() because it's not
106 // always desirable to read the request body. This has to be requested
107 // explicitly by the application.
108 func (a *Credentials) LoadTokensFromHTTPRequestBody(r *http.Request) error {
109         if r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" {
110                 return nil
111         }
112         if err := r.ParseForm(); err != nil {
113                 return err
114         }
115         if t := r.PostFormValue("api_token"); t != "" {
116                 a.Tokens = append(a.Tokens, strings.TrimSpace(t))
117         }
118         return nil
119 }