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