generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
ingress.go
252 lines (220 loc) · 6.1 KB
/
ingress.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
package ingress
import (
"encoding/base64"
"encoding/json"
"fmt"
"math/rand"
"reflect"
"strconv"
"strings"
"time"
"github.com/TBD54566975/ftl/backend/controller/dal"
"github.com/TBD54566975/ftl/backend/schema"
"github.com/TBD54566975/ftl/internal/slices"
)
type path []string
func (p path) String() string {
return strings.TrimLeft(strings.Join(p, ""), ".")
}
func GetIngressRoute(routes []dal.IngressRoute, method string, path string) (*dal.IngressRoute, error) {
var matchedRoutes = slices.Filter(routes, func(route dal.IngressRoute) bool {
return matchSegments(route.Path, path, func(segment, value string) {})
})
if len(matchedRoutes) == 0 {
return nil, dal.ErrNotFound
}
// TODO: add load balancing at some point
route := matchedRoutes[rand.Intn(len(matchedRoutes))] //nolint:gosec
return &route, nil
}
func matchSegments(pattern, urlPath string, onMatch func(segment, value string)) bool {
patternSegments := strings.Split(strings.Trim(pattern, "/"), "/")
urlSegments := strings.Split(strings.Trim(urlPath, "/"), "/")
if len(patternSegments) != len(urlSegments) {
return false
}
for i, segment := range patternSegments {
if segment == "" && urlSegments[i] == "" {
continue // Skip empty segments
}
if strings.HasPrefix(segment, "{") && strings.HasSuffix(segment, "}") {
key := strings.Trim(segment, "{}") // Dynamic segment
onMatch(key, urlSegments[i])
} else if segment != urlSegments[i] {
return false
}
}
return true
}
func ValidateCallBody(body []byte, ref *schema.Ref, sch *schema.Schema) error {
verb := &schema.Verb{}
err := sch.ResolveRefToType(ref, verb)
if err != nil {
return err
}
var requestMap map[string]any
err = json.Unmarshal(body, &requestMap)
if err != nil {
return fmt.Errorf("HTTP request body is not valid JSON: %w", err)
}
return validateValue(verb.Request, []string{verb.Request.String()}, requestMap, sch)
}
func getBodyField(ref *schema.Ref, sch *schema.Schema) (*schema.Field, error) {
data, err := sch.ResolveRefMonomorphised(ref)
if err != nil {
return nil, err
}
var bodyField *schema.Field
for _, field := range data.Fields {
if field.Name == "body" {
bodyField = field
break
}
}
if bodyField == nil {
return nil, fmt.Errorf("verb %s must have a 'body' field", ref.Name)
}
return bodyField, nil
}
func validateValue(fieldType schema.Type, path path, value any, sch *schema.Schema) error { //nolint:maintidx
var typeMatches bool
switch fieldType := fieldType.(type) {
case *schema.Any:
typeMatches = true
case *schema.Unit:
// TODO: Use type assertions consistently in this function rather than reflection.
rv := reflect.ValueOf(value)
if rv.Kind() != reflect.Map || rv.Len() != 0 {
return fmt.Errorf("%s must be an empty map", path)
}
return nil
case *schema.Time:
str, ok := value.(string)
if !ok {
return fmt.Errorf("time %s must be an RFC3339 formatted string", path)
}
_, err := time.Parse(time.RFC3339Nano, str)
if err != nil {
return fmt.Errorf("time %s must be an RFC3339 formatted string: %w", path, err)
}
return nil
case *schema.Int:
switch value := value.(type) {
case int64, float64:
typeMatches = true
case string:
if _, err := strconv.ParseInt(value, 10, 64); err == nil {
typeMatches = true
}
}
case *schema.Float:
switch value := value.(type) {
case float64:
typeMatches = true
case string:
if _, err := strconv.ParseFloat(value, 64); err == nil {
typeMatches = true
}
}
case *schema.String:
_, typeMatches = value.(string)
case *schema.Bool:
switch value := value.(type) {
case bool:
typeMatches = true
case string:
if _, err := strconv.ParseBool(value); err == nil {
typeMatches = true
}
}
case *schema.Array:
rv := reflect.ValueOf(value)
if rv.Kind() != reflect.Slice {
return fmt.Errorf("%s is not a slice", path)
}
elementType := fieldType.Element
for i := range rv.Len() {
elemPath := append(path, fmt.Sprintf("[%d]", i)) //nolint:gocritic
elem := rv.Index(i).Interface()
if err := validateValue(elementType, elemPath, elem, sch); err != nil {
return err
}
}
typeMatches = true
case *schema.Map:
rv := reflect.ValueOf(value)
if rv.Kind() != reflect.Map {
return fmt.Errorf("%s is not a map", path)
}
keyType := fieldType.Key
valueType := fieldType.Value
for _, key := range rv.MapKeys() {
elemPath := append(path, fmt.Sprintf("[%q]", key)) //nolint:gocritic
elem := rv.MapIndex(key).Interface()
if err := validateValue(keyType, elemPath, key.Interface(), sch); err != nil {
return err
}
if err := validateValue(valueType, elemPath, elem, sch); err != nil {
return err
}
}
typeMatches = true
case *schema.Ref:
decl := sch.ResolveRef(fieldType)
if decl == nil {
return fmt.Errorf("unknown ref %v", fieldType)
}
switch d := decl.(type) {
case *schema.Verb:
case *schema.Data:
if valueMap, ok := value.(map[string]any); ok {
if err := validateRequestMap(fieldType, path, valueMap, sch); err != nil {
return err
}
typeMatches = true
}
case *schema.Enum:
for _, v := range d.Variants {
switch t := v.Value.(type) {
case *schema.StringValue:
if valueStr, ok := value.(string); ok {
if t.Value == valueStr {
typeMatches = true
break
}
}
case *schema.IntValue:
if valueInt, ok := value.(int); ok {
if t.Value == valueInt {
typeMatches = true
break
}
}
}
}
if !typeMatches {
return fmt.Errorf("%s is not a valid variant of enum %s", value, fieldType)
}
case *schema.Config, *schema.Database, *schema.Secret:
}
case *schema.Bytes:
_, typeMatches = value.([]byte)
if bodyStr, ok := value.(string); ok {
_, err := base64.StdEncoding.DecodeString(bodyStr)
if err != nil {
return fmt.Errorf("%s is not a valid base64 string", path)
}
typeMatches = true
}
case *schema.Optional:
if value == nil {
typeMatches = true
} else {
return validateValue(fieldType.Type, path, value, sch)
}
}
if !typeMatches {
return fmt.Errorf("%s has wrong type, expected %s found %T", path, fieldType, value)
}
return nil
}