8311: Remove debug printf.
[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                         w.Write([]byte(statusText))
74                 }
75
76                 // If the given password is a valid token, log the first 10 characters of the token.
77                 // Otherwise: log the string <invalid> if a password is given, else an empty string.
78                 passwordToLog := ""
79                 if !validApiToken {
80                         if len(apiToken) > 0 {
81                                 passwordToLog = "<invalid>"
82                         }
83                 } else {
84                         passwordToLog = apiToken[0:10]
85                 }
86
87                 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
88         }()
89
90         creds := auth.NewCredentialsFromHTTPRequest(r)
91         if len(creds.Tokens) == 0 {
92                 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
93                 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
94                 return
95         }
96         apiToken = creds.Tokens[0]
97
98         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
99         // protected by the permissions on the repository named
100         // "foo/bar".
101         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
102         if len(pathParts) != 2 {
103                 statusCode, statusText = http.StatusNotFound, "not found"
104                 return
105         }
106         repoName = pathParts[0]
107         repoName = strings.TrimRight(repoName, "/")
108
109         arv := h.clientPool.Get()
110         if arv == nil {
111                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
112                 return
113         }
114         defer h.clientPool.Put(arv)
115
116         // Ask API server whether the repository is readable using
117         // this token (by trying to read it!)
118         arv.ApiToken = apiToken
119         reposFound := arvadosclient.Dict{}
120         if err := arv.List("repositories", arvadosclient.Dict{
121                 "filters": [][]string{{"name", "=", repoName}},
122         }, &reposFound); err != nil {
123                 statusCode, statusText = http.StatusInternalServerError, err.Error()
124                 return
125         }
126         validApiToken = true
127         if avail, ok := reposFound["items_available"].(float64); !ok {
128                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
129                 return
130         } else if avail < 1 {
131                 statusCode, statusText = http.StatusNotFound, "not found"
132                 return
133         } else if avail > 1 {
134                 statusCode, statusText = http.StatusInternalServerError, "name collision"
135                 return
136         }
137
138         repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
139
140         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
141         if !isWrite {
142                 statusText = "read"
143         } else {
144                 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
145                         "repository": arvadosclient.Dict{
146                                 "modified_at": time.Now().String(),
147                         },
148                 }, &arvadosclient.Dict{})
149                 if err != nil {
150                         statusCode, statusText = http.StatusForbidden, err.Error()
151                         return
152                 }
153                 statusText = "write"
154         }
155
156         // Regardless of whether the client asked for "/foo.git" or
157         // "/foo/.git", we choose whichever variant exists in our repo
158         // root, and we try {uuid}.git and {uuid}/.git first. If none
159         // of these exist, we 404 even though the API told us the repo
160         // _should_ exist (presumably this means the repo was just
161         // created, and gitolite sync hasn't run yet).
162         rewrittenPath := ""
163         tryDirs := []string{
164                 "/" + repoUUID + ".git",
165                 "/" + repoUUID + "/.git",
166                 "/" + repoName + ".git",
167                 "/" + repoName + "/.git",
168         }
169         for _, dir := range tryDirs {
170                 if fileInfo, err := os.Stat(theConfig.RepoRoot + dir); err != nil {
171                         if !os.IsNotExist(err) {
172                                 statusCode, statusText = http.StatusInternalServerError, err.Error()
173                                 return
174                         }
175                 } else if fileInfo.IsDir() {
176                         rewrittenPath = dir + "/" + pathParts[1]
177                         break
178                 }
179         }
180         if rewrittenPath == "" {
181                 log.Println("WARNING:", repoUUID,
182                         "git directory not found in", theConfig.RepoRoot, tryDirs)
183                 // We say "content not found" to disambiguate from the
184                 // earlier "API says that repo does not exist" error.
185                 statusCode, statusText = http.StatusNotFound, "content not found"
186                 return
187         }
188         r.URL.Path = rewrittenPath
189
190         h.handler.ServeHTTP(w, r)
191 }