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