Merge branch '12418-glob-empty-collection' closes #12418
[arvados.git] / services / arv-git-httpd / auth_handler.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "log"
9         "net/http"
10         "os"
11         "strings"
12         "sync"
13         "time"
14
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"
18 )
19
20 type authHandler struct {
21         handler    http.Handler
22         clientPool *arvadosclient.ClientPool
23         setupOnce  sync.Once
24 }
25
26 func (h *authHandler) setup() {
27         ac, err := arvadosclient.New(&theConfig.Client)
28         if err != nil {
29                 log.Fatal(err)
30         }
31         h.clientPool = &arvadosclient.ClientPool{Prototype: ac}
32         log.Printf("%+v", h.clientPool.Prototype)
33 }
34
35 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
36         h.setupOnce.Do(h.setup)
37
38         var statusCode int
39         var statusText string
40         var apiToken string
41         var repoName string
42         var validApiToken bool
43
44         w := httpserver.WrapResponseWriter(wOrig)
45
46         defer func() {
47                 if w.WroteStatus() == 0 {
48                         // Nobody has called WriteHeader yet: that
49                         // must be our job.
50                         w.WriteHeader(statusCode)
51                         w.Write([]byte(statusText))
52                 }
53
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.
56                 passwordToLog := ""
57                 if !validApiToken {
58                         if len(apiToken) > 0 {
59                                 passwordToLog = "<invalid>"
60                         }
61                 } else {
62                         passwordToLog = apiToken[0:10]
63                 }
64
65                 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
66         }()
67
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\"")
72                 return
73         }
74         apiToken = creds.Tokens[0]
75
76         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
77         // protected by the permissions on the repository named
78         // "foo/bar".
79         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
80         if len(pathParts) != 2 {
81                 statusCode, statusText = http.StatusBadRequest, "bad request"
82                 return
83         }
84         repoName = pathParts[0]
85         repoName = strings.TrimRight(repoName, "/")
86
87         arv := h.clientPool.Get()
88         if arv == nil {
89                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
90                 return
91         }
92         defer h.clientPool.Put(arv)
93
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()
102                 return
103         }
104         validApiToken = true
105         if avail, ok := reposFound["items_available"].(float64); !ok {
106                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
107                 return
108         } else if avail < 1 {
109                 statusCode, statusText = http.StatusNotFound, "not found"
110                 return
111         } else if avail > 1 {
112                 statusCode, statusText = http.StatusInternalServerError, "name collision"
113                 return
114         }
115
116         repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
117
118         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
119         if !isWrite {
120                 statusText = "read"
121         } else {
122                 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
123                         "repository": arvadosclient.Dict{
124                                 "modified_at": time.Now().String(),
125                         },
126                 }, &arvadosclient.Dict{})
127                 if err != nil {
128                         statusCode, statusText = http.StatusForbidden, err.Error()
129                         return
130                 }
131                 statusText = "write"
132         }
133
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).
140         rewrittenPath := ""
141         tryDirs := []string{
142                 "/" + repoUUID + ".git",
143                 "/" + repoUUID + "/.git",
144                 "/" + repoName + ".git",
145                 "/" + repoName + "/.git",
146         }
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()
151                                 return
152                         }
153                 } else if fileInfo.IsDir() {
154                         rewrittenPath = dir + "/" + pathParts[1]
155                         break
156                 }
157         }
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"
164                 return
165         }
166         r.URL.Path = rewrittenPath
167
168         h.handler.ServeHTTP(&w, r)
169 }