Merge branch '12462-search-hyphen'
[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         if r.Method == "OPTIONS" {
47                 method := r.Header.Get("Access-Control-Request-Method")
48                 if method != "GET" && method != "POST" {
49                         w.WriteHeader(http.StatusMethodNotAllowed)
50                         return
51                 }
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)
57                 return
58         }
59
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", "*")
67         }
68
69         defer func() {
70                 if w.WroteStatus() == 0 {
71                         // Nobody has called WriteHeader yet: that
72                         // must be our job.
73                         w.WriteHeader(statusCode)
74                         w.Write([]byte(statusText))
75                 }
76
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.
79                 passwordToLog := ""
80                 if !validApiToken {
81                         if len(apiToken) > 0 {
82                                 passwordToLog = "<invalid>"
83                         }
84                 } else {
85                         passwordToLog = apiToken[0:10]
86                 }
87
88                 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
89         }()
90
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\"")
95                 return
96         }
97         apiToken = creds.Tokens[0]
98
99         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
100         // protected by the permissions on the repository named
101         // "foo/bar".
102         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
103         if len(pathParts) != 2 {
104                 statusCode, statusText = http.StatusNotFound, "not found"
105                 return
106         }
107         repoName = pathParts[0]
108         repoName = strings.TrimRight(repoName, "/")
109
110         arv := h.clientPool.Get()
111         if arv == nil {
112                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
113                 return
114         }
115         defer h.clientPool.Put(arv)
116
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()
125                 return
126         }
127         validApiToken = true
128         if avail, ok := reposFound["items_available"].(float64); !ok {
129                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
130                 return
131         } else if avail < 1 {
132                 statusCode, statusText = http.StatusNotFound, "not found"
133                 return
134         } else if avail > 1 {
135                 statusCode, statusText = http.StatusInternalServerError, "name collision"
136                 return
137         }
138
139         repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
140
141         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
142         if !isWrite {
143                 statusText = "read"
144         } else {
145                 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
146                         "repository": arvadosclient.Dict{
147                                 "modified_at": time.Now().String(),
148                         },
149                 }, &arvadosclient.Dict{})
150                 if err != nil {
151                         statusCode, statusText = http.StatusForbidden, err.Error()
152                         return
153                 }
154                 statusText = "write"
155         }
156
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).
163         rewrittenPath := ""
164         tryDirs := []string{
165                 "/" + repoUUID + ".git",
166                 "/" + repoUUID + "/.git",
167                 "/" + repoName + ".git",
168                 "/" + repoName + "/.git",
169         }
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()
174                                 return
175                         }
176                 } else if fileInfo.IsDir() {
177                         rewrittenPath = dir + "/" + pathParts[1]
178                         break
179                 }
180         }
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"
187                 return
188         }
189         r.URL.Path = rewrittenPath
190
191         h.handler.ServeHTTP(&w, r)
192 }