8311: Fix "read" or "write" mistakenly appended to response data.
[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 }
33
34 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
35         h.setupOnce.Do(h.setup)
36
37         var statusCode int
38         var statusText string
39         var apiToken string
40         var repoName string
41         var validApiToken bool
42
43         w := httpserver.WrapResponseWriter(wOrig)
44
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)
49                         return
50                 }
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)
56                 return
57         }
58
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", "*")
66         }
67
68         defer func() {
69                 if w.WroteStatus() == 0 {
70                         // Nobody has called WriteHeader yet: that
71                         // must be our job.
72                         w.WriteHeader(statusCode)
73                         if statusCode >= 400 {
74                                 w.Write([]byte(statusText))
75                         }
76                 }
77
78                 // If the given password is a valid token, log the first 10 characters of the token.
79                 // Otherwise: log the string <invalid> if a password is given, else an empty string.
80                 passwordToLog := ""
81                 if !validApiToken {
82                         if len(apiToken) > 0 {
83                                 passwordToLog = "<invalid>"
84                         }
85                 } else {
86                         passwordToLog = apiToken[0:10]
87                 }
88
89                 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
90         }()
91
92         creds := auth.NewCredentialsFromHTTPRequest(r)
93         if len(creds.Tokens) == 0 {
94                 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
95                 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
96                 return
97         }
98         apiToken = creds.Tokens[0]
99
100         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
101         // protected by the permissions on the repository named
102         // "foo/bar".
103         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
104         if len(pathParts) != 2 {
105                 statusCode, statusText = http.StatusNotFound, "not found"
106                 return
107         }
108         repoName = pathParts[0]
109         repoName = strings.TrimRight(repoName, "/")
110
111         arv := h.clientPool.Get()
112         if arv == nil {
113                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
114                 return
115         }
116         defer h.clientPool.Put(arv)
117
118         // Ask API server whether the repository is readable using
119         // this token (by trying to read it!)
120         arv.ApiToken = apiToken
121         reposFound := arvadosclient.Dict{}
122         if err := arv.List("repositories", arvadosclient.Dict{
123                 "filters": [][]string{{"name", "=", repoName}},
124         }, &reposFound); err != nil {
125                 statusCode, statusText = http.StatusInternalServerError, err.Error()
126                 return
127         }
128         validApiToken = true
129         if avail, ok := reposFound["items_available"].(float64); !ok {
130                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
131                 return
132         } else if avail < 1 {
133                 statusCode, statusText = http.StatusNotFound, "not found"
134                 return
135         } else if avail > 1 {
136                 statusCode, statusText = http.StatusInternalServerError, "name collision"
137                 return
138         }
139
140         repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
141
142         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
143         if !isWrite {
144                 statusText = "read"
145         } else {
146                 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
147                         "repository": arvadosclient.Dict{
148                                 "modified_at": time.Now().String(),
149                         },
150                 }, &arvadosclient.Dict{})
151                 if err != nil {
152                         statusCode, statusText = http.StatusForbidden, err.Error()
153                         return
154                 }
155                 statusText = "write"
156         }
157
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).
164         rewrittenPath := ""
165         tryDirs := []string{
166                 "/" + repoUUID + ".git",
167                 "/" + repoUUID + "/.git",
168                 "/" + repoName + ".git",
169                 "/" + repoName + "/.git",
170         }
171         for _, dir := range tryDirs {
172                 if fileInfo, err := os.Stat(theConfig.RepoRoot + dir); err != nil {
173                         if !os.IsNotExist(err) {
174                                 statusCode, statusText = http.StatusInternalServerError, err.Error()
175                                 return
176                         }
177                 } else if fileInfo.IsDir() {
178                         rewrittenPath = dir + "/" + pathParts[1]
179                         break
180                 }
181         }
182         if rewrittenPath == "" {
183                 log.Println("WARNING:", repoUUID,
184                         "git directory not found in", theConfig.RepoRoot, 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"
188                 return
189         }
190         r.URL.Path = rewrittenPath
191
192         h.handler.ServeHTTP(w, r)
193 }