5416: Merge branch 'master' into 5416-arv-git-httpd
[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.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")
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         // Regardless of whether the client asked for "/foo.git" or
79         // "/foo/.git", we choose whichever variant exists in our repo
80         // root. If neither exists, we won't even bother checking
81         // authentication.
82         rewrittenPath := ""
83         tryDirs := []string{
84                 "/" + repoName + ".git",
85                 "/" + repoName + "/.git",
86         }
87         for _, dir := range tryDirs {
88                 if fileInfo, err := os.Stat(theConfig.Root + dir); err != nil {
89                         if !os.IsNotExist(err) {
90                                 statusCode, statusText = http.StatusInternalServerError, err.Error()
91                                 return
92                         }
93                 } else if fileInfo.IsDir() {
94                         rewrittenPath = dir + "/" + pathParts[1]
95                         break
96                 }
97         }
98         if rewrittenPath == "" {
99                 statusCode, statusText = http.StatusNotFound, "not found"
100                 return
101         }
102         r.URL.Path = rewrittenPath
103
104         arv, ok := connectionPool.Get().(*arvadosclient.ArvadosClient)
105         if !ok || arv == nil {
106                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed"
107                 return
108         }
109         defer connectionPool.Put(arv)
110
111         // Ask API server whether the repository is readable using this token (by trying to read it!)
112         arv.ApiToken = password
113         reposFound := arvadosclient.Dict{}
114         if err := arv.List("repositories", arvadosclient.Dict{
115                 "filters": [][]string{[]string{"name", "=", repoName}},
116         }, &reposFound); err != nil {
117                 statusCode, statusText = http.StatusInternalServerError, err.Error()
118                 return
119         }
120         if avail, ok := reposFound["items_available"].(float64); !ok {
121                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
122                 return
123         } else if avail < 1 {
124                 statusCode, statusText = http.StatusNotFound, "not found"
125                 return
126         } else if avail > 1 {
127                 statusCode, statusText = http.StatusInternalServerError, "name collision"
128                 return
129         }
130         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
131         if !isWrite {
132                 statusText = "read"
133         } else {
134                 uuid := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
135                 err := arv.Update("repositories", uuid, arvadosclient.Dict{
136                         "repository": arvadosclient.Dict{
137                                 "modified_at": time.Now().String(),
138                         },
139                 }, &arvadosclient.Dict{})
140                 if err != nil {
141                         statusCode, statusText = http.StatusForbidden, err.Error()
142                         return
143                 }
144                 statusText = "write"
145         }
146         handlerCopy := *h.handler
147         handlerCopy.Env = append(handlerCopy.Env, "REMOTE_USER="+r.RemoteAddr) // Should be username
148         handlerCopy.ServeHTTP(&w, r)
149 }
150
151 var escaper = strings.NewReplacer("\"", "\\\"", "\\", "\\\\", "\n", "\\n")
152
153 // Transform strings so they are safer to write in logs (e.g.,
154 // 'foo"bar' becomes '"foo\"bar"'). Non-string args are left alone.
155 func quoteStrings(args ...interface{}) []interface{} {
156         for i, arg := range args {
157                 if s, ok := arg.(string); ok {
158                         args[i] = "\"" + escaper.Replace(s) + "\""
159                 }
160         }
161         return args
162 }