6827: add a comment that only the first 10 characters of a valid token are logged.
[arvados.git] / services / arv-git-httpd / auth_handler.go
1 package main
2
3 import (
4         "log"
5         "net/http"
6         "net/http/cgi"
7         "os"
8         "strings"
9         "sync"
10         "time"
11
12         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
13 )
14
15 func newArvadosClient() interface{} {
16         arv, err := arvadosclient.MakeArvadosClient()
17         if err != nil {
18                 log.Println("MakeArvadosClient:", err)
19                 return nil
20         }
21         return &arv
22 }
23
24 var connectionPool = &sync.Pool{New: newArvadosClient}
25
26 type spyingResponseWriter struct {
27         http.ResponseWriter
28         wroteStatus *int
29 }
30
31 func (w spyingResponseWriter) WriteHeader(s int) {
32         *w.wroteStatus = s
33         w.ResponseWriter.WriteHeader(s)
34 }
35
36 type authHandler struct {
37         handler *cgi.Handler
38 }
39
40 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
41         var statusCode int
42         var statusText string
43         var username, password string
44         var repoName string
45         var wroteStatus int
46
47         w := spyingResponseWriter{wOrig, &wroteStatus}
48
49         defer func() {
50                 if wroteStatus == 0 {
51                         // Nobody has called WriteHeader yet: that must be our job.
52                         w.WriteHeader(statusCode)
53                         w.Write([]byte(statusText))
54                 }
55
56     // If the given password is a valid token, log the first 10 characters of the token.
57     // Otherwise: log the string <invalid> if a password is given, else an empty string.
58                 passwordToLog := ""
59                 if statusCode == 401 || strings.Contains(statusText, "Unauthorized") {
60                         if len(password) > 0 {
61                                 passwordToLog = "<invalid>"
62                         }
63                 } else {
64                         passwordToLog = password[0:10]
65                 }
66
67                 log.Println(quoteStrings(r.RemoteAddr, username, passwordToLog, wroteStatus, statusText, repoName, r.Method, r.URL.Path)...)
68         }()
69
70         // HTTP request username is logged, but unused. Password is an
71         // Arvados API token.
72         username, password, ok := BasicAuth(r)
73         if !ok || username == "" || password == "" {
74                 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
75                 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
76                 return
77         }
78
79         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
80         // protected by the permissions on the repository named
81         // "foo/bar".
82         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
83         if len(pathParts) != 2 {
84                 statusCode, statusText = http.StatusBadRequest, "bad request"
85                 return
86         }
87         repoName = pathParts[0]
88         repoName = strings.TrimRight(repoName, "/")
89
90         arv, ok := connectionPool.Get().(*arvadosclient.ArvadosClient)
91         if !ok || arv == nil {
92                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed"
93                 return
94         }
95         defer connectionPool.Put(arv)
96
97         // Ask API server whether the repository is readable using
98         // this token (by trying to read it!)
99         arv.ApiToken = password
100         reposFound := arvadosclient.Dict{}
101         if err := arv.List("repositories", arvadosclient.Dict{
102                 "filters": [][]string{{"name", "=", repoName}},
103         }, &reposFound); err != nil {
104                 statusCode, statusText = http.StatusInternalServerError, err.Error()
105                 return
106         }
107         if avail, ok := reposFound["items_available"].(float64); !ok {
108                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
109                 return
110         } else if avail < 1 {
111                 statusCode, statusText = http.StatusNotFound, "not found"
112                 return
113         } else if avail > 1 {
114                 statusCode, statusText = http.StatusInternalServerError, "name collision"
115                 return
116         }
117
118         repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
119
120         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
121         if !isWrite {
122                 statusText = "read"
123         } else {
124                 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
125                         "repository": arvadosclient.Dict{
126                                 "modified_at": time.Now().String(),
127                         },
128                 }, &arvadosclient.Dict{})
129                 if err != nil {
130                         statusCode, statusText = http.StatusForbidden, err.Error()
131                         return
132                 }
133                 statusText = "write"
134         }
135
136         // Regardless of whether the client asked for "/foo.git" or
137         // "/foo/.git", we choose whichever variant exists in our repo
138         // root, and we try {uuid}.git and {uuid}/.git first. If none
139         // of these exist, we 404 even though the API told us the repo
140         // _should_ exist (presumably this means the repo was just
141         // created, and gitolite sync hasn't run yet).
142         rewrittenPath := ""
143         tryDirs := []string{
144                 "/" + repoUUID + ".git",
145                 "/" + repoUUID + "/.git",
146                 "/" + repoName + ".git",
147                 "/" + repoName + "/.git",
148         }
149         for _, dir := range tryDirs {
150                 if fileInfo, err := os.Stat(theConfig.Root + dir); err != nil {
151                         if !os.IsNotExist(err) {
152                                 statusCode, statusText = http.StatusInternalServerError, err.Error()
153                                 return
154                         }
155                 } else if fileInfo.IsDir() {
156                         rewrittenPath = dir + "/" + pathParts[1]
157                         break
158                 }
159         }
160         if rewrittenPath == "" {
161                 log.Println("WARNING:", repoUUID,
162                         "git directory not found in", theConfig.Root, tryDirs)
163                 // We say "content not found" to disambiguate from the
164                 // earlier "API says that repo does not exist" error.
165                 statusCode, statusText = http.StatusNotFound, "content not found"
166                 return
167         }
168         r.URL.Path = rewrittenPath
169
170         handlerCopy := *h.handler
171         handlerCopy.Env = append(handlerCopy.Env, "REMOTE_USER="+r.RemoteAddr) // Should be username
172         handlerCopy.ServeHTTP(&w, r)
173 }
174
175 var escaper = strings.NewReplacer("\"", "\\\"", "\\", "\\\\", "\n", "\\n")
176
177 // Transform strings so they are safer to write in logs (e.g.,
178 // 'foo"bar' becomes '"foo\"bar"'). Non-string args are left alone.
179 func quoteStrings(args ...interface{}) []interface{} {
180         for i, arg := range args {
181                 if s, ok := arg.(string); ok {
182                         args[i] = "\"" + escaper.Replace(s) + "\""
183                 }
184         }
185         return args
186 }