9005: Rename ClearCache to RefreshServiceDiscovery
[arvados.git] / services / arv-git-httpd / auth_handler.go
1 package main
2
3 import (
4         "log"
5         "net/http"
6         "os"
7         "strings"
8         "sync"
9         "time"
10
11         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
12         "git.curoverse.com/arvados.git/sdk/go/auth"
13         "git.curoverse.com/arvados.git/sdk/go/httpserver"
14 )
15
16 type authHandler struct {
17         handler    http.Handler
18         clientPool *arvadosclient.ClientPool
19         setupOnce  sync.Once
20 }
21
22 func (h *authHandler) setup() {
23         ac, err := arvadosclient.New(&theConfig.Client)
24         if err != nil {
25                 log.Fatal(err)
26         }
27         h.clientPool = &arvadosclient.ClientPool{Prototype: ac}
28         log.Printf("%+v", h.clientPool.Prototype)
29 }
30
31 func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
32         h.setupOnce.Do(h.setup)
33
34         var statusCode int
35         var statusText string
36         var apiToken string
37         var repoName string
38         var validApiToken bool
39
40         w := httpserver.WrapResponseWriter(wOrig)
41
42         defer func() {
43                 if w.WroteStatus() == 0 {
44                         // Nobody has called WriteHeader yet: that
45                         // must be our job.
46                         w.WriteHeader(statusCode)
47                         w.Write([]byte(statusText))
48                 }
49
50                 // If the given password is a valid token, log the first 10 characters of the token.
51                 // Otherwise: log the string <invalid> if a password is given, else an empty string.
52                 passwordToLog := ""
53                 if !validApiToken {
54                         if len(apiToken) > 0 {
55                                 passwordToLog = "<invalid>"
56                         }
57                 } else {
58                         passwordToLog = apiToken[0:10]
59                 }
60
61                 httpserver.Log(r.RemoteAddr, passwordToLog, w.WroteStatus(), statusText, repoName, r.Method, r.URL.Path)
62         }()
63
64         creds := auth.NewCredentialsFromHTTPRequest(r)
65         if len(creds.Tokens) == 0 {
66                 statusCode, statusText = http.StatusUnauthorized, "no credentials provided"
67                 w.Header().Add("WWW-Authenticate", "Basic realm=\"git\"")
68                 return
69         }
70         apiToken = creds.Tokens[0]
71
72         // Access to paths "/foo/bar.git/*" and "/foo/bar/.git/*" are
73         // protected by the permissions on the repository named
74         // "foo/bar".
75         pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
76         if len(pathParts) != 2 {
77                 statusCode, statusText = http.StatusBadRequest, "bad request"
78                 return
79         }
80         repoName = pathParts[0]
81         repoName = strings.TrimRight(repoName, "/")
82
83         arv := h.clientPool.Get()
84         if arv == nil {
85                 statusCode, statusText = http.StatusInternalServerError, "connection pool failed: "+h.clientPool.Err().Error()
86                 return
87         }
88         defer h.clientPool.Put(arv)
89
90         // Ask API server whether the repository is readable using
91         // this token (by trying to read it!)
92         arv.ApiToken = apiToken
93         reposFound := arvadosclient.Dict{}
94         if err := arv.List("repositories", arvadosclient.Dict{
95                 "filters": [][]string{{"name", "=", repoName}},
96         }, &reposFound); err != nil {
97                 statusCode, statusText = http.StatusInternalServerError, err.Error()
98                 return
99         }
100         validApiToken = true
101         if avail, ok := reposFound["items_available"].(float64); !ok {
102                 statusCode, statusText = http.StatusInternalServerError, "bad list response from API"
103                 return
104         } else if avail < 1 {
105                 statusCode, statusText = http.StatusNotFound, "not found"
106                 return
107         } else if avail > 1 {
108                 statusCode, statusText = http.StatusInternalServerError, "name collision"
109                 return
110         }
111
112         repoUUID := reposFound["items"].([]interface{})[0].(map[string]interface{})["uuid"].(string)
113
114         isWrite := strings.HasSuffix(r.URL.Path, "/git-receive-pack")
115         if !isWrite {
116                 statusText = "read"
117         } else {
118                 err := arv.Update("repositories", repoUUID, arvadosclient.Dict{
119                         "repository": arvadosclient.Dict{
120                                 "modified_at": time.Now().String(),
121                         },
122                 }, &arvadosclient.Dict{})
123                 if err != nil {
124                         statusCode, statusText = http.StatusForbidden, err.Error()
125                         return
126                 }
127                 statusText = "write"
128         }
129
130         // Regardless of whether the client asked for "/foo.git" or
131         // "/foo/.git", we choose whichever variant exists in our repo
132         // root, and we try {uuid}.git and {uuid}/.git first. If none
133         // of these exist, we 404 even though the API told us the repo
134         // _should_ exist (presumably this means the repo was just
135         // created, and gitolite sync hasn't run yet).
136         rewrittenPath := ""
137         tryDirs := []string{
138                 "/" + repoUUID + ".git",
139                 "/" + repoUUID + "/.git",
140                 "/" + repoName + ".git",
141                 "/" + repoName + "/.git",
142         }
143         for _, dir := range tryDirs {
144                 if fileInfo, err := os.Stat(theConfig.RepoRoot + dir); err != nil {
145                         if !os.IsNotExist(err) {
146                                 statusCode, statusText = http.StatusInternalServerError, err.Error()
147                                 return
148                         }
149                 } else if fileInfo.IsDir() {
150                         rewrittenPath = dir + "/" + pathParts[1]
151                         break
152                 }
153         }
154         if rewrittenPath == "" {
155                 log.Println("WARNING:", repoUUID,
156                         "git directory not found in", theConfig.RepoRoot, tryDirs)
157                 // We say "content not found" to disambiguate from the
158                 // earlier "API says that repo does not exist" error.
159                 statusCode, statusText = http.StatusNotFound, "content not found"
160                 return
161         }
162         r.URL.Path = rewrittenPath
163
164         h.handler.ServeHTTP(&w, r)
165 }