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)
46 if r.Method == "OPTIONS" {
47 method := r.Header.Get("Access-Control-Request-Method")
48 if method != "GET" && method != "POST" {
49 w.WriteHeader(http.StatusMethodNotAllowed)
52 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
53 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
54 w.Header().Set("Access-Control-Allow-Origin", "*")
55 w.Header().Set("Access-Control-Max-Age", "86400")
56 w.WriteHeader(http.StatusOK)
60 if r.Header.Get("Origin") != "" {
61 // Allow simple cross-origin requests without user
62 // credentials ("user credentials" as defined by CORS,
63 // i.e., cookies, HTTP authentication, and client-side
64 // SSL certificates. See
65 // http://www.w3.org/TR/cors/#user-credentials).
66 w.Header().Set("Access-Control-Allow-Origin", "*")
70 if w.WroteStatus() == 0 {
71 // Nobody has called WriteHeader yet: that
73 w.WriteHeader(statusCode)
74 w.Write([]byte(statusText))
77 // If the given password is a valid token, log the first 10 characters of the token.
78 // Otherwise: log the string <invalid> if a password is given, else an empty string.
81 if len(apiToken) > 0 {
82 passwordToLog = "<invalid>"
85 passwordToLog = apiToken[0:10]
88 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
91 creds := auth.NewCredentialsFromHTTPRequest(r)
92 if len(creds.Tokens) == 0 {
93 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
94 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
97 apiToken = creds.Tokens[0]
99 // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
100 // protected by the permissions on the repository named
102 pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
103 if len(pathParts) != 2 {
104 statusCode, statusText = http.StatusNotFound, "not found"
107 repoName = pathParts[0]
108 repoName = strings.TrimRight(repoName, "/")
110 arv := h.clientPool.Get()
112 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
115 defer h.clientPool.Put(arv)
117 // Ask API server whether the repository is readable using
118 // this token (by trying to read it!)
119 arv.ApiToken = apiToken
120 reposFound := arvadosclient.Dict{}
121 if err := arv.List("repositories", arvadosclient.Dict{
122 "filters": [][]string{{"name", "=", repoName}},
123 }, &reposFound); err != nil {
124 statusCode, statusText = http.StatusInternalServerError, err.Error()
128 if avail, ok := reposFound["items_available"].(float64); !ok {
129 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
131 } else if avail < 1 {
132 statusCode, statusText = http.StatusNotFound, "not found"
134 } else if avail > 1 {
135 statusCode, statusText = http.StatusInternalServerError, "name collision"
139 repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
141 isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
145 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
146 "repository": arvadosclient.Dict{
147 "modified_at": time.Now().String(),
149 }, &arvadosclient.Dict{})
151 statusCode, statusText = http.StatusForbidden, err.Error()
157 // Regardless of whether the client asked for "/foo.git" or
158 // "/foo/.git", we choose whichever variant exists in our repo
159 // root, and we try {uuid}.git and {uuid}/.git first. If none
160 // of these exist, we 404 even though the API told us the repo
161 // _should_ exist (presumably this means the repo was just
162 // created, and gitolite sync hasn't run yet).
165 "/" + repoUUID + ".git",
166 "/" + repoUUID + "/.git",
167 "/" + repoName + ".git",
168 "/" + repoName + "/.git",
170 for _, dir := range tryDirs {
171 if fileInfo, err := os.Stat(theConfig.RepoRoot + dir); err != nil {
172 if !os.IsNotExist(err) {
173 statusCode, statusText = http.StatusInternalServerError, err.Error()
176 } else if fileInfo.IsDir() {
177 rewrittenPath = dir + "/" + pathParts[1]
181 if rewrittenPath == "" {
182 log.Println("WARNING:", repoUUID,
183 "git directory not found in", theConfig.RepoRoot, tryDirs)
184 // We say "content not found" to disambiguate from the
185 // earlier "API says that repo does not exist" error.
186 statusCode, statusText = http.StatusNotFound, "content not found"
189 r.URL.Path = rewrittenPath
191 h.handler.ServeHTTP(w, r)