-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathroutes.go
666 lines (565 loc) · 19.1 KB
/
routes.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
// Copyright 2020 The Prometheus Authors
// 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
//
// http://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 injectproxy
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"sort"
"strings"
"github.com/efficientgo/core/merrors"
"github.com/metalmatze/signal/server/signalhttp"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
)
const (
queryParam = "query"
matchersParam = "match[]"
)
type routes struct {
upstream *url.URL
handler http.Handler
label string
el ExtractLabeler
mux http.Handler
modifiers map[string]func(*http.Response) error
errorOnReplace bool
}
type options struct {
enableLabelAPIs bool
passthroughPaths []string
errorOnReplace bool
registerer prometheus.Registerer
extraHttpHeaders map[string]string
rewriteHostHeader string
}
type Option interface {
apply(*options)
}
type optionFunc func(*options)
func (f optionFunc) apply(o *options) {
f(o)
}
// WithPrometheusRegistry configures the proxy to use the given registerer.
func WithPrometheusRegistry(reg prometheus.Registerer) Option {
return optionFunc(func(o *options) {
o.registerer = reg
})
}
// WithEnabledLabelsAPI enables proxying to labels API. If false, "501 Not implemented" will be return for those.
func WithEnabledLabelsAPI() Option {
return optionFunc(func(o *options) {
o.enableLabelAPIs = true
})
}
// WithPassthroughPaths configures routes to register given paths as passthrough handlers for all HTTP methods.
// that, if requested, will be forwarded without enforcing label. Use with care.
// NOTE: Passthrough "all" paths like "/" or "" and regex are not allowed.
func WithPassthroughPaths(paths []string) Option {
return optionFunc(func(o *options) {
o.passthroughPaths = paths
})
}
// WithErrorOnReplace causes the proxy to return 400 if a label matcher we want to
// inject is present in the query already and matches something different
func WithErrorOnReplace() Option {
return optionFunc(func(o *options) {
o.errorOnReplace = true
})
}
func WithExtraHttpHeader(key, value string) Option {
return optionFunc(func(o *options) {
o.extraHttpHeaders[key] = value
})
}
func WithRewriteHostHeader(host string) Option {
return optionFunc(func(o *options) {
o.rewriteHostHeader = host
})
}
// mux abstracts away the behavior we expect from the http.ServeMux type in this package.
type mux interface {
http.Handler
Handle(string, http.Handler)
}
// strictMux is a mux that wraps standard HTTP handler with safer handler that allows safe user provided handler registrations.
type strictMux struct {
mux
seen map[string]struct{}
}
func newStrictMux(m mux) *strictMux {
return &strictMux{
m,
map[string]struct{}{},
}
}
// Handle is like HTTP mux handle but it does not allow to register paths that are shared with previously registered paths.
// It also makes sure the trailing / is registered too.
// For example if /api/v1/federate was registered consequent registrations like /api/v1/federate/ or /api/v1/federate/some will
// return error. In the mean time request with both /api/v1/federate and /api/v1/federate/ will point to the handled passed by /api/v1/federate
// registration.
// This allows to de-risk ability for user to mis-configure and leak inject isolation.
func (s *strictMux) Handle(pattern string, handler http.Handler) error {
sanitized := pattern
for next := strings.TrimSuffix(sanitized, "/"); next != sanitized; sanitized = next {
}
if _, ok := s.seen[sanitized]; ok {
return fmt.Errorf("pattern %q was already registered", sanitized)
}
for p := range s.seen {
if strings.HasPrefix(sanitized+"/", p+"/") {
return fmt.Errorf("pattern %q is registered, cannot register path %q that shares it", p, sanitized)
}
}
s.mux.Handle(sanitized, handler)
s.mux.Handle(sanitized+"/", handler)
s.seen[sanitized] = struct{}{}
return nil
}
// instrumentedMux wraps a mux and instruments it.
type instrumentedMux struct {
mux
i signalhttp.HandlerInstrumenter
}
func newInstrumentedMux(m mux, r prometheus.Registerer) *instrumentedMux {
return &instrumentedMux{
m,
signalhttp.NewHandlerInstrumenter(r, []string{"handler"}),
}
}
// Handle implements the mux interface.
func (i *instrumentedMux) Handle(pattern string, handler http.Handler) {
i.mux.Handle(pattern, i.i.NewHandler(prometheus.Labels{"handler": pattern}, handler))
}
// ExtractLabeler is an HTTP handler that extract the label value to be
// enforced from the HTTP request. If a valid label value is found, it should
// store it in the request's context. Otherwise it should return an error in
// the HTTP response (usually 400 or 500).
type ExtractLabeler interface {
ExtractLabel(next http.HandlerFunc) http.Handler
}
// HTTPFormEnforcer enforces a label value extracted from the HTTP form and query parameters.
type HTTPFormEnforcer struct {
ParameterName string
}
// ExtractLabel implements the ExtractLabeler interface.
func (hff HTTPFormEnforcer) ExtractLabel(next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
labelValues, err := hff.getLabelValues(r)
if err != nil {
prometheusAPIError(w, humanFriendlyErrorMessage(err), http.StatusBadRequest)
return
}
// Remove the proxy label from the query parameters.
q := r.URL.Query()
q.Del(hff.ParameterName)
r.URL.RawQuery = q.Encode()
// Remove the param from the PostForm.
if r.Method == http.MethodPost {
if err := r.ParseForm(); err != nil {
prometheusAPIError(w, fmt.Sprintf("Failed to parse the PostForm: %v", err), http.StatusInternalServerError)
return
}
if r.PostForm.Get(hff.ParameterName) != "" {
r.PostForm.Del(hff.ParameterName)
newBody := r.PostForm.Encode()
// We are replacing request body, close previous one (r.FormValue ensures it is read fully and not nil).
_ = r.Body.Close()
r.Body = io.NopCloser(strings.NewReader(newBody))
r.ContentLength = int64(len(newBody))
}
}
next.ServeHTTP(w, r.WithContext(WithLabelValues(r.Context(), labelValues)))
})
}
func (hff HTTPFormEnforcer) getLabelValues(r *http.Request) ([]string, error) {
err := r.ParseForm()
if err != nil {
return nil, fmt.Errorf("the form data can not be parsed: %w", err)
}
formValues := removeEmptyValues(r.Form[hff.ParameterName])
if len(formValues) == 0 {
return nil, fmt.Errorf("the %q query parameter must be provided", hff.ParameterName)
}
return formValues, nil
}
// HTTPHeaderEnforcer enforces a label value extracted from the HTTP headers.
type HTTPHeaderEnforcer struct {
Name string
}
// ExtractLabel implements the ExtractLabeler interface.
func (hhe HTTPHeaderEnforcer) ExtractLabel(next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
labelValues, err := hhe.getLabelValues(r)
if err != nil {
prometheusAPIError(w, humanFriendlyErrorMessage(err), http.StatusBadRequest)
return
}
next.ServeHTTP(w, r.WithContext(WithLabelValues(r.Context(), labelValues)))
})
}
func (hhe HTTPHeaderEnforcer) getLabelValues(r *http.Request) ([]string, error) {
headerValues := removeEmptyValues(r.Header[hhe.Name])
if len(headerValues) == 0 {
return nil, fmt.Errorf("missing HTTP header %q", hhe.Name)
}
return headerValues, nil
}
// StaticLabelEnforcer enforces a static label value.
type StaticLabelEnforcer []string
// ExtractLabel implements the ExtractLabeler interface.
func (sle StaticLabelEnforcer) ExtractLabel(next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next(w, r.WithContext(WithLabelValues(r.Context(), sle)))
})
}
func NewRoutes(upstream *url.URL, label string, extractLabeler ExtractLabeler, opts ...Option) (*routes, error) {
opt := options{}
for _, o := range opts {
o.apply(&opt)
}
if opt.registerer == nil {
opt.registerer = prometheus.NewRegistry()
}
proxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.SetURL(upstream)
if opt.rewriteHostHeader == "" {
r.Out.Host = r.In.Host
} else {
r.Out.Host = opt.rewriteHostHeader
}
for header, val := range opt.extraHttpHeaders {
r.Out.Header.Set(header, val)
}
},
}
r := &routes{
upstream: upstream,
handler: proxy,
label: label,
el: extractLabeler,
errorOnReplace: opt.errorOnReplace,
}
mux := newStrictMux(newInstrumentedMux(http.NewServeMux(), opt.registerer))
errs := merrors.New(
mux.Handle("/federate", r.el.ExtractLabel(enforceMethods(r.matcher, "GET"))),
mux.Handle("/api/v1/query", r.el.ExtractLabel(enforceMethods(r.query, "GET", "POST"))),
mux.Handle("/api/v1/query_range", r.el.ExtractLabel(enforceMethods(r.query, "GET", "POST"))),
mux.Handle("/api/v1/alerts", r.el.ExtractLabel(enforceMethods(r.passthrough, "GET"))),
mux.Handle("/api/v1/rules", r.el.ExtractLabel(enforceMethods(r.passthrough, "GET"))),
mux.Handle("/api/v1/series", r.el.ExtractLabel(enforceMethods(r.matcher, "GET", "POST"))),
mux.Handle("/api/v1/query_exemplars", r.el.ExtractLabel(enforceMethods(r.query, "GET", "POST"))),
)
if opt.enableLabelAPIs {
errs.Add(
mux.Handle("/api/v1/labels", r.el.ExtractLabel(enforceMethods(r.matcher, "GET", "POST"))),
// Full path is /api/v1/label/<label_name>/values but http mux does not support patterns.
// This is fine though as we don't care about name for matcher injector.
mux.Handle("/api/v1/label/", r.el.ExtractLabel(enforceMethods(r.matcher, "GET"))),
)
}
errs.Add(
// Reject multi label values with assertSingleLabelValue() because the
// semantics of the Silences API don't support multi-label matchers.
mux.Handle("/api/v2/silences", r.el.ExtractLabel(
enforceMethods(
assertSingleLabelValue(r.silences),
"GET", "POST",
),
)),
mux.Handle("/api/v2/silence/", r.el.ExtractLabel(
enforceMethods(
assertSingleLabelValue(r.deleteSilence),
"DELETE",
),
)),
mux.Handle("/api/v2/alerts/groups", r.el.ExtractLabel(enforceMethods(r.enforceFilterParameter, "GET"))),
mux.Handle("/api/v2/alerts", r.el.ExtractLabel(enforceMethods(r.alerts, "GET"))),
)
errs.Add(
mux.Handle("/healthz", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
})),
)
if err := errs.Err(); err != nil {
return nil, err
}
// Validate paths.
for _, path := range opt.passthroughPaths {
u, err := url.Parse(fmt.Sprintf("http://example.com%v", path))
if err != nil {
return nil, fmt.Errorf("path %q is not a valid URI path, got %v", path, opt.passthroughPaths)
}
if u.Path != path {
return nil, fmt.Errorf("path %q is not a valid URI path, got %v", path, opt.passthroughPaths)
}
if u.Path == "" || u.Path == "/" {
return nil, fmt.Errorf("path %q is not allowed, got %v", u.Path, opt.passthroughPaths)
}
}
// Register optional passthrough paths.
for _, path := range opt.passthroughPaths {
if err := mux.Handle(path, http.HandlerFunc(r.passthrough)); err != nil {
return nil, err
}
}
r.mux = mux
r.modifiers = map[string]func(*http.Response) error{
"/api/v1/rules": modifyAPIResponse(r.filterRules),
"/api/v1/alerts": modifyAPIResponse(r.filterAlerts),
}
proxy.ModifyResponse = r.ModifyResponse
return r, nil
}
func (r *routes) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.mux.ServeHTTP(w, req)
}
func (r *routes) ModifyResponse(resp *http.Response) error {
m, found := r.modifiers[resp.Request.URL.Path]
if !found {
// Return the server's response unmodified.
return nil
}
return m(resp)
}
func enforceMethods(h http.HandlerFunc, methods ...string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
for _, m := range methods {
if m == req.Method {
h(w, req)
return
}
}
http.NotFound(w, req)
}
}
type ctxKey int
const keyLabel ctxKey = iota
// MustLabelValues returns labels (previously stored using WithLabelValue())
// from the given context.
// It will panic if no label is found or the value is empty.
func MustLabelValues(ctx context.Context) []string {
labels, ok := ctx.Value(keyLabel).([]string)
if !ok {
panic(fmt.Sprintf("can't find the %q value in the context", keyLabel))
}
if len(labels) == 0 {
panic(fmt.Sprintf("empty %q value in the context", keyLabel))
}
sort.Strings(labels)
return labels
}
// MustLabelValue returns the first (alphabetical order) label value previously
// stored using WithLabelValue() from the given context.
// Similar to MustLabelValues, it will panic if no label is found or the value
// is empty.
func MustLabelValue(ctx context.Context) string {
v := MustLabelValues(ctx)
return v[0]
}
func labelValuesToRegexpString(labelValues []string) string {
lvs := make([]string, len(labelValues))
for i := range labelValues {
lvs[i] = regexp.QuoteMeta(labelValues[i])
}
return strings.Join(lvs, "|")
}
// WithLabelValues stores labels in the given context.
func WithLabelValues(ctx context.Context, labels []string) context.Context {
return context.WithValue(ctx, keyLabel, labels)
}
func (r *routes) passthrough(w http.ResponseWriter, req *http.Request) {
r.handler.ServeHTTP(w, req)
}
func (r *routes) query(w http.ResponseWriter, req *http.Request) {
var matcher *labels.Matcher
if len(MustLabelValues(req.Context())) > 1 {
matcher = &labels.Matcher{
Name: r.label,
Type: labels.MatchRegexp,
Value: labelValuesToRegexpString(MustLabelValues(req.Context())),
}
} else {
matcher = &labels.Matcher{
Name: r.label,
Type: labels.MatchEqual,
Value: MustLabelValue(req.Context()),
}
}
e := NewEnforcer(r.errorOnReplace, matcher)
// The `query` can come in the URL query string and/or the POST body.
// For this reason, we need to try to enforcing in both places.
// Note: a POST request may include some values in the URL query string
// and others in the body. If both locations include a `query`, then
// enforce in both places.
q, found1, err := enforceQueryValues(e, req.URL.Query())
if err != nil {
switch err.(type) {
case IllegalLabelMatcherError:
prometheusAPIError(w, err.Error(), http.StatusBadRequest)
case queryParseError:
prometheusAPIError(w, err.Error(), http.StatusBadRequest)
case enforceLabelError:
prometheusAPIError(w, err.Error(), http.StatusInternalServerError)
}
return
}
req.URL.RawQuery = q
var found2 bool
// Enforce the query in the POST body if needed.
if req.Method == http.MethodPost {
if err := req.ParseForm(); err != nil {
prometheusAPIError(w, err.Error(), http.StatusBadRequest)
}
q, found2, err = enforceQueryValues(e, req.PostForm)
if err != nil {
switch err.(type) {
case IllegalLabelMatcherError:
prometheusAPIError(w, err.Error(), http.StatusBadRequest)
case queryParseError:
prometheusAPIError(w, err.Error(), http.StatusBadRequest)
case enforceLabelError:
prometheusAPIError(w, err.Error(), http.StatusInternalServerError)
}
return
}
// We are replacing request body, close previous one (ParseForm ensures it is read fully and not nil).
_ = req.Body.Close()
req.Body = io.NopCloser(strings.NewReader(q))
req.ContentLength = int64(len(q))
}
// If no query was found, return early.
if !found1 && !found2 {
return
}
r.handler.ServeHTTP(w, req)
}
func enforceQueryValues(e *Enforcer, v url.Values) (values string, noQuery bool, err error) {
// If no values were given or no query is present,
// e.g. because the query came in the POST body
// but the URL query string was passed, then finish early.
if v.Get(queryParam) == "" {
return v.Encode(), false, nil
}
expr, err := parser.ParseExpr(v.Get(queryParam))
if err != nil {
queryParseError := newQueryParseError(err)
return "", true, queryParseError
}
if err := e.EnforceNode(expr); err != nil {
if _, ok := err.(IllegalLabelMatcherError); ok {
return "", true, err
}
enforceLabelError := newEnforceLabelError(err)
return "", true, enforceLabelError
}
v.Set(queryParam, expr.String())
return v.Encode(), true, nil
}
// matcher ensures all the provided match[] if any has label injected. If none was provided, single matcher is injected.
// This works for non-query Prometheus APIs like: /api/v1/series, /api/v1/label/<name>/values, /api/v1/labels and /federate support multiple matchers.
// See e.g https://prometheus.io/docs/prometheus/latest/querying/api/#querying-metadata
func (r *routes) matcher(w http.ResponseWriter, req *http.Request) {
matcher := &labels.Matcher{
Name: r.label,
Type: labels.MatchRegexp,
Value: labelValuesToRegexpString(MustLabelValues(req.Context())),
}
q := req.URL.Query()
if err := injectMatcher(q, matcher); err != nil {
return
}
req.URL.RawQuery = q.Encode()
if req.Method == http.MethodPost {
if err := req.ParseForm(); err != nil {
return
}
q = req.PostForm
if err := injectMatcher(q, matcher); err != nil {
return
}
// We are replacing request body, close previous one (ParseForm ensures it is read fully and not nil).
_ = req.Body.Close()
newBody := q.Encode()
req.Body = io.NopCloser(strings.NewReader(newBody))
req.ContentLength = int64(len(newBody))
}
r.handler.ServeHTTP(w, req)
}
func injectMatcher(q url.Values, matcher *labels.Matcher) error {
matchers := q[matchersParam]
if len(matchers) == 0 {
q.Set(matchersParam, matchersToString(matcher))
return nil
}
// Inject label into existing matchers.
for i, m := range matchers {
ms, err := parser.ParseMetricSelector(m)
if err != nil {
return err
}
matchers[i] = matchersToString(append(ms, matcher)...)
}
q[matchersParam] = matchers
return nil
}
func matchersToString(ms ...*labels.Matcher) string {
var el []string
for _, m := range ms {
el = append(el, m.String())
}
return fmt.Sprintf("{%v}", strings.Join(el, ","))
}
type queryParseError struct {
msg string
}
func (e queryParseError) Error() string {
return e.msg
}
func newQueryParseError(err error) queryParseError {
return queryParseError{msg: fmt.Sprintf("error parsing query string %q", err.Error())}
}
type enforceLabelError struct {
msg string
}
func (e enforceLabelError) Error() string {
return e.msg
}
func newEnforceLabelError(err error) enforceLabelError {
return enforceLabelError{msg: fmt.Sprintf("error enforcing label %q", err.Error())}
}
// humanFriendlyErrorMessage returns an error message with a capitalized first letter
// and a punctuation at the end.
func humanFriendlyErrorMessage(err error) string {
if err == nil {
return ""
}
errMsg := err.Error()
return fmt.Sprintf("%s%s.", strings.ToUpper(errMsg[:1]), errMsg[1:])
}
func removeEmptyValues(slice []string) []string {
for i := 0; i < len(slice); i++ {
if slice[i] == "" {
slice = append(slice[:i], slice[i+1:]...)
i--
}
}
return slice
}