12 "git.curoverse.com/arvados.git/sdk/go/auth"
13 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
16 func newArvadosClient() interface{} {
17 arv, err := arvadosclient.MakeArvadosClient()
19 log.Println("MakeArvadosClient:", err)
25 var connectionPool = &sync.Pool{New: newArvadosClient}
27 type spyingResponseWriter struct {
32 func (w spyingResponseWriter) WriteHeader(s int) {
34 w.ResponseWriter.WriteHeader(s)
37 type authHandler struct {
41 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
47 var validApiToken bool
49 w := spyingResponseWriter{wOrig, &wroteStatus}
53 // Nobody has called WriteHeader yet: that
55 w.WriteHeader(statusCode)
56 w.Write([]byte(statusText))
59 // If the given password is a valid token, log the first 10 characters of the token.
60 // Otherwise: log the string <invalid> if a password is given, else an empty string.
63 if len(apiToken) > 0 {
64 passwordToLog = "<invalid>"
67 passwordToLog = apiToken[0:10]
70 log.Println(quoteStrings(r.RemoteAddr, passwordToLog, wroteStatus, statusText, repoName, r.Method, r.URL.Path)...)
73 creds := auth.NewCredentialsFromHTTPRequest(r)
74 if len(creds.Tokens) == 0 {
75 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
76 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
79 apiToken = creds.Tokens[0]
81 // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
82 // protected by the permissions on the repository named
84 pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
85 if len(pathParts) != 2 {
86 statusCode, statusText = http.StatusBadRequest, "bad request"
89 repoName = pathParts[0]
90 repoName = strings.TrimRight(repoName, "/")
92 arv, ok := connectionPool.Get().(*arvadosclient.ArvadosClient)
93 if !ok || arv == nil {
94 statusCode, statusText = http.StatusInternalServerError, "connection pool failed"
97 defer connectionPool.Put(arv)
99 // Ask API server whether the repository is readable using
100 // this token (by trying to read it!)
101 arv.ApiToken = apiToken
102 reposFound := arvadosclient.Dict{}
103 if err := arv.List("repositories", arvadosclient.Dict{
104 "filters": [][]string{{"name", "=", repoName}},
105 }, &reposFound); err != nil {
106 statusCode, statusText = http.StatusInternalServerError, err.Error()
110 if avail, ok := reposFound["items_available"].(float64); !ok {
111 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
113 } else if avail < 1 {
114 statusCode, statusText = http.StatusNotFound, "not found"
116 } else if avail > 1 {
117 statusCode, statusText = http.StatusInternalServerError, "name collision"
121 repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
123 isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
127 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
128 "repository": arvadosclient.Dict{
129 "modified_at": time.Now().String(),
131 }, &arvadosclient.Dict{})
133 statusCode, statusText = http.StatusForbidden, err.Error()
139 // Regardless of whether the client asked for "/foo.git" or
140 // "/foo/.git", we choose whichever variant exists in our repo
141 // root, and we try {uuid}.git and {uuid}/.git first. If none
142 // of these exist, we 404 even though the API told us the repo
143 // _should_ exist (presumably this means the repo was just
144 // created, and gitolite sync hasn't run yet).
147 "/" + repoUUID + ".git",
148 "/" + repoUUID + "/.git",
149 "/" + repoName + ".git",
150 "/" + repoName + "/.git",
152 for _, dir := range tryDirs {
153 if fileInfo, err := os.Stat(theConfig.Root + dir); err != nil {
154 if !os.IsNotExist(err) {
155 statusCode, statusText = http.StatusInternalServerError, err.Error()
158 } else if fileInfo.IsDir() {
159 rewrittenPath = dir + "/" + pathParts[1]
163 if rewrittenPath == "" {
164 log.Println("WARNING:", repoUUID,
165 "git directory not found in", theConfig.Root, tryDirs)
166 // We say "content not found" to disambiguate from the
167 // earlier "API says that repo does not exist" error.
168 statusCode, statusText = http.StatusNotFound, "content not found"
171 r.URL.Path = rewrittenPath
173 handlerCopy := *h.handler
174 handlerCopy.Env = append(handlerCopy.Env, "REMOTE_USER="+r.RemoteAddr) // Should be username
175 handlerCopy.ServeHTTP(&w, r)
178 var escaper = strings.NewReplacer("\"", "\\\"", "\\", "\\\\", "\n", "\\n")
180 // Transform strings so they are safer to write in logs (e.g.,
181 // 'foo"bar' becomes '"foo\"bar"'). Non-string args are left alone.
182 func quoteStrings(args ...interface{}) []interface{} {
183 for i, arg := range args {
184 if s, ok := arg.(string); ok {
185 args[i] = "\"" + escaper.Replace(s) + "\""