1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.arvados.org/arvados.git/sdk/go/arvados"
18 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
19 "git.arvados.org/arvados.git/sdk/go/auth"
20 "git.arvados.org/arvados.git/sdk/go/httpserver"
23 type authHandler struct {
25 clientPool *arvadosclient.ClientPool
26 cluster *arvados.Cluster
30 func (h *authHandler) setup() {
31 client, err := arvados.NewClientFromConfig(h.cluster)
36 ac, err := arvadosclient.New(client)
38 log.Fatalf("Error setting up arvados client prototype %v", err)
41 h.clientPool = &arvadosclient.ClientPool{Prototype: ac}
44 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
45 h.setupOnce.Do(h.setup)
51 var validApiToken bool
53 w := httpserver.WrapResponseWriter(wOrig)
55 if r.Method == "OPTIONS" {
56 method := r.Header.Get("Access-Control-Request-Method")
57 if method != "GET" && method != "POST" {
58 w.WriteHeader(http.StatusMethodNotAllowed)
61 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
62 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
63 w.Header().Set("Access-Control-Allow-Origin", "*")
64 w.Header().Set("Access-Control-Max-Age", "86400")
65 w.WriteHeader(http.StatusOK)
69 if r.Header.Get("Origin") != "" {
70 // Allow simple cross-origin requests without user
71 // credentials ("user credentials" as defined by CORS,
72 // i.e., cookies, HTTP authentication, and client-side
73 // SSL certificates. See
74 // http://www.w3.org/TR/cors/#user-credentials).
75 w.Header().Set("Access-Control-Allow-Origin", "*")
79 if w.WroteStatus() == 0 {
80 // Nobody has called WriteHeader yet: that
82 w.WriteHeader(statusCode)
83 if statusCode >= 400 {
84 w.Write([]byte(statusText))
88 // If the given password is a valid token, log the first 10 characters of the token.
89 // Otherwise: log the string <invalid> if a password is given, else an empty string.
92 if len(apiToken) > 0 {
93 passwordToLog = "<invalid>"
96 passwordToLog = apiToken[0:10]
99 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
102 creds := auth.CredentialsFromRequest(r)
103 if len(creds.Tokens) == 0 {
104 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
105 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
108 apiToken = creds.Tokens[0]
110 // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
111 // protected by the permissions on the repository named
113 pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
114 if len(pathParts) != 2 {
115 statusCode, statusText = http.StatusNotFound, "not found"
118 repoName = pathParts[0]
119 repoName = strings.TrimRight(repoName, "/")
121 arv := h.clientPool.Get()
123 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
126 defer h.clientPool.Put(arv)
128 // Ask API server whether the repository is readable using
129 // this token (by trying to read it!)
130 arv.ApiToken = apiToken
131 repoUUID, err := h.lookupRepo(arv, repoName)
133 statusCode, statusText = http.StatusInternalServerError, err.Error()
138 statusCode, statusText = http.StatusNotFound, "not found"
142 isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
146 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
147 "repository": arvadosclient.Dict{
148 "modified_at": time.Now().String(),
150 }, &arvadosclient.Dict{})
152 statusCode, statusText = http.StatusForbidden, err.Error()
158 // Regardless of whether the client asked for "/foo.git" or
159 // "/foo/.git", we choose whichever variant exists in our repo
160 // root, and we try {uuid}.git and {uuid}/.git first. If none
161 // of these exist, we 404 even though the API told us the repo
162 // _should_ exist (presumably this means the repo was just
163 // created, and gitolite sync hasn't run yet).
166 "/" + repoUUID + ".git",
167 "/" + repoUUID + "/.git",
168 "/" + repoName + ".git",
169 "/" + repoName + "/.git",
171 for _, dir := range tryDirs {
172 if fileInfo, err := os.Stat(h.cluster.Git.Repositories + dir); err != nil {
173 if !os.IsNotExist(err) {
174 statusCode, statusText = http.StatusInternalServerError, err.Error()
177 } else if fileInfo.IsDir() {
178 rewrittenPath = dir + "/" + pathParts[1]
182 if rewrittenPath == "" {
183 log.Println("WARNING:", repoUUID,
184 "git directory not found in", h.cluster.Git.Repositories, tryDirs)
185 // We say "content not found" to disambiguate from the
186 // earlier "API says that repo does not exist" error.
187 statusCode, statusText = http.StatusNotFound, "content not found"
190 r.URL.Path = rewrittenPath
192 h.handler.ServeHTTP(w, r)
195 var uuidRegexp = regexp.MustCompile(`^[0-9a-z]{5}-s0uqq-[0-9a-z]{15}$`)
197 func (h *authHandler) lookupRepo(arv *arvadosclient.ArvadosClient, repoName string) (string, error) {
198 reposFound := arvadosclient.Dict{}
200 if uuidRegexp.MatchString(repoName) {
205 err := arv.List("repositories", arvadosclient.Dict{
206 "filters": [][]string{{column, "=", repoName}},
210 } else if avail, ok := reposFound["items_available"].(float64); !ok {
211 return "", errors.New("bad list response from API")
212 } else if avail < 1 {
214 } else if avail > 1 {
215 return "", errors.New("name collision")
217 return reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string), nil