Merge branch 'master' into 6507-node-manager-azure
[arvados.git] / services / arv-git-httpd / auth_handler.go
1 package main
2
3 import (
4         "log"
5         "net/http"
6         "os"
7         "strings"
8         "time"
9
10         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11         "git.curoverse.com/arvados.git/sdk/go/auth"
12         "git.curoverse.com/arvados.git/sdk/go/httpserver"
13 )
14
15 var clientPool = arvadosclient.MakeClientPool()
16
17 type authHandler struct {
18         handler http.Handler
19 }
20
21 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
22         var statusCode int
23         var statusText string
24         var apiToken string
25         var repoName string
26         var validApiToken bool
27
28         w := httpserver.WrapResponseWriter(wOrig)
29
30         defer func() {
31                 if w.WroteStatus() == 0 {
32                         // Nobody has called WriteHeader yet: that
33                         // must be our job.
34                         w.WriteHeader(statusCode)
35                         w.Write([]byte(statusText))
36                 }
37
38                 // If the given password is a valid token, log the first 10 characters of the token.
39                 // Otherwise: log the string <invalid> if a password is given, else an empty string.
40                 passwordToLog := ""
41                 if !validApiToken {
42                         if len(apiToken) > 0 {
43                                 passwordToLog = "<invalid>"
44                         }
45                 } else {
46                         passwordToLog = apiToken[0:10]
47                 }
48
49                 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
50         }()
51
52         creds := auth.NewCredentialsFromHTTPRequest(r)
53         if len(creds.Tokens) == 0 {
54                 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
55                 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
56                 return
57         }
58         apiToken = creds.Tokens[0]
59
60         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
61         // protected by the permissions on the repository named
62         // "foo/bar".
63         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
64         if len(pathParts) != 2 {
65                 statusCode, statusText = http.StatusBadRequest, "bad request"
66                 return
67         }
68         repoName = pathParts[0]
69         repoName = strings.TrimRight(repoName, "/")
70
71         arv := clientPool.Get()
72         if arv == nil {
73                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+clientPool.Err().Error()
74                 return
75         }
76         defer clientPool.Put(arv)
77
78         // Ask API server whether the repository is readable using
79         // this token (by trying to read it!)
80         arv.ApiToken = apiToken
81         reposFound := arvadosclient.Dict{}
82         if err := arv.List("repositories", arvadosclient.Dict{
83                 "filters": [][]string{{"name", "=", repoName}},
84         }, &reposFound); err != nil {
85                 statusCode, statusText = http.StatusInternalServerError, err.Error()
86                 return
87         }
88         validApiToken = true
89         if avail, ok := reposFound["items_available"].(float64); !ok {
90                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
91                 return
92         } else if avail < 1 {
93                 statusCode, statusText = http.StatusNotFound, "not found"
94                 return
95         } else if avail > 1 {
96                 statusCode, statusText = http.StatusInternalServerError, "name collision"
97                 return
98         }
99
100         repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
101
102         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
103         if !isWrite {
104                 statusText = "read"
105         } else {
106                 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
107                         "repository": arvadosclient.Dict{
108                                 "modified_at": time.Now().String(),
109                         },
110                 }, &arvadosclient.Dict{})
111                 if err != nil {
112                         statusCode, statusText = http.StatusForbidden, err.Error()
113                         return
114                 }
115                 statusText = "write"
116         }
117
118         // Regardless of whether the client asked for "/foo.git" or
119         // "/foo/.git", we choose whichever variant exists in our repo
120         // root, and we try {uuid}.git and {uuid}/.git first. If none
121         // of these exist, we 404 even though the API told us the repo
122         // _should_ exist (presumably this means the repo was just
123         // created, and gitolite sync hasn't run yet).
124         rewrittenPath := ""
125         tryDirs := []string{
126                 "/" + repoUUID + ".git",
127                 "/" + repoUUID + "/.git",
128                 "/" + repoName + ".git",
129                 "/" + repoName + "/.git",
130         }
131         for _, dir := range tryDirs {
132                 if fileInfo, err := os.Stat(theConfig.Root + dir); err != nil {
133                         if !os.IsNotExist(err) {
134                                 statusCode, statusText = http.StatusInternalServerError, err.Error()
135                                 return
136                         }
137                 } else if fileInfo.IsDir() {
138                         rewrittenPath = dir + "/" + pathParts[1]
139                         break
140                 }
141         }
142         if rewrittenPath == "" {
143                 log.Println("WARNING:", repoUUID,
144                         "git directory not found in", theConfig.Root, tryDirs)
145                 // We say "content not found" to disambiguate from the
146                 // earlier "API says that repo does not exist" error.
147                 statusCode, statusText = http.StatusNotFound, "content not found"
148                 return
149         }
150         r.URL.Path = rewrittenPath
151
152         h.handler.ServeHTTP(&w, r)
153 }