17417: Merge branch 'main' into 17417-add-arm64
[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         "errors"
9         "log"
10         "net/http"
11         "os"
12         "regexp"
13         "strings"
14         "sync"
15         "time"
16
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"
21 )
22
23 type authHandler struct {
24         handler    http.Handler
25         clientPool *arvadosclient.ClientPool
26         cluster    *arvados.Cluster
27         setupOnce  sync.Once
28 }
29
30 func (h *authHandler) setup() {
31         client, err := arvados.NewClientFromConfig(h.cluster)
32         if err != nil {
33                 log.Fatal(err)
34         }
35
36         ac, err := arvadosclient.New(client)
37         if err != nil {
38                 log.Fatalf("Error setting up arvados client prototype %v", err)
39         }
40
41         h.clientPool = &arvadosclient.ClientPool{Prototype: ac}
42 }
43
44 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
45         h.setupOnce.Do(h.setup)
46
47         var statusCode int
48         var statusText string
49         var apiToken string
50         var repoName string
51         var validAPIToken bool
52
53         w := httpserver.WrapResponseWriter(wOrig)
54
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)
59                         return
60                 }
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)
66                 return
67         }
68
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", "*")
76         }
77
78         defer func() {
79                 if w.WroteStatus() == 0 {
80                         // Nobody has called WriteHeader yet: that
81                         // must be our job.
82                         w.WriteHeader(statusCode)
83                         if statusCode >= 400 {
84                                 w.Write([]byte(statusText))
85                         }
86                 }
87
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.
90                 passwordToLog := ""
91                 if !validAPIToken {
92                         if len(apiToken) > 0 {
93                                 passwordToLog = "<invalid>"
94                         }
95                 } else {
96                         passwordToLog = apiToken[0:10]
97                 }
98
99                 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
100         }()
101
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\"")
106                 return
107         }
108         apiToken = creds.Tokens[0]
109
110         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
111         // protected by the permissions on the repository named
112         // "foo/bar".
113         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
114         if len(pathParts) != 2 {
115                 statusCode, statusText = http.StatusNotFound, "not found"
116                 return
117         }
118         repoName = pathParts[0]
119         repoName = strings.TrimRight(repoName, "/")
120
121         arv := h.clientPool.Get()
122         if arv == nil {
123                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
124                 return
125         }
126         defer h.clientPool.Put(arv)
127
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)
132         if err != nil {
133                 statusCode, statusText = http.StatusInternalServerError, err.Error()
134                 return
135         }
136         validAPIToken = true
137         if repoUUID == "" {
138                 statusCode, statusText = http.StatusNotFound, "not found"
139                 return
140         }
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(h.cluster.Git.Repositories + 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", 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"
188                 return
189         }
190         r.URL.Path = rewrittenPath
191
192         h.handler.ServeHTTP(w, r)
193 }
194
195 var uuidRegexp = regexp.MustCompile(`^[0-9a-z]{5}-s0uqq-[0-9a-z]{15}$`)
196
197 func (h *authHandler) lookupRepo(arv *arvadosclient.ArvadosClient, repoName string) (string, error) {
198         reposFound := arvadosclient.Dict{}
199         var column string
200         if uuidRegexp.MatchString(repoName) {
201                 column = "uuid"
202         } else {
203                 column = "name"
204         }
205         err := arv.List("repositories", arvadosclient.Dict{
206                 "filters": [][]string{{column, "=", repoName}},
207         }, &reposFound)
208         if err != nil {
209                 return "", err
210         } else if avail, ok := reposFound["items_available"].(float64); !ok {
211                 return "", errors.New("bad list response from API")
212         } else if avail < 1 {
213                 return "", nil
214         } else if avail > 1 {
215                 return "", errors.New("name collision")
216         }
217         return reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string), nil
218 }