summaryrefslogtreecommitdiff
path: root/modules/caddyhttp/matchers.go
blob: 0179dd7b3511d58678e28258aab9d8620d8e7e9c (plain)
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
package caddyhttp

import (
	"fmt"
	"log"
	"net/http"
	"net/textproto"
	"net/url"
	"regexp"
	"strings"

	"bitbucket.org/lightcodelabs/caddy2"
	"bitbucket.org/lightcodelabs/caddy2/internal/caddyscript"
	"go.starlark.net/starlark"
)

type (
	matchHost     []string
	matchPath     []string
	matchPathRE   struct{ matchRegexp }
	matchMethod   []string
	matchQuery    url.Values
	matchHeader   http.Header
	matchHeaderRE map[string]*matchRegexp
	matchProtocol string
	matchStarlark string
)

func init() {
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.host",
		New:  func() (interface{}, error) { return matchHost{}, nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.path",
		New:  func() (interface{}, error) { return matchPath{}, nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.path_regexp",
		New:  func() (interface{}, error) { return new(matchPathRE), nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.method",
		New:  func() (interface{}, error) { return matchMethod{}, nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.query",
		New:  func() (interface{}, error) { return matchQuery{}, nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.header",
		New:  func() (interface{}, error) { return matchHeader{}, nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.header_regexp",
		New:  func() (interface{}, error) { return matchHeaderRE{}, nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.protocol",
		New:  func() (interface{}, error) { return new(matchProtocol), nil },
	})
	caddy2.RegisterModule(caddy2.Module{
		Name: "http.matchers.caddyscript",
		New:  func() (interface{}, error) { return new(matchStarlark), nil },
	})
}

func (m matchHost) Match(r *http.Request) bool {
outer:
	for _, host := range m {
		if strings.Contains(host, "*") {
			patternParts := strings.Split(host, ".")
			incomingParts := strings.Split(r.Host, ".")
			if len(patternParts) != len(incomingParts) {
				continue
			}
			for i := range patternParts {
				if patternParts[i] == "*" {
					continue
				}
				if !strings.EqualFold(patternParts[i], incomingParts[i]) {
					continue outer
				}
			}
			return true
		} else if strings.EqualFold(r.Host, host) {
			return true
		}
	}
	return false
}

func (m matchPath) Match(r *http.Request) bool {
	for _, path := range m {
		if strings.HasPrefix(r.URL.Path, path) {
			return true
		}
	}
	return false
}

func (m matchPathRE) Match(r *http.Request) bool {
	repl := r.Context().Value(ReplacerCtxKey).(*Replacer)
	return m.match(r.URL.Path, repl, "path_regexp")
}

func (m matchMethod) Match(r *http.Request) bool {
	for _, method := range m {
		if r.Method == method {
			return true
		}
	}
	return false
}

func (m matchQuery) Match(r *http.Request) bool {
	for param, vals := range m {
		paramVal := r.URL.Query().Get(param)
		for _, v := range vals {
			if paramVal == v {
				return true
			}
		}
	}
	return false
}

func (m matchHeader) Match(r *http.Request) bool {
	for field, allowedFieldVals := range m {
		var match bool
		actualFieldVals := r.Header[textproto.CanonicalMIMEHeaderKey(field)]
	fieldVals:
		for _, actualFieldVal := range actualFieldVals {
			for _, allowedFieldVal := range allowedFieldVals {
				if actualFieldVal == allowedFieldVal {
					match = true
					break fieldVals
				}
			}
		}
		if !match {
			return false
		}
	}
	return true
}

func (m matchHeaderRE) Match(r *http.Request) bool {
	for field, rm := range m {
		repl := r.Context().Value(ReplacerCtxKey).(*Replacer)
		match := rm.match(r.Header.Get(field), repl, "header_regexp")
		if !match {
			return false
		}
	}
	return true
}

func (m matchHeaderRE) Provision() error {
	for _, rm := range m {
		err := rm.Provision()
		if err != nil {
			return err
		}
	}
	return nil
}

func (m matchHeaderRE) Validate() error {
	for _, rm := range m {
		err := rm.Validate()
		if err != nil {
			return err
		}
	}
	return nil
}

func (m matchProtocol) Match(r *http.Request) bool {
	switch string(m) {
	case "grpc":
		return r.Header.Get("content-type") == "application/grpc"
	case "https":
		return r.TLS != nil
	case "http":
		return r.TLS == nil
	}
	return false
}

func (m matchStarlark) Match(r *http.Request) bool {
	input := string(m)
	thread := new(starlark.Thread)
	env := caddyscript.MatcherEnv(r)
	val, err := starlark.Eval(thread, "", input, env)
	if err != nil {
		// TODO: Can we detect this in Provision or Validate instead?
		log.Printf("caddyscript for matcher is invalid: attempting to evaluate expression `%v` error `%v`", input, err)
		return false
	}
	return val.String() == "True"
}

// matchRegexp is just the fields common among
// matchers that can use regular expressions.
type matchRegexp struct {
	Name     string `json:"name"`
	Pattern  string `json:"pattern"`
	compiled *regexp.Regexp
}

func (mre *matchRegexp) Provision() error {
	re, err := regexp.Compile(mre.Pattern)
	if err != nil {
		return fmt.Errorf("compiling matcher regexp %s: %v", mre.Pattern, err)
	}
	mre.compiled = re
	return nil
}

func (mre *matchRegexp) Validate() error {
	if mre.Name != "" && !wordRE.MatchString(mre.Name) {
		return fmt.Errorf("invalid regexp name (must contain only word characters): %s", mre.Name)
	}
	return nil
}

func (mre *matchRegexp) match(input string, repl *Replacer, scope string) bool {
	matches := mre.compiled.FindStringSubmatch(input)
	if matches == nil {
		return false
	}

	// save all capture groups, first by index
	for i, match := range matches {
		key := fmt.Sprintf("http.matchers.%s.%s.%d", scope, mre.Name, i)
		repl.Map(key, match)
	}

	// then by name
	for i, name := range mre.compiled.SubexpNames() {
		if i != 0 && name != "" {
			key := fmt.Sprintf("http.matchers.%s.%s.%s", scope, mre.Name, name)
			repl.Map(key, matches[i])
		}
	}

	return true
}

var wordRE = regexp.MustCompile(`\w+`)

// Interface guards
var (
	_ RouteMatcher = (*matchHost)(nil)
	_ RouteMatcher = (*matchPath)(nil)
	_ RouteMatcher = (*matchPathRE)(nil)
	_ RouteMatcher = (*matchMethod)(nil)
	_ RouteMatcher = (*matchQuery)(nil)
	_ RouteMatcher = (*matchHeader)(nil)
	_ RouteMatcher = (*matchHeaderRE)(nil)
	_ RouteMatcher = (*matchProtocol)(nil)
	_ RouteMatcher = (*matchStarlark)(nil)
)