Merge branch '18696-rnaseq-training' refs #18696
[arvados.git] / services / arv-git-httpd / auth_handler.go
index 617c73282f633ac6ddbca83c2094c1acfe8f3f18..13706ae3e83732281e17eb1d397853a3fbb8a548 100644 (file)
@@ -5,31 +5,40 @@
 package main
 
 import (
+       "errors"
        "log"
        "net/http"
        "os"
+       "regexp"
        "strings"
        "sync"
        "time"
 
-       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
-       "git.curoverse.com/arvados.git/sdk/go/auth"
-       "git.curoverse.com/arvados.git/sdk/go/httpserver"
+       "git.arvados.org/arvados.git/sdk/go/arvados"
+       "git.arvados.org/arvados.git/sdk/go/arvadosclient"
+       "git.arvados.org/arvados.git/sdk/go/auth"
+       "git.arvados.org/arvados.git/sdk/go/httpserver"
 )
 
 type authHandler struct {
        handler    http.Handler
        clientPool *arvadosclient.ClientPool
+       cluster    *arvados.Cluster
        setupOnce  sync.Once
 }
 
 func (h *authHandler) setup() {
-       ac, err := arvadosclient.New(&theConfig.Client)
+       client, err := arvados.NewClientFromConfig(h.cluster)
        if err != nil {
                log.Fatal(err)
        }
+
+       ac, err := arvadosclient.New(client)
+       if err != nil {
+               log.Fatalf("Error setting up arvados client prototype %v", err)
+       }
+
        h.clientPool = &arvadosclient.ClientPool{Prototype: ac}
-       log.Printf("%+v", h.clientPool.Prototype)
 }
 
 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
@@ -39,7 +48,7 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
        var statusText string
        var apiToken string
        var repoName string
-       var validApiToken bool
+       var validAPIToken bool
 
        w := httpserver.WrapResponseWriter(wOrig)
 
@@ -71,13 +80,15 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
                        // Nobody has called WriteHeader yet: that
                        // must be our job.
                        w.WriteHeader(statusCode)
-                       w.Write([]byte(statusText))
+                       if statusCode >= 400 {
+                               w.Write([]byte(statusText))
+                       }
                }
 
                // If the given password is a valid token, log the first 10 characters of the token.
                // Otherwise: log the string <invalid> if a password is given, else an empty string.
                passwordToLog := ""
-               if !validApiToken {
+               if !validAPIToken {
                        if len(apiToken) > 0 {
                                passwordToLog = "<invalid>"
                        }
@@ -88,7 +99,7 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
                httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
        }()
 
-       creds := auth.NewCredentialsFromHTTPRequest(r)
+       creds := auth.CredentialsFromRequest(r)
        if len(creds.Tokens) == 0 {
                statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
                w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
@@ -117,27 +128,17 @@ 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 = apiToken
-       reposFound := arvadosclient.Dict{}
-       if err := arv.List("repositories", arvadosclient.Dict{
-               "filters": [][]string{{"name", "=", repoName}},
-       }, &reposFound); err != nil {
+       repoUUID, err := h.lookupRepo(arv, repoName)
+       if err != nil {
                statusCode, statusText = http.StatusInternalServerError, err.Error()
                return
        }
-       validApiToken = true
-       if avail, ok := reposFound["items_available"].(float64); !ok {
-               statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
-               return
-       } else if avail < 1 {
+       validAPIToken = true
+       if repoUUID == "" {
                statusCode, statusText = http.StatusNotFound, "not found"
                return
-       } else if avail > 1 {
-               statusCode, statusText = http.StatusInternalServerError, "name collision"
-               return
        }
 
-       repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
-
        isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
        if !isWrite {
                statusText = "read"
@@ -168,7 +169,7 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
                "/" + repoName + "/.git",
        }
        for _, dir := range tryDirs {
-               if fileInfo, err := os.Stat(theConfig.RepoRoot + dir); err != nil {
+               if fileInfo, err := os.Stat(h.cluster.Git.Repositories + dir); err != nil {
                        if !os.IsNotExist(err) {
                                statusCode, statusText = http.StatusInternalServerError, err.Error()
                                return
@@ -180,7 +181,7 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
        }
        if rewrittenPath == "" {
                log.Println("WARNING:", repoUUID,
-                       "git directory not found in", theConfig.RepoRoot, tryDirs)
+                       "git directory not found in", h.cluster.Git.Repositories, tryDirs)
                // We say "content not found" to disambiguate from the
                // earlier "API says that repo does not exist" error.
                statusCode, statusText = http.StatusNotFound, "content not found"
@@ -190,3 +191,28 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
 
        h.handler.ServeHTTP(w, r)
 }
+
+var uuidRegexp = regexp.MustCompile(`^[0-9a-z]{5}-s0uqq-[0-9a-z]{15}$`)
+
+func (h *authHandler) lookupRepo(arv *arvadosclient.ArvadosClient, repoName string) (string, error) {
+       reposFound := arvadosclient.Dict{}
+       var column string
+       if uuidRegexp.MatchString(repoName) {
+               column = "uuid"
+       } else {
+               column = "name"
+       }
+       err := arv.List("repositories", arvadosclient.Dict{
+               "filters": [][]string{{column, "=", repoName}},
+       }, &reposFound)
+       if err != nil {
+               return "", err
+       } else if avail, ok := reposFound["items_available"].(float64); !ok {
+               return "", errors.New("bad list response from API")
+       } else if avail < 1 {
+               return "", nil
+       } else if avail > 1 {
+               return "", errors.New("name collision")
+       }
+       return reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string), nil
+}