Debian Codegraph @

modules/caddyhttp/map/map.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package maphandler
16
17 import (
18 "fmt"
19 "net/http"
20 "regexp"
21 "slices"
22 "strings"
23
24 "github.com/caddyserver/caddy/v2"
25 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
26 )
27
28 func init() {
29 caddy.RegisterModule(Handler{})
30 }
31
32 // Handler implements a middleware that maps inputs to outputs. Specifically, it
33 // compares a source value against the map inputs, and for one that matches, it
34 // applies the output values to each destination. Destinations become placeholder
35 // names.
36 //
37 // Mapped placeholders are not evaluated until they are used, so even for very
38 // large mappings, this handler is quite efficient.
39 type Handler struct {
40 // Source is the placeholder from which to get the input value.
41 Source string `json:"source,omitempty"`
42
43 // Destinations are the names of placeholders in which to store the outputs.
44 // Destination values should be wrapped in braces, for example, {my_placeholder}.
45 Destinations []string `json:"destinations,omitempty"`
46
47 // Mappings from source values (inputs) to destination values (outputs).
48 // The first matching, non-nil mapping will be applied.
49 Mappings []Mapping `json:"mappings,omitempty"`
50
51 // If no mappings match or if the mapped output is null/nil, the associated
52 // default output will be applied (optional).
53 Defaults []string `json:"defaults,omitempty"`
54 }
55
56 // CaddyModule returns the Caddy module information.
57 func (Handler) CaddyModule() caddy.ModuleInfo {
58 return caddy.ModuleInfo{
59 ID: "http.handlers.map",
60 New: func() caddy.Module { return new(Handler) },
61 }
62 }
63
64 // Provision sets up h.
65 func (h *Handler) Provision(_ caddy.Context) error {
66 for j, dest := range h.Destinations {
67 if strings.Count(dest, "{") != 1 || !strings.HasPrefix(dest, "{") {
68 return fmt.Errorf("destination must be a placeholder and only a placeholder")
69 }
70 h.Destinations[j] = strings.Trim(dest, "{}")
71 }
72
73 for i, m := range h.Mappings {
74 if m.InputRegexp == "" {
75 continue
76 }
77 var err error
78 h.Mappings[i].re, err = regexp.Compile(m.InputRegexp)
79 if err != nil {
80 return fmt.Errorf("compiling regexp for mapping %d: %v", i, err)
81 }
82 }
83
84 // TODO: improve efficiency even further by using an actual map type
85 // for the non-regexp mappings, OR sort them and do a binary search
86
87 return nil
88 }
89
90 // Validate ensures that h is configured properly.
91 func (h *Handler) Validate() error {
92 nDest, nDef := len(h.Destinations), len(h.Defaults)
93 if nDef > 0 && nDef != nDest {
94 return fmt.Errorf("%d destinations != %d defaults", nDest, nDef)
95 }
96
97 seen := make(map[string]int)
98 for i, m := range h.Mappings {
99 // prevent confusing/ambiguous mappings
100 if m.Input != "" && m.InputRegexp != "" {
101 return fmt.Errorf("mapping %d has both input and input_regexp fields specified, which is confusing", i)
102 }
103
104 // prevent duplicate mappings
105 input := m.Input
106 if m.InputRegexp != "" {
107 input = m.InputRegexp
108 }
109 if prev, ok := seen[input]; ok {
110 return fmt.Errorf("mapping %d has a duplicate input '%s' previously used with mapping %d", i, input, prev)
111 }
112 seen[input] = i
113
114 // ensure mappings have 1:1 output-to-destination correspondence
115 nOut := len(m.Outputs)
116 if nOut != nDest {
117 return fmt.Errorf("mapping %d has %d outputs but there are %d destinations defined", i, nOut, nDest)
118 }
119 }
120
121 return nil
122 }
123
124 func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
125 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
126
127 // defer work until a variable is actually evaluated by using replacer's Map callback
128 repl.Map(func(key string) (any, bool) {
129 // return early if the variable is not even a configured destination
130 destIdx := slices.Index(h.Destinations, key)
131 if destIdx < 0 {
132 return nil, false
133 }
134
135 input := repl.ReplaceAll(h.Source, "")
136
137 // find the first mapping matching the input and return
138 // the requested destination/output value
139 for _, m := range h.Mappings {
140 output := m.Outputs[destIdx]
141 if output == nil {
142 continue
143 }
144 outputStr := caddy.ToString(output)
145
146 // evaluate regular expression if configured
147 if m.re != nil {
148 var result []byte
149 matches := m.re.FindStringSubmatchIndex(input)
150 if matches == nil {
151 continue
152 }
153 result = m.re.ExpandString(result, outputStr, input, matches)
154 return string(result), true
155 }
156
157 // otherwise simple string comparison
158 if input == m.Input {
159 return repl.ReplaceAll(outputStr, ""), true
160 }
161 }
162
163 // fall back to default if no match or if matched nil value
164 if len(h.Defaults) > destIdx {
165 return repl.ReplaceAll(h.Defaults[destIdx], ""), true
166 }
167
168 return nil, true
169 })
170
171 return next.ServeHTTP(w, r)
172 }
173
174 // Mapping describes a mapping from input to outputs.
175 type Mapping struct {
176 // The input value to match. Must be distinct from other mappings.
177 // Mutually exclusive to input_regexp.
178 Input string `json:"input,omitempty"`
179
180 // The input regular expression to match. Mutually exclusive to input.
181 InputRegexp string `json:"input_regexp,omitempty"`
182
183 // Upon a match with the input, each output is positionally correlated
184 // with each destination of the parent handler. An output that is null
185 // (nil) will be treated as if it was not mapped at all.
186 Outputs []any `json:"outputs,omitempty"`
187
188 re *regexp.Regexp
189 }
190
191 // Interface guards
192 var (
193 _ caddy.Provisioner = (*Handler)(nil)
194 _ caddy.Validator = (*Handler)(nil)
195 _ caddyhttp.MiddlewareHandler = (*Handler)(nil)
196 )