-
Notifications
You must be signed in to change notification settings - Fork 23
/
checkhttp.go
487 lines (427 loc) · 16.5 KB
/
checkhttp.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
package checkhttp
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"mime"
"mime/multipart"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/util"
"google.golang.org/genproto/googleapis/rpc/code"
"google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
flowcontrolv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/flowcontrol/check/v1"
flowcontrolhttpv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/flowcontrol/checkhttp/v1"
"github.com/fluxninja/aperture/v2/pkg/log"
"github.com/fluxninja/aperture/v2/pkg/net/grpc"
otelconsts "github.com/fluxninja/aperture/v2/pkg/otelcollector/consts"
"github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/iface"
flowlabel "github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/label"
classification "github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/resources/classifier"
servicegetter "github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/service-getter"
"github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/service/check"
checkhttp_baggage "github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/service/checkhttp/baggage"
)
var baggageSanitizeRegex *regexp.Regexp = regexp.MustCompile(`[\s\\\/;",]`)
var (
missingControlPointSampler = log.NewRatelimitingSampler()
failedBaggageInjectionSampler = log.NewRatelimitingSampler()
)
// NewHandler creates new handler for flowcontrol CheckHTTP
//
// It will use the given classifier to inject flow labels and return them as
// metadata in the response to the Check calls.
func NewHandler(
classifier *classification.ClassificationEngine,
serviceGetter servicegetter.ServiceGetter,
fcHandler check.HandlerWithValues,
) *Handler {
return &Handler{
classifier: classifier,
serviceGetter: serviceGetter,
propagator: checkhttp_baggage.W3Baggage{},
fcHandler: fcHandler,
}
}
// sanitizeBaggageHeaderValue excludes characters that should be url escaped
// Otherwise both baggage.String method and envoy itself will do it.
func sanitizeBaggageHeaderValue(value string) string {
// All characters allowed except control chars, whitespace, double quote, comma, semicolon, backslash
// see https://www.w3.org/TR/baggage/#header-content
cleanValue := baggageSanitizeRegex.ReplaceAll([]byte(value), []byte("-"))
return string(cleanValue)
}
// Handler implements aperture.flowcontrol.v1.FlowControlServiceHTTP and handles Check call.
type Handler struct {
flowcontrolhttpv1.UnimplementedFlowControlServiceHTTPServer
serviceGetter servicegetter.ServiceGetter
classifier *classification.ClassificationEngine
propagator checkhttp_baggage.Propagator
fcHandler check.HandlerWithValues
}
// CheckHTTP is the Check method of Flow Control service returns the allow/deny decisions of
// whether to accept the traffic after running the algorithms.
func (h *Handler) CheckHTTP(ctx context.Context, req *flowcontrolhttpv1.CheckHTTPRequest) (*flowcontrolhttpv1.CheckHTTPResponse, error) {
// record the start time of the request
start := time.Now()
createResponse := func(checkResponse *flowcontrolv1.CheckResponse) *flowcontrolhttpv1.CheckHTTPResponse {
marshalledCheckResponse, err := proto.Marshal(checkResponse)
if err != nil {
log.Bug().Err(err).Msg("bug: Failed to marshal check response")
return nil
}
checkResponseBase64 := base64.StdEncoding.EncodeToString(marshalledCheckResponse)
// record the end time of the request
end := time.Now()
checkResponse.Start = timestamppb.New(start)
checkResponse.End = timestamppb.New(end)
return &flowcontrolhttpv1.CheckHTTPResponse{
DynamicMetadata: &structpb.Struct{
Fields: map[string]*structpb.Value{
otelconsts.ApertureCheckResponseLabel: structpb.NewStringValue(checkResponseBase64),
},
},
}
}
ctrlPt := req.GetControlPoint()
if ctrlPt == "" {
return nil, grpc.LoggedError(log.Sample(missingControlPointSampler).Warn()).
Code(codes.InvalidArgument).Msg("missing control-point")
}
sourceAddress := req.GetSource().GetAddress()
sourceSvcs := h.serviceGetter.ServicesFromAddress(sourceAddress)
if sourceSvcs == nil {
sourceSvcs = []string{"UNKNOWN"}
}
sourceSvcsStr := strings.Join(sourceSvcs, ",")
destinationAddress := req.GetDestination().GetAddress()
destinationSvcs := h.serviceGetter.ServicesFromAddress(destinationAddress)
if destinationSvcs == nil {
sourceSvcs = []string{"UNKNOWN"}
}
destinationSvcsStr := strings.Join(destinationSvcs, ",")
// make flowlabels from source and destination services
sdFlowLabels := make(flowlabel.FlowLabels, 2)
sdFlowLabels[otelconsts.ApertureSourceServiceLabel] = flowlabel.FlowLabelValue{
Value: sourceSvcsStr,
Telemetry: true,
}
sdFlowLabels[otelconsts.ApertureDestinationServiceLabel] = flowlabel.FlowLabelValue{
Value: destinationSvcsStr,
Telemetry: true,
}
input := RequestToInputWithServices(req, sourceSvcs, destinationSvcs)
// Default flow labels from request
requestFlowLabels := CheckHTTPRequestToFlowLabels(req.GetRequest())
existingHeaders := checkhttp_baggage.Headers(req.GetRequest().GetHeaders())
baggageFlowLabels := h.propagator.Extract(existingHeaders)
// Merge flow labels from request and baggage headers
mergedFlowLabels := requestFlowLabels
// Baggage can overwrite request flow labels
flowlabel.Merge(mergedFlowLabels, baggageFlowLabels)
flowlabel.Merge(mergedFlowLabels, sdFlowLabels)
classifierMsgs, newFlowLabels := h.classifier.Classify(ctx, destinationSvcs, ctrlPt, mergedFlowLabels.ToPlainMap(), input)
for key, fl := range newFlowLabels {
cleanValue := sanitizeBaggageHeaderValue(fl.Value)
fl.Value = cleanValue
newFlowLabels[key] = fl
}
// Add new flow labels to baggage
newHeaders, err := h.propagator.Inject(newFlowLabels, existingHeaders)
if err != nil {
log.Sample(failedBaggageInjectionSampler).
Warn().Err(err).Msg("Failed to inject baggage into headers")
}
// Make the freshly created flow labels available to flowcontrol.
// Newly created flow labels can overwrite existing flow labels.
flowlabel.Merge(mergedFlowLabels, newFlowLabels)
flowLabels := mergedFlowLabels.ToPlainMap()
// Ask flow control service for Ok/Deny
// checkResponse := h.fcHandler.CheckRequest(ctx, destinationSvcs, ctrlPt, flowLabels)
checkResponse := h.fcHandler.CheckRequest(ctx,
iface.RequestContext{
Services: destinationSvcs,
ControlPoint: ctrlPt,
FlowLabels: flowLabels,
},
)
checkResponse.ClassifierInfos = classifierMsgs
// Set telemetry_flow_labels in the CheckResponse
checkResponse.TelemetryFlowLabels = flowLabels
// add control point type
checkResponse.TelemetryFlowLabels[otelconsts.ApertureControlPointTypeLabel] = otelconsts.HTTPControlPoint
checkResponse.TelemetryFlowLabels[otelconsts.ApertureSourceServiceLabel] = strings.Join(sourceSvcs, ",")
checkResponse.TelemetryFlowLabels[otelconsts.ApertureDestinationServiceLabel] = strings.Join(destinationSvcs, ",")
resp := createResponse(checkResponse)
switch checkResponse.DecisionType {
case flowcontrolv1.CheckResponse_DECISION_TYPE_ACCEPTED:
resp.Status = &status.Status{
Code: int32(code.Code_OK),
}
resp.HttpResponse = &flowcontrolhttpv1.CheckHTTPResponse_OkResponse{
OkResponse: &flowcontrolhttpv1.OkHttpResponse{
Headers: newHeaders,
},
}
case flowcontrolv1.CheckResponse_DECISION_TYPE_REJECTED:
resp.Status = &status.Status{
Code: int32(code.Code_UNAVAILABLE),
}
switch checkResponse.RejectReason {
case flowcontrolv1.CheckResponse_REJECT_REASON_RATE_LIMITED:
resp.HttpResponse = &flowcontrolhttpv1.CheckHTTPResponse_DeniedResponse{
DeniedResponse: &flowcontrolhttpv1.DeniedHttpResponse{
Status: http.StatusTooManyRequests,
},
}
case flowcontrolv1.CheckResponse_REJECT_REASON_NO_TOKENS:
resp.HttpResponse = &flowcontrolhttpv1.CheckHTTPResponse_DeniedResponse{
DeniedResponse: &flowcontrolhttpv1.DeniedHttpResponse{
Status: http.StatusServiceUnavailable,
},
}
case flowcontrolv1.CheckResponse_REJECT_REASON_REGULATED:
resp.HttpResponse = &flowcontrolhttpv1.CheckHTTPResponse_DeniedResponse{
DeniedResponse: &flowcontrolhttpv1.DeniedHttpResponse{
Status: http.StatusForbidden,
},
}
default:
log.Bug().Stringer("reason", checkResponse.RejectReason).Msg("Unexpected reject reason")
}
default:
return nil, grpc.Bug().Stringer("type", checkResponse.DecisionType).
Msg("unexpected decision type")
}
return resp, nil
}
// RequestToInput - Converts a CheckHTTPRequest to an input map.
func RequestToInput(req *flowcontrolhttpv1.CheckHTTPRequest) ast.Value {
return RequestToInputWithServices(req, nil, nil)
}
// RequestToInputWithServices - Converts a CheckHTTPRequest to an input map
// Additionally sets attributes.source.services and attributes.destination.services with discovered services.
func RequestToInputWithServices(req *flowcontrolhttpv1.CheckHTTPRequest, sourceSvcs, destinationSvcs []string) ast.Value {
request := req.GetRequest()
path := request.GetPath()
body := request.GetBody()
headers := request.GetHeaders()
http := ast.NewObject()
http.Insert(ast.StringTerm("path"), ast.StringTerm(path))
http.Insert(ast.StringTerm("body"), ast.StringTerm(body))
http.Insert(ast.StringTerm("host"), ast.StringTerm(request.GetHost()))
http.Insert(ast.StringTerm("method"), ast.StringTerm(request.GetMethod()))
http.Insert(ast.StringTerm("scheme"), ast.StringTerm(request.GetScheme()))
http.Insert(ast.StringTerm("size"),
ast.NumberTerm(json.Number(strconv.FormatInt(request.GetSize(), 10))))
http.Insert(ast.StringTerm("protocol"), ast.StringTerm(request.GetProtocol()))
headersObj := ast.NewObject()
for key, val := range headers {
headersObj.Insert(ast.StringTerm(key), ast.StringTerm(val))
}
http.Insert(ast.StringTerm("headers"), ast.NewTerm(headersObj))
srcSocketAddress := ast.NewObject()
srcSocketAddress.Insert(ast.StringTerm("address"), ast.StringTerm(req.GetSource().GetAddress()))
srcSocketAddress.Insert(ast.StringTerm("port"),
ast.NumberTerm(json.Number(strconv.FormatUint(uint64(req.GetSource().GetPort()), 10))))
dstSocketAddress := ast.NewObject()
dstSocketAddress.Insert(ast.StringTerm("address"), ast.StringTerm(req.GetDestination().GetAddress()))
dstSocketAddress.Insert(ast.StringTerm("port"),
ast.NumberTerm(json.Number(strconv.FormatUint(uint64(req.GetDestination().GetPort()), 10))))
source := ast.NewObject()
source.Insert(ast.StringTerm("socketAddress"), ast.NewTerm(srcSocketAddress))
if sourceSvcs != nil {
srcServicesArray := make([]*ast.Term, 0)
for _, svc := range sourceSvcs {
srcServicesArray = append(srcServicesArray, ast.StringTerm(svc))
}
source.Insert(ast.StringTerm("source_fqdns"), ast.NewTerm(ast.NewArray(srcServicesArray...)))
}
destination := ast.NewObject()
destination.Insert(ast.StringTerm("socketAddress"), ast.NewTerm(dstSocketAddress))
if destinationSvcs != nil {
dstServicesArray := make([]*ast.Term, 0)
for _, svc := range destinationSvcs {
dstServicesArray = append(dstServicesArray, ast.StringTerm(svc))
}
destination.Insert(ast.StringTerm("destination_fqdns"), ast.NewTerm(ast.NewArray(dstServicesArray...)))
}
requestMap := ast.NewObject()
requestMap.Insert(ast.StringTerm("http"), ast.NewTerm(http))
attributes := ast.NewObject()
attributes.Insert(ast.StringTerm("request"), ast.NewTerm(requestMap))
attributes.Insert(ast.StringTerm("source"), ast.NewTerm(source))
attributes.Insert(ast.StringTerm("destination"), ast.NewTerm(destination))
input := ast.NewObject()
input.Insert(ast.StringTerm("attributes"), ast.NewTerm(attributes))
parsedPath, parsedQuery, err := getParsedPathAndQuery(path)
if err == nil {
input.Insert(ast.StringTerm("parsed_path"), parsedPath)
input.Insert(ast.StringTerm("parsed_query"), parsedQuery)
}
parsedBody, isBodyTruncated, err := getParsedBody(headers, body)
if err == nil {
input.Insert(ast.StringTerm("parsed_body"), parsedBody)
input.Insert(ast.StringTerm("truncated_body"), ast.BooleanTerm(isBodyTruncated))
}
return input
}
func getParsedPathAndQuery(path string) (*ast.Term, *ast.Term, error) {
parsedURL, err := url.Parse(path)
if err != nil {
return ast.NullTerm(), ast.NullTerm(), err
}
parsedPath := strings.Split(strings.TrimLeft(parsedURL.Path, "/"), "/")
parsedPathSlice := make([]*ast.Term, 0)
for _, v := range parsedPath {
parsedPathSlice = append(parsedPathSlice, ast.StringTerm(v))
}
parsedQueryInterface := ast.NewObject()
for paramKey, paramValues := range parsedURL.Query() {
queryValues := make([]*ast.Term, 0)
for _, v := range paramValues {
queryValues = append(queryValues, ast.StringTerm(v))
}
parsedQueryInterface.Insert(ast.StringTerm(paramKey), ast.NewTerm(ast.NewArray(queryValues...)))
}
return ast.NewTerm(ast.NewArray(parsedPathSlice...)), ast.NewTerm(parsedQueryInterface), nil
}
func getParsedBody(headers map[string]string, body string) (*ast.Term, bool, error) {
data := ast.NewObject()
if val, ok := headers["content-type"]; ok {
if strings.Contains(val, "application/json") {
if body == "" {
return ast.NullTerm(), false, nil
}
if headerVal, ok := headers["content-length"]; ok {
truncated, err := checkIfHTTPBodyTruncated(headerVal, int64(len(body)))
if err != nil {
return ast.NullTerm(), false, err
}
if truncated {
return ast.NullTerm(), true, nil
}
}
astValue, err := ast.ValueFromReader(bytes.NewReader([]byte(body)))
if err != nil {
return ast.NullTerm(), false, err
}
return ast.NewTerm(astValue), false, nil
} else if strings.Contains(val, "application/x-www-form-urlencoded") {
var payload string
switch {
case body != "":
payload = body
default:
return ast.NullTerm(), false, nil
}
if headerVal, ok := headers["content-length"]; ok {
truncated, err := checkIfHTTPBodyTruncated(headerVal, int64(len(payload)))
if err != nil {
return ast.NullTerm(), false, err
}
if truncated {
return ast.NullTerm(), true, nil
}
}
parsed, err := url.ParseQuery(payload)
if err != nil {
return ast.NullTerm(), false, err
}
for key, valArray := range parsed {
helperArr := make([]*ast.Term, 0)
for _, val := range valArray {
helperArr = append(helperArr, ast.StringTerm(val))
}
data.Insert(ast.StringTerm(key), ast.NewTerm(ast.NewArray(helperArr...)))
}
} else if strings.Contains(val, "multipart/form-data") {
var payload string
switch {
case body != "":
payload = body
default:
return ast.NullTerm(), false, nil
}
if headerVal, ok := headers["content-length"]; ok {
truncated, err := checkIfHTTPBodyTruncated(headerVal, int64(len(payload)))
if err != nil {
return ast.NullTerm(), false, err
}
if truncated {
return ast.NullTerm(), true, nil
}
}
_, params, err := mime.ParseMediaType(headers["content-type"])
if err != nil {
return ast.NullTerm(), false, err
}
boundary, ok := params["boundary"]
if !ok {
return ast.NullTerm(), false, nil
}
values := ast.NewObject()
mr := multipart.NewReader(strings.NewReader(payload), boundary)
for {
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return ast.NullTerm(), false, err
}
name := p.FormName()
if name == "" {
continue
}
value, err := io.ReadAll(p)
if err != nil {
return ast.NullTerm(), false, err
}
switch {
case strings.Contains(p.Header.Get("Content-Type"), "application/json"):
var jsonValue interface{}
if err := util.UnmarshalJSON(value, &jsonValue); err != nil {
return ast.NullTerm(), false, err
}
jsonData, err := ast.InterfaceToValue(jsonValue)
if err != nil {
return ast.NullTerm(), false, err
}
values.Insert(ast.StringTerm(name),
ast.NewTerm(ast.NewArray(ast.NewTerm(jsonData))))
default:
values.Insert(ast.StringTerm(name),
ast.NewTerm(ast.NewArray((ast.StringTerm(string(value))))))
}
}
data = values
} else {
log.Debug().Msgf("rego content-type: %s parsing not supported", val)
}
} else {
log.Debug().Msg("rego no content-type header supplied, performing no body parsing")
}
return ast.NewTerm(data), false, nil
}
func checkIfHTTPBodyTruncated(contentLength string, bodyLength int64) (bool, error) {
cl, err := strconv.ParseInt(contentLength, 10, 64)
if err != nil {
return false, err
}
if cl != -1 && cl > bodyLength {
return true, nil
}
return false, nil
}