1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
15 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
16 "git.curoverse.com/arvados.git/sdk/go/auth"
17 "git.curoverse.com/arvados.git/sdk/go/httpserver"
20 type authHandler struct {
22 clientPool *arvadosclient.ClientPool
26 func (h *authHandler) setup() {
27 ac, err := arvadosclient.New(&theConfig.Client)
31 h.clientPool = &arvadosclient.ClientPool{Prototype: ac}
32 log.Printf("%+v", h.clientPool.Prototype)
35 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
36 h.setupOnce.Do(h.setup)
42 var validApiToken bool
44 w := httpserver.WrapResponseWriter(wOrig)
47 if w.WroteStatus() == 0 {
48 // Nobody has called WriteHeader yet: that
50 w.WriteHeader(statusCode)
51 w.Write([]byte(statusText))
54 // If the given password is a valid token, log the first 10 characters of the token.
55 // Otherwise: log the string <invalid> if a password is given, else an empty string.
58 if len(apiToken) > 0 {
59 passwordToLog = "<invalid>"
62 passwordToLog = apiToken[0:10]
65 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
68 creds := auth.NewCredentialsFromHTTPRequest(r)
69 if len(creds.Tokens) == 0 {
70 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
71 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
74 apiToken = creds.Tokens[0]
76 // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
77 // protected by the permissions on the repository named
79 pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
80 if len(pathParts) != 2 {
81 statusCode, statusText = http.StatusBadRequest, "bad request"
84 repoName = pathParts[0]
85 repoName = strings.TrimRight(repoName, "/")
87 arv := h.clientPool.Get()
89 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
92 defer h.clientPool.Put(arv)
94 // Ask API server whether the repository is readable using
95 // this token (by trying to read it!)
96 arv.ApiToken = apiToken
97 reposFound := arvadosclient.Dict{}
98 if err := arv.List("repositories", arvadosclient.Dict{
99 "filters": [][]string{{"name", "=", repoName}},
100 }, &reposFound); err != nil {
101 statusCode, statusText = http.StatusInternalServerError, err.Error()
105 if avail, ok := reposFound["items_available"].(float64); !ok {
106 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
108 } else if avail < 1 {
109 statusCode, statusText = http.StatusNotFound, "not found"
111 } else if avail > 1 {
112 statusCode, statusText = http.StatusInternalServerError, "name collision"
116 repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
118 isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
122 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
123 "repository": arvadosclient.Dict{
124 "modified_at": time.Now().String(),
126 }, &arvadosclient.Dict{})
128 statusCode, statusText = http.StatusForbidden, err.Error()
134 // Regardless of whether the client asked for "/foo.git" or
135 // "/foo/.git", we choose whichever variant exists in our repo
136 // root, and we try {uuid}.git and {uuid}/.git first. If none
137 // of these exist, we 404 even though the API told us the repo
138 // _should_ exist (presumably this means the repo was just
139 // created, and gitolite sync hasn't run yet).
142 "/" + repoUUID + ".git",
143 "/" + repoUUID + "/.git",
144 "/" + repoName + ".git",
145 "/" + repoName + "/.git",
147 for _, dir := range tryDirs {
148 if fileInfo, err := os.Stat(theConfig.RepoRoot + dir); err != nil {
149 if !os.IsNotExist(err) {
150 statusCode, statusText = http.StatusInternalServerError, err.Error()
153 } else if fileInfo.IsDir() {
154 rewrittenPath = dir + "/" + pathParts[1]
158 if rewrittenPath == "" {
159 log.Println("WARNING:", repoUUID,
160 "git directory not found in", theConfig.RepoRoot, tryDirs)
161 // We say "content not found" to disambiguate from the
162 // earlier "API says that repo does not exist" error.
163 statusCode, statusText = http.StatusNotFound, "content not found"
166 r.URL.Path = rewrittenPath
168 h.handler.ServeHTTP(&w, r)