-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathutils.go
More file actions
436 lines (378 loc) · 10.4 KB
/
utils.go
File metadata and controls
436 lines (378 loc) · 10.4 KB
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
package limen
import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path"
reflect "reflect"
"regexp"
"slices"
"strings"
"time"
)
type CharSetType int
const (
CharSetAlphanumeric CharSetType = iota
CharSetNumeric
)
var (
alphanumericChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
numericChars = "0123456789"
)
// generateCryptoSecureRandomString generates a cryptographically secure random string
func generateCryptoSecureRandomString() string {
buf := make([]byte, 32)
_, _ = rand.Read(buf)
return base64.RawURLEncoding.EncodeToString(buf)
}
func GenerateRandomString(length int, charSetType ...CharSetType) string {
chars := alphanumericChars
if len(charSetType) > 0 && charSetType[0] == CharSetNumeric {
chars = numericChars
}
charCount := len(chars)
expectedBytes := make([]byte, length)
_, _ = rand.Read(expectedBytes)
for i := range length {
expectedBytes[i] = chars[int(expectedBytes[i])%charCount]
}
return string(expectedBytes)
}
func ipExtractorFromRemoteAddr(request *http.Request) string {
if ip := request.Header.Get("X-Forwarded-For"); ip != "" {
return ip
}
if ip := request.Header.Get("X-Real-IP"); ip != "" {
return ip
}
ip, _, _ := net.SplitHostPort(request.RemoteAddr)
return ip
}
// compileRateLimitPattern compiles a rate limit pattern to a regex
// Returns the compiled regex and an error if compilation fails
func compileRateLimitPattern(pattern string) (*regexp.Regexp, error) {
regexPattern := globToRegex(pattern, true)
return regexp.Compile(regexPattern)
}
// globToRegex converts a glob pattern to a regex pattern
func globToRegex(pattern string, supportPathParameters bool) string {
var result strings.Builder
result.WriteString("^")
runes := []rune(pattern)
i := 0
for i < len(runes) {
char := runes[i]
switch char {
case '*':
// Check if it's **
if i+1 < len(runes) && runes[i+1] == '*' {
// ** matches zero or more characters including /
result.WriteString(".*")
i += 2 // Skip both stars
continue
} else {
// Single * matches any sequence except /
result.WriteString("[^/]*")
}
case '?':
// ? matches any single character except /
result.WriteString("[^/]")
case ':':
if supportPathParameters {
// Route parameter (:param) - match one path segment. Skip param name until next / or end.
result.WriteString("[^/]+")
i++
for i < len(runes) && runes[i] != '/' {
i++
}
continue
} else {
result.WriteRune(char)
}
case '[':
// Character class - copy until closing ]
result.WriteRune('[')
i++
for i < len(runes) && runes[i] != ']' {
result.WriteRune(runes[i])
i++
}
if i < len(runes) {
result.WriteRune(']')
}
case '\\':
// Escape character - escape the next character
if i+1 < len(runes) {
result.WriteRune('\\')
result.WriteRune(runes[i+1])
i += 2
continue
}
result.WriteRune('\\')
case '.', '+', '(', ')', '|', '{', '}', '^', '$':
// Escape regex special characters
result.WriteRune('\\')
result.WriteRune(char)
default:
result.WriteRune(char)
}
i++
}
result.WriteString("$")
return result.String()
}
// sortRulesBySpecificity sorts the rules by specificity.
//
// The rules are sorted by the following criteria:
// 1. Patterns without wildcards are more specific
// 2. Longer paths are more specific
// 3. Patterns with fewer wildcards are more specific
func sortRulesBySpecificity(rules []*RateLimitRule) {
slices.SortFunc(rules, func(a *RateLimitRule, b *RateLimitRule) int {
pathA, pathB := a.path, b.path
// Exact matches first
if !containsWildcard(pathA) && containsWildcard(pathB) {
return -1
}
if containsWildcard(pathA) && !containsWildcard(pathB) {
return 1
}
// Longer paths are more specific
if len(pathA) != len(pathB) {
return len(pathB) - len(pathA)
}
// Count wildcards (fewer is more specific)
wildcardsA := countWildcards(pathA)
wildcardsB := countWildcards(pathB)
return wildcardsA - wildcardsB
})
}
func containsWildcard(pathStr string) bool {
return strings.Contains(pathStr, "*") || strings.Contains(pathStr, "?") || strings.Contains(pathStr, ":")
}
func countWildcards(pathStr string) int {
count := 0
for _, char := range pathStr {
if char == '*' || char == '?' || char == ':' {
count++
}
}
return count
}
func pathMatcher(req *http.Request, pathRegex *regexp.Regexp) bool {
normalizedPath := normalizePath(req.URL.Path)
return pathRegex.MatchString(normalizedPath)
}
func writeToFile(data []byte, outputPath string) error {
file, err := os.Create(outputPath)
if err != nil {
return fmt.Errorf("failed to create output file: %w", err)
}
defer file.Close()
if _, err := io.Copy(file, bytes.NewReader(data)); err != nil {
return fmt.Errorf("failed to write schemas file: %w", err)
}
return nil
}
func addTimestampFields(fields []ColumnDefinition) []ColumnDefinition {
return append(fields, ColumnDefinition{
Name: string(SchemaCreatedAtField),
LogicalField: SchemaCreatedAtField,
Type: ColumnTypeTime,
IsNullable: false,
IsPrimaryKey: false,
DefaultValue: string(DatabaseDefaultValueNow),
Tags: map[string]string{
"json": "created_at",
},
}, ColumnDefinition{
Name: string(SchemaUpdatedAtField),
LogicalField: SchemaUpdatedAtField,
Type: ColumnTypeTime,
IsNullable: false,
IsPrimaryKey: false,
Tags: map[string]string{
"json": "updated_at",
},
})
}
func addSoftDeleteField(fields []ColumnDefinition, config *SchemaConfig, schemaName SchemaName) []ColumnDefinition {
softDeleteField := config.getCoreSchemaCustomizationField(schemaName, SchemaSoftDeleteField)
if softDeleteField != "" {
return append(fields, ColumnDefinition{
Name: softDeleteField,
LogicalField: SchemaSoftDeleteField,
Type: ColumnTypeTime,
IsNullable: true,
IsPrimaryKey: false,
Tags: map[string]string{
"json": softDeleteField,
},
})
}
return fields
}
// isValidCoreSchema checks if a string is a valid core schema name.
func isValidCoreSchema(name string) bool {
switch SchemaName(name) {
case CoreSchemaUsers, CoreSchemaSessions, CoreSchemaVerifications, CoreSchemaRateLimits, CoreSchemaAccounts:
return true
default:
return false
}
}
func getNullableValue[T any](value any) *T {
if value == nil {
return nil
}
v := value.(T)
return &v
}
func getString(v any) string {
if v == nil {
return ""
}
s, _ := v.(string)
return s
}
func getTime(v any) time.Time {
if v == nil {
return time.Time{}
}
t, _ := v.(time.Time)
return t
}
func joinCustomStringSlice[T ~string](fields []T, separator string) string {
var joined strings.Builder
for i := range fields {
joined.WriteString(string(fields[i]))
if i < len(fields)-1 {
joined.WriteString(separator)
}
}
return joined.String()
}
func compileTrustedOrigins(origins ...string) []*regexp.Regexp {
patterns := make([]*regexp.Regexp, 0, len(origins))
for _, pattern := range origins {
normalizedPattern := pattern
if !strings.Contains(pattern, "://") {
normalizedPattern = "*://" + pattern
}
regexPattern := globToRegex(normalizedPattern, false)
re, err := regexp.Compile(regexPattern)
if err != nil {
log.Panicf("failed to compile pattern for trusted origin %s: %v", pattern, err)
}
patterns = append(patterns, re)
}
return patterns
}
func processCustomRateLimitRules(basePath string, customRules map[string]*RateLimitRule) map[string]*RateLimitRule {
rules := make(map[string]*RateLimitRule)
for pattern, rule := range customRules {
completePath := path.Join(basePath, pattern)
if err := compileAndSetRulePattern(rule, completePath); err != nil {
log.Panicf("failed to compile pattern for path %s: %v", completePath, err)
}
rules[completePath] = rule
}
return rules
}
// compileAndSetRulePattern compiles the pattern and sets it on the rule
func compileAndSetRulePattern(rule *RateLimitRule, completePath string) error {
compiledPattern, err := compileRateLimitPattern(completePath)
if err != nil {
return fmt.Errorf("failed to compile pattern: %w", err)
}
rule.path = completePath
rule.pathRegex = compiledPattern
return nil
}
func resolveRuleOverride(rule *RateLimitRule, customRules map[string]*RateLimitRule) *RateLimitRule {
if customRule, exists := customRules[rule.path]; exists {
delete(customRules, rule.path)
return customRule
}
return rule
}
func normalizePluginPath(basePath, pluginBasePath string, override *PluginHTTPOverride) string {
if override != nil && override.BasePath != "" {
pluginBasePath = override.BasePath
}
return path.Join(basePath, normalizePath(pluginBasePath))
}
func isCoreSchema(schema Schema) bool {
switch schema.(type) {
case *UserSchema, *VerificationSchema, *SessionSchema, *RateLimitSchema, *AccountSchema:
return true
}
return embedsCoreSchema(schema)
}
func embedsCoreSchema(schema Schema) bool {
sType := reflect.TypeOf(schema)
if sType == nil || sType.Kind() != reflect.Pointer {
return false
}
sType = sType.Elem()
if sType.Kind() != reflect.Struct {
return false
}
coreTypes := map[reflect.Type]bool{
reflect.TypeFor[UserSchema](): true,
reflect.TypeFor[VerificationSchema](): true,
reflect.TypeFor[SessionSchema](): true,
reflect.TypeFor[RateLimitSchema](): true,
reflect.TypeFor[AccountSchema](): true,
}
for i := 0; i < sType.NumField(); i++ {
field := sType.Field(i)
if field.Anonymous {
fieldType := field.Type
if fieldType.Kind() == reflect.Pointer {
fieldType = fieldType.Elem()
}
if coreTypes[fieldType] {
return true
}
}
}
return false
}
func GetFromMap[T any](m map[string]any, key string) T {
var result T
if m == nil {
return result
}
if value, ok := m[key].(T); ok {
result = value
}
return result
}
// ExtractCookieValue extracts the value of a cookie from the Set-Cookie headers.
// Returns empty string if the cookie is not found.
func ExtractCookieValue(headers http.Header, cookieName string) string {
prefix := cookieName + "="
for _, cookie := range headers.Values("Set-Cookie") {
cookieValue := strings.Split(cookie, ";")[0]
if strings.HasPrefix(cookieValue, prefix) {
return cookieValue[len(prefix):]
}
}
return ""
}
// simple wrapper around url.JoinPath that returns an empty string if the join fails
func joinURL(baseURL string, pathElems ...string) string {
joined, err := url.JoinPath(baseURL, pathElems...)
if err != nil {
return ""
}
return joined
}