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}
34 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
35 h.setupOnce.Do(h.setup)
41 var validApiToken bool
43 w := httpserver.WrapResponseWriter(wOrig)
45 if r.Method == "OPTIONS" {
46 method := r.Header.Get("Access-Control-Request-Method")
47 if method != "GET" && method != "POST" {
48 w.WriteHeader(http.StatusMethodNotAllowed)
51 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
52 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
53 w.Header().Set("Access-Control-Allow-Origin", "*")
54 w.Header().Set("Access-Control-Max-Age", "86400")
55 w.WriteHeader(http.StatusOK)
59 if r.Header.Get("Origin") != "" {
60 // Allow simple cross-origin requests without user
61 // credentials ("user credentials" as defined by CORS,
62 // i.e., cookies, HTTP authentication, and client-side
63 // SSL certificates. See
64 // http://www.w3.org/TR/cors/#user-credentials).
65 w.Header().Set("Access-Control-Allow-Origin", "*")
69 if w.WroteStatus() == 0 {
70 // Nobody has called WriteHeader yet: that
72 w.WriteHeader(statusCode)
73 w.Write([]byte(statusText))
76 // If the given password is a valid token, log the first 10 characters of the token.
77 // Otherwise: log the string <invalid> if a password is given, else an empty string.
80 if len(apiToken) > 0 {
81 passwordToLog = "<invalid>"
84 passwordToLog = apiToken[0:10]
87 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
90 creds := auth.NewCredentialsFromHTTPRequest(r)
91 if len(creds.Tokens) == 0 {
92 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
93 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
96 apiToken = creds.Tokens[0]
98 // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
99 // protected by the permissions on the repository named
101 pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
102 if len(pathParts) != 2 {
103 statusCode, statusText = http.StatusNotFound, "not found"
106 repoName = pathParts[0]
107 repoName = strings.TrimRight(repoName, "/")
109 arv := h.clientPool.Get()
111 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
114 defer h.clientPool.Put(arv)
116 // Ask API server whether the repository is readable using
117 // this token (by trying to read it!)
118 arv.ApiToken = apiToken
119 reposFound := arvadosclient.Dict{}
120 if err := arv.List("repositories", arvadosclient.Dict{
121 "filters": [][]string{{"name", "=", repoName}},
122 }, &reposFound); err != nil {
123 statusCode, statusText = http.StatusInternalServerError, err.Error()
127 if avail, ok := reposFound["items_available"].(float64); !ok {
128 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
130 } else if avail < 1 {
131 statusCode, statusText = http.StatusNotFound, "not found"
133 } else if avail > 1 {
134 statusCode, statusText = http.StatusInternalServerError, "name collision"
138 repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
140 isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
144 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
145 "repository": arvadosclient.Dict{
146 "modified_at": time.Now().String(),
148 }, &arvadosclient.Dict{})
150 statusCode, statusText = http.StatusForbidden, err.Error()
156 // Regardless of whether the client asked for "/foo.git" or
157 // "/foo/.git", we choose whichever variant exists in our repo
158 // root, and we try {uuid}.git and {uuid}/.git first. If none
159 // of these exist, we 404 even though the API told us the repo
160 // _should_ exist (presumably this means the repo was just
161 // created, and gitolite sync hasn't run yet).
164 "/" + repoUUID + ".git",
165 "/" + repoUUID + "/.git",
166 "/" + repoName + ".git",
167 "/" + repoName + "/.git",
169 for _, dir := range tryDirs {
170 if fileInfo, err := os.Stat(theConfig.RepoRoot + dir); err != nil {
171 if !os.IsNotExist(err) {
172 statusCode, statusText = http.StatusInternalServerError, err.Error()
175 } else if fileInfo.IsDir() {
176 rewrittenPath = dir + "/" + pathParts[1]
180 if rewrittenPath == "" {
181 log.Println("WARNING:", repoUUID,
182 "git directory not found in", theConfig.RepoRoot, tryDirs)
183 // We say "content not found" to disambiguate from the
184 // earlier "API says that repo does not exist" error.
185 statusCode, statusText = http.StatusNotFound, "content not found"
188 r.URL.Path = rewrittenPath
190 h.handler.ServeHTTP(w, r)