-
Notifications
You must be signed in to change notification settings - Fork 59
/
main.go
256 lines (221 loc) · 7.88 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"regexp"
"strings"
)
const (
ctxKeyOriginalHost = myContextKey("original-host")
)
var (
re = regexp.MustCompile(`^/v2/`)
realm = regexp.MustCompile(`realm="(.*?)"`)
)
type myContextKey string
type registryConfig struct {
host string
repoPrefix string
}
func main() {
host := os.Getenv("HOST")
port := os.Getenv("PORT")
if port == "" {
log.Fatal("PORT environment variable not specified")
}
browserRedirects := os.Getenv("DISABLE_BROWSER_REDIRECTS") == ""
registryHost := os.Getenv("REGISTRY_HOST")
if registryHost == "" {
log.Fatal("REGISTRY_HOST environment variable not specified (example: gcr.io)")
}
repoPrefix := os.Getenv("REPO_PREFIX")
if repoPrefix == "" {
log.Fatal("REPO_PREFIX environment variable not specified")
}
reg := registryConfig{
host: registryHost,
repoPrefix: repoPrefix,
}
tokenEndpoint, err := discoverTokenService(reg.host)
if err != nil {
log.Fatalf("target registry's token endpoint could not be discovered: %+v", err)
}
log.Printf("discovered token endpoint for backend registry: %s", tokenEndpoint)
var auth authenticator
if basic := os.Getenv("AUTH_HEADER"); basic != "" {
auth = authHeader(basic)
} else if gcpKey := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"); gcpKey != "" {
b, err := ioutil.ReadFile(gcpKey)
if err != nil {
log.Fatalf("could not read key file from %s: %+v", gcpKey, err)
}
log.Printf("using specified service account json key to authenticate proxied requests")
auth = authHeader("Basic " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("_json_key:%s", string(b)))))
}
mux := http.NewServeMux()
if browserRedirects {
mux.Handle("/", browserRedirectHandler(reg))
}
if tokenEndpoint != "" {
mux.Handle("/_token", tokenProxyHandler(tokenEndpoint, repoPrefix))
}
mux.Handle("/v2/", registryAPIProxy(reg, auth))
addr := fmt.Sprintf("%s:%s", host, port)
handler := captureHostHeader(mux)
log.Printf("starting to listen on %s", addr)
if cert, key := os.Getenv("TLS_CERT"), os.Getenv("TLS_KEY"); cert != "" && key != "" {
err = http.ListenAndServeTLS(addr, cert, key, handler)
} else {
err = http.ListenAndServe(addr, handler)
}
if err != http.ErrServerClosed {
log.Fatalf("listen error: %+v", err)
}
log.Printf("server shutdown successfully")
}
func discoverTokenService(registryHost string) (string, error) {
url := fmt.Sprintf("https://%s/v2/", registryHost)
resp, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("failed to query the registry host %s: %+v", registryHost, err)
}
hdr := resp.Header.Get("www-authenticate")
if hdr == "" {
return "", fmt.Errorf("www-authenticate header not returned from %s, cannot locate token endpoint", url)
}
matches := realm.FindStringSubmatch(hdr)
if len(matches) == 0 {
return "", fmt.Errorf("cannot locate 'realm' in %s response header www-authenticate: %s", url, hdr)
}
return matches[1], nil
}
// captureHostHeader is a middleware to capture Host header in a context key.
func captureHostHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := context.WithValue(req.Context(), ctxKeyOriginalHost, req.Host)
req = req.WithContext(ctx)
next.ServeHTTP(rw, req.WithContext(ctx))
})
}
// tokenProxyHandler proxies the token requests to the specified token service.
// It adjusts the ?scope= parameter in the query from "repository:foo:..." to
// "repository:repoPrefix/foo:.." and reverse proxies the query to the specified
// tokenEndpoint.
func tokenProxyHandler(tokenEndpoint, repoPrefix string) http.HandlerFunc {
return (&httputil.ReverseProxy{
FlushInterval: -1,
Director: func(r *http.Request) {
orig := r.URL.String()
q := r.URL.Query()
scope := q.Get("scope")
if scope == "" {
return
}
newScope := strings.Replace(scope, "repository:", fmt.Sprintf("repository:%s/", repoPrefix), 1)
q.Set("scope", newScope)
u, _ := url.Parse(tokenEndpoint)
u.RawQuery = q.Encode()
r.URL = u
log.Printf("tokenProxyHandler: rewrote url:%s into:%s", orig, r.URL)
r.Host = u.Host
},
}).ServeHTTP
}
// browserRedirectHandler redirects a request like example.com/my-image to
// REGISTRY_HOST/my-image, which shows a public UI for browsing the registry.
// This works only on registries that support a web UI when the image name is
// entered into the browser, like GCR (gcr.io/google-containers/busybox).
func browserRedirectHandler(cfg registryConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
url := fmt.Sprintf("https://%s/%s%s", cfg.host, cfg.repoPrefix, r.RequestURI)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
}
// registryAPIProxy returns a reverse proxy to the specified registry.
func registryAPIProxy(cfg registryConfig, auth authenticator) http.HandlerFunc {
return (&httputil.ReverseProxy{
FlushInterval: -1,
Director: rewriteRegistryV2URL(cfg),
Transport: ®istryRoundtripper{
auth: auth,
},
}).ServeHTTP
}
// rewriteRegistryV2URL rewrites request.URL like /v2/* that come into the server
// into https://[GCR_HOST]/v2/[PROJECT_ID]/*. It leaves /v2/ as is.
func rewriteRegistryV2URL(c registryConfig) func(*http.Request) {
return func(req *http.Request) {
u := req.URL.String()
req.Host = c.host
req.URL.Scheme = "https"
req.URL.Host = c.host
if req.URL.Path != "/v2/" {
req.URL.Path = re.ReplaceAllString(req.URL.Path, fmt.Sprintf("/v2/%s/", c.repoPrefix))
}
log.Printf("rewrote url: %s into %s", u, req.URL)
}
}
type registryRoundtripper struct {
auth authenticator
}
func (rrt *registryRoundtripper) RoundTrip(req *http.Request) (*http.Response, error) {
log.Printf("request received. url=%s", req.URL)
if rrt.auth != nil {
req.Header.Set("Authorization", rrt.auth.AuthHeader())
}
origHost := req.Context().Value(ctxKeyOriginalHost).(string)
if ua := req.Header.Get("user-agent"); ua != "" {
req.Header.Set("user-agent", "gcr-proxy/0.1 customDomain/"+origHost+" "+ua)
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err == nil {
log.Printf("request completed (status=%d) url=%s", resp.StatusCode, req.URL)
} else {
log.Printf("request failed with error: %+v", err)
return nil, err
}
// Google Artifact Registry sends a "location: /artifacts-downloads/..." URL
// to download blobs. We don't want these routed to the proxy itself.
if locHdr := resp.Header.Get("location"); req.Method == http.MethodGet &&
resp.StatusCode == http.StatusFound && strings.HasPrefix(locHdr, "/") {
resp.Header.Set("location", req.URL.Scheme+"://"+req.URL.Host+locHdr)
}
updateTokenEndpoint(resp, origHost)
return resp, nil
}
// updateTokenEndpoint modifies the response header like:
// Www-Authenticate: Bearer realm="https://auth.docker.io/token",service="registry.docker.io"
// to point to the https://host/token endpoint to force using local token
// endpoint proxy.
func updateTokenEndpoint(resp *http.Response, host string) {
v := resp.Header.Get("www-authenticate")
if v == "" {
return
}
cur := fmt.Sprintf("https://%s/_token", host)
resp.Header.Set("www-authenticate", realm.ReplaceAllString(v, fmt.Sprintf(`realm="%s"`, cur)))
}
type authenticator interface {
AuthHeader() string
}
type authHeader string
func (b authHeader) AuthHeader() string { return string(b) }