5824: Move request auth code into an SDK package. Support more ways of passing tokens.
authorTom Clegg <tom@curoverse.com>
Thu, 21 May 2015 04:33:56 +0000 (00:33 -0400)
committerTom Clegg <tom@curoverse.com>
Tue, 11 Aug 2015 00:25:44 +0000 (20:25 -0400)
sdk/go/auth/auth.go [new file with mode: 0644]
sdk/go/auth/basic_auth_go13.go [moved from services/arv-git-httpd/basic_auth_go13.go with 97% similarity]
sdk/go/auth/basic_auth_go14.go [moved from services/arv-git-httpd/basic_auth_go14.go with 91% similarity]
sdk/go/auth/basic_auth_test.go [moved from services/arv-git-httpd/basic_auth_test.go with 98% similarity]
services/arv-git-httpd/auth_handler.go

diff --git a/sdk/go/auth/auth.go b/sdk/go/auth/auth.go
new file mode 100644 (file)
index 0000000..4a719e9
--- /dev/null
@@ -0,0 +1,61 @@
+package auth
+
+import (
+       "net/http"
+       "net/url"
+       "strings"
+)
+
+type Credentials struct {
+       Tokens []string
+}
+
+func NewCredentials() *Credentials {
+       return &Credentials{Tokens: []string{}}
+}
+
+func NewCredentialsFromHTTPRequest(r *http.Request) *Credentials {
+       c := NewCredentials()
+       c.LoadTokensFromHTTPRequest(r)
+       return c
+}
+
+// LoadTokensFromHttpRequest loads all tokens it can find in the
+// headers and query string of an http query.
+func (a *Credentials) LoadTokensFromHTTPRequest(r *http.Request) {
+       // Load plain token from "Authorization: OAuth2 ..." header
+       // (typically used by smart API clients)
+       if toks := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(toks) == 2 && toks[0] == "OAuth2" {
+               a.Tokens = append(a.Tokens, toks[1])
+       }
+
+       // Load base64-encoded token from "Authorization: Basic ..."
+       // header (typically used by git via credential helper)
+       if _, password, ok := BasicAuth(r); ok {
+               a.Tokens = append(a.Tokens, password)
+       }
+
+       // Load tokens from query string. It's generally not a good
+       // idea to pass tokens around this way, but passing a narrowly
+       // scoped token is a reasonable way to implement "secret link
+       // to an object" in a generic way.
+       //
+       // ParseQuery always returns a non-nil map which might have
+       // valid parameters, even when a decoding error causes it to
+       // return a non-nil err. We ignore err; hopefully the caller
+       // will also need to parse the query string for
+       // application-specific purposes and will therefore
+       // find/report decoding errors in a suitable way.
+       qvalues, _ := url.ParseQuery(r.URL.RawQuery)
+       if val, ok := qvalues["api_token"]; ok {
+               a.Tokens = append(a.Tokens, val...)
+       }
+
+       // TODO: Load token from Rails session cookie (if Rails site
+       // secret is known)
+}
+
+// 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
+// application.
similarity index 97%
rename from services/arv-git-httpd/basic_auth_go13.go
rename to sdk/go/auth/basic_auth_go13.go
index 087f2c891166cd52256c77ad1d7d72304f01ddfe..c0fe5fc3445defd5e9c43ef1c587f3d985fe9219 100644 (file)
@@ -1,6 +1,6 @@
 // +build !go1.4
 
-package main
+package auth
 
 import (
        "encoding/base64"
similarity index 91%
rename from services/arv-git-httpd/basic_auth_go14.go
rename to sdk/go/auth/basic_auth_go14.go
index 6a0079ab5c0a57a4a2c383fa1c195445b39b1326..aeedb066c783a781c4c188c11130705e19741044 100644 (file)
@@ -1,6 +1,6 @@
 // +build go1.4
 
-package main
+package auth
 
 import (
        "net/http"
similarity index 98%
rename from services/arv-git-httpd/basic_auth_test.go
rename to sdk/go/auth/basic_auth_test.go
index 2bd84dc82e99e5ce28e44596d9531d9d1c995396..935f696120f4aa38019883b0fed8589097c4ffc0 100644 (file)
@@ -1,4 +1,4 @@
-package main
+package auth
 
 import (
        "net/http"
index 116535496893555e973dd503e02432df1f86f1d5..ebda2a4a9b5537148e0562dbf05f7e67eba5016e 100644 (file)
@@ -9,6 +9,7 @@ import (
        "sync"
        "time"
 
+       "git.curoverse.com/arvados.git/sdk/go/auth"
        "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
 )
 
@@ -40,7 +41,7 @@ type authHandler struct {
 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
        var statusCode int
        var statusText string
-       var username, password string
+       var apiToken string
        var repoName string
        var wroteStatus int
        var validApiToken bool
@@ -49,7 +50,8 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
 
        defer func() {
                if wroteStatus == 0 {
-                       // Nobody has called WriteHeader yet: that must be our job.
+                       // Nobody has called WriteHeader yet: that
+                       // must be our job.
                        w.WriteHeader(statusCode)
                        w.Write([]byte(statusText))
                }
@@ -58,24 +60,23 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
                // Otherwise: log the string <invalid> if a password is given, else an empty string.
                passwordToLog := ""
                if !validApiToken {
-                       if len(password) > 0 {
+                       if len(apiToken) > 0 {
                                passwordToLog = "<invalid>"
                        }
                } else {
-                       passwordToLog = password[0:10]
+                       passwordToLog = apiToken[0:10]
                }
 
-               log.Println(quoteStrings(r.RemoteAddr, username, passwordToLog, wroteStatus, statusText, repoName, r.Method, r.URL.Path)...)
+               log.Println(quoteStrings(r.RemoteAddr, passwordToLog, wroteStatus, statusText, repoName, r.Method, r.URL.Path)...)
        }()
 
-       // HTTP request username is logged, but unused. Password is an
-       // Arvados API token.
-       username, password, ok := BasicAuth(r)
-       if !ok || username == "" || password == "" {
+       creds := auth.NewCredentialsFromHTTPRequest(r)
+       if len(creds.Tokens) == 0 {
                statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
                w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
                return
        }
+       apiToken = creds.Tokens[0]
 
        // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
        // protected by the permissions on the repository named
@@ -97,7 +98,7 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
 
        // Ask API server whether the repository is readable using
        // this token (by trying to read it!)
-       arv.ApiToken = password
+       arv.ApiToken = apiToken
        reposFound := arvadosclient.Dict{}
        if err := arv.List("repositories", arvadosclient.Dict{
                "filters": [][]string{{"name", "=", repoName}},