1// Licensed to Elasticsearch B.V. under one or more contributor
2// license agreements. See the NOTICE file distributed with
3// this work for additional information regarding copyright
4// ownership. Elasticsearch B.V. licenses this file to you under
5// the Apache License, Version 2.0 (the "License"); you may
6// not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9//     http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package apm
19
20import (
21	"go.elastic.co/apm/internal/wildcard"
22	"go.elastic.co/apm/model"
23)
24
25const redacted = "[REDACTED]"
26
27// sanitizeRequest sanitizes HTTP request data, redacting the
28// values of cookies, headers and forms whose corresponding keys
29// match any of the given wildcard patterns.
30func sanitizeRequest(r *model.Request, matchers wildcard.Matchers) {
31	for _, c := range r.Cookies {
32		if !matchers.MatchAny(c.Name) {
33			continue
34		}
35		c.Value = redacted
36	}
37	sanitizeHeaders(r.Headers, matchers)
38	if r.Body != nil && r.Body.Form != nil {
39		for key, values := range r.Body.Form {
40			if !matchers.MatchAny(key) {
41				continue
42			}
43			for i := range values {
44				values[i] = redacted
45			}
46		}
47	}
48}
49
50// sanitizeResponse sanitizes HTTP response data, redacting
51// the values of response headers whose corresponding keys
52// match any of the given wildcard patterns.
53func sanitizeResponse(r *model.Response, matchers wildcard.Matchers) {
54	sanitizeHeaders(r.Headers, matchers)
55}
56
57func sanitizeHeaders(headers model.Headers, matchers wildcard.Matchers) {
58	for i := range headers {
59		h := &headers[i]
60		if !matchers.MatchAny(h.Key) || len(h.Values) == 0 {
61			continue
62		}
63		h.Values = h.Values[:1]
64		h.Values[0] = redacted
65	}
66}
67