-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic.go
More file actions
572 lines (492 loc) · 15.1 KB
/
Copy pathstatic.go
File metadata and controls
572 lines (492 loc) · 15.1 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package servex
import (
"bufio"
"fmt"
"net"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/gorilla/mux"
)
// RegisterStaticFileMiddleware sets up static file serving middleware based on the configuration.
// This should be called after all API routes are registered but before starting the server.
// It returns a cleanup function that should be called when shutting down.
func RegisterStaticFileMiddleware(router MiddlewareRouter, cfg StaticFileConfig) {
if !cfg.isActive() {
return
}
// Create the static file handler
staticHandler := createStaticFileHandler(cfg)
// For gorilla/mux, we need to use middleware that only handles 404s
// This ensures API routes are handled first
if muxRouter, ok := router.(*mux.Router); ok {
// Use middleware that captures 404s and serves static files
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Only handle GET and HEAD requests for static files
if r.Method != http.MethodGet && r.Method != http.MethodHead {
next.ServeHTTP(w, r)
return
}
// Check if this path should be excluded from static file serving
if shouldExcludeFromStatic(r.URL.Path, cfg.ExcludePaths) {
next.ServeHTTP(w, r)
return
}
// Create a response writer that captures the status code
captureWriter := &staticResponseWriter{ResponseWriter: w}
// Let other handlers try first
next.ServeHTTP(captureWriter, r)
// If we got a 404, try to serve static files
if captureWriter.statusCode == 404 || captureWriter.statusCode == 0 {
// Reset the response writer for static file serving
// Create a new response writer that doesn't interfere with the original
if captureWriter.bytesWritten == 0 {
// Only serve static files if nothing was written yet
if cfg.SPAMode {
staticHandler.serveSPA(w, r, http.NotFoundHandler())
} else {
staticHandler.serveStatic(w, r, http.NotFoundHandler())
}
}
}
})
})
// Also set a custom NotFoundHandler as fallback
originalNotFound := muxRouter.NotFoundHandler
muxRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Only handle GET and HEAD requests for static files
if r.Method != http.MethodGet && r.Method != http.MethodHead {
if originalNotFound != nil {
originalNotFound.ServeHTTP(w, r)
} else {
http.NotFound(w, r)
}
return
}
// Check if this path should be excluded from static file serving
if shouldExcludeFromStatic(r.URL.Path, cfg.ExcludePaths) {
if originalNotFound != nil {
originalNotFound.ServeHTTP(w, r)
} else {
http.NotFound(w, r)
}
return
}
// Try to serve static file
if cfg.SPAMode {
staticHandler.serveSPA(w, r, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if originalNotFound != nil {
originalNotFound.ServeHTTP(w, r)
} else {
http.NotFound(w, r)
}
}))
} else {
staticHandler.serveStatic(w, r, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if originalNotFound != nil {
originalNotFound.ServeHTTP(w, r)
} else {
http.NotFound(w, r)
}
}))
}
})
return
}
// For other router types, use middleware
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Only handle GET and HEAD requests for static files
if r.Method != http.MethodGet && r.Method != http.MethodHead {
next.ServeHTTP(w, r)
return
}
// Check if this path should be excluded from static file serving
if shouldExcludeFromStatic(r.URL.Path, cfg.ExcludePaths) {
next.ServeHTTP(w, r)
return
}
// Try to serve static file
if cfg.SPAMode {
staticHandler.serveSPA(w, r, next)
} else {
staticHandler.serveStatic(w, r, next)
}
})
})
}
// staticFileHandler handles static file serving with optional SPA support
type staticFileHandler struct {
config StaticFileConfig
indexPath string
}
// createStaticFileHandler creates a new static file handler based on configuration
func createStaticFileHandler(cfg StaticFileConfig) *staticFileHandler {
// Resolve absolute directory path
absDir, err := filepath.Abs(cfg.Dir)
if err != nil {
absDir = cfg.Dir
}
// Set default index file for SPA mode
indexFile := cfg.IndexFile
if cfg.SPAMode && indexFile == "" {
indexFile = "index.html"
}
var indexPath string
if indexFile != "" {
indexPath = filepath.Join(absDir, indexFile)
}
return &staticFileHandler{
config: cfg,
indexPath: indexPath,
}
}
// serveStatic serves static files without SPA fallback
func (h *staticFileHandler) serveStatic(w http.ResponseWriter, r *http.Request, next http.Handler) {
requestPath := r.URL.Path
// Check URL prefix matching
if h.config.URLPrefix != "" {
if !strings.HasPrefix(requestPath, h.config.URLPrefix) {
next.ServeHTTP(w, r)
return
}
}
// Try to serve the file
h.serveStaticFile(w, r, next)
}
// serveStaticFile handles the actual file serving with security checks
func (h *staticFileHandler) serveStaticFile(w http.ResponseWriter, r *http.Request, next http.Handler) {
requestPath := r.URL.Path
// Convert URL path to file system path with security checks
cleanPath := path.Clean(requestPath)
if isDirectoryTraversalAttempt(cleanPath) {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
// Remove URL prefix if configured
if h.config.URLPrefix != "" {
cleanPath = strings.TrimPrefix(cleanPath, h.config.URLPrefix)
}
// Strip configured prefix from the URL before file lookup
if h.config.StripPrefix != "" {
cleanPath = strings.TrimPrefix(cleanPath, h.config.StripPrefix)
}
// Build file system path
fsPath := filepath.Join(h.config.Dir, filepath.FromSlash(cleanPath))
// Additional security check - ensure the resolved path is still within the configured directory
absConfigDir, err := filepath.Abs(h.config.Dir)
if err != nil {
next.ServeHTTP(w, r)
return
}
absFilePath, err := filepath.Abs(fsPath)
if err != nil {
next.ServeHTTP(w, r)
return
}
if !strings.HasPrefix(absFilePath, absConfigDir+string(filepath.Separator)) && absFilePath != absConfigDir {
next.ServeHTTP(w, r)
return
}
// Check if file exists
stat, err := os.Stat(fsPath)
if err != nil {
next.ServeHTTP(w, r)
return
}
if stat.IsDir() {
next.ServeHTTP(w, r)
return
}
// Apply caching headers before serving
h.applyCacheHeaders(w, r)
// Apply security headers for static files
applySecurityHeaders(w, h.config.securityHeadersForStaticFiles)
// Serve the file directly
file, err := os.Open(fsPath)
if err != nil {
next.ServeHTTP(w, r)
return
}
defer func() { _ = file.Close() }()
// Set appropriate content type
ext := strings.ToLower(filepath.Ext(fsPath))
contentType := getContentType(ext)
w.Header().Set("Content-Type", contentType)
// Serve the file content
http.ServeContent(w, r, filepath.Base(fsPath), stat.ModTime(), file)
}
// getContentType returns the MIME type for common file extensions
func getContentType(ext string) string {
switch strings.ToLower(ext) {
case ".html", ".htm":
return "text/html; charset=utf-8"
case ".css":
return "text/css; charset=utf-8"
case ".js":
return "application/javascript"
case ".json":
return "application/json"
case ".png":
return "image/png"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".gif":
return "image/gif"
case ".svg":
return "image/svg+xml"
case ".ico":
return "image/x-icon"
case ".pdf":
return "application/pdf"
case ".txt":
return "text/plain; charset=utf-8"
default:
return "application/octet-stream"
}
}
// serveSPA serves static files with SPA fallback support
func (h *staticFileHandler) serveSPA(w http.ResponseWriter, r *http.Request, next http.Handler) {
requestPath := r.URL.Path
// Check URL prefix matching first
if h.config.URLPrefix != "" {
if !strings.HasPrefix(requestPath, h.config.URLPrefix) {
next.ServeHTTP(w, r)
return
}
}
// For SPA mode, we need to check if the requested file exists
if h.fileExists(requestPath) {
// File exists, serve it directly with our custom handler
h.serveStaticFile(w, r, next)
return
}
// Check if this looks like an API route or should be handled by other handlers
if h.shouldPassToNextHandler(requestPath) {
next.ServeHTTP(w, r)
return
}
// File doesn't exist and it's not an API route - serve index file for SPA routing
if h.indexPath != "" {
h.serveIndexFile(w, r)
} else {
next.ServeHTTP(w, r)
}
}
// fileExists checks if a file exists at the given request path
func (h *staticFileHandler) fileExists(requestPath string) bool {
// Convert URL path to file system path
cleanPath := path.Clean(requestPath)
if isDirectoryTraversalAttempt(cleanPath) {
return false // Security: prevent directory traversal
}
// Remove URL prefix if configured
if h.config.URLPrefix != "" {
if !strings.HasPrefix(cleanPath, h.config.URLPrefix) {
return false
}
cleanPath = strings.TrimPrefix(cleanPath, h.config.URLPrefix)
}
// Strip configured prefix from the URL before file lookup
if h.config.StripPrefix != "" {
cleanPath = strings.TrimPrefix(cleanPath, h.config.StripPrefix)
}
// Build file system path
fsPath := filepath.Join(h.config.Dir, filepath.FromSlash(cleanPath))
// Check if file exists and is not a directory
info, err := os.Stat(fsPath)
return err == nil && !info.IsDir()
}
// shouldPassToNextHandler determines if a request should be handled by other handlers
func (h *staticFileHandler) shouldPassToNextHandler(requestPath string) bool {
// If it looks like an API endpoint, let other handlers process it
// This is a simple heuristic - you might want to customize this
if strings.HasPrefix(requestPath, "/api/") {
return true
}
if strings.HasPrefix(requestPath, "/auth/") {
return true
}
if strings.HasPrefix(requestPath, "/admin/") {
return true
}
if strings.HasPrefix(requestPath, "/ws/") {
return true
}
// Check configured exclude paths
return shouldExcludeFromStatic(requestPath, h.config.ExcludePaths)
}
// serveIndexFile serves the index.html file for SPA routing
func (h *staticFileHandler) serveIndexFile(w http.ResponseWriter, r *http.Request) {
// Read the index file
content, err := os.ReadFile(h.indexPath)
if err != nil {
http.Error(w, "Index file not found", http.StatusNotFound)
return
}
// Apply appropriate headers for HTML
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// Apply cache headers (typically short cache for HTML in SPA)
if h.config.CacheMaxAge > 0 {
// For HTML in SPA mode, use short cache or no-cache
htmlCacheAge := h.getCacheAge(".html", r.URL.Path)
if htmlCacheAge > 0 {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", htmlCacheAge))
} else {
w.Header().Set("Cache-Control", "no-cache")
}
}
// Serve the content
w.WriteHeader(http.StatusOK)
_, _ = w.Write(content)
}
// applyCacheHeaders applies caching headers based on configuration
func (h *staticFileHandler) applyCacheHeaders(w http.ResponseWriter, r *http.Request) {
if h.config.CacheMaxAge <= 0 && len(h.config.CacheRules) == 0 {
return // No caching configured
}
requestPath := r.URL.Path
cacheAge := h.getCacheAge(path.Ext(requestPath), requestPath)
if cacheAge > 0 {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", cacheAge))
// Set Expires header for older clients
expires := time.Now().Add(time.Duration(cacheAge) * time.Second)
w.Header().Set("Expires", expires.Format(http.TimeFormat))
// ETag is handled by http.ServeContent based on file modification time
} else {
w.Header().Set("Cache-Control", "no-cache")
}
}
// getCacheAge returns the cache age for a given file extension and path
func (h *staticFileHandler) getCacheAge(ext, path string) int {
// Check specific cache rules first
if h.config.CacheRules != nil {
// Check for exact path match first
if age, ok := h.config.CacheRules[path]; ok {
return age
}
// Check for pattern matches (simplified - only supports trailing *)
for pattern, age := range h.config.CacheRules {
if strings.HasSuffix(pattern, "*") {
prefix := strings.TrimSuffix(pattern, "*")
if strings.HasPrefix(path, prefix) {
return age
}
}
}
// Check for file extension match
if age, ok := h.config.CacheRules[ext]; ok {
return age
}
}
// Fall back to default max age
return h.config.CacheMaxAge
}
// shouldExcludeFromStatic checks if a path should be excluded from static file serving
func shouldExcludeFromStatic(requestPath string, excludePaths []string) bool {
// matchPath returns true if the path should be processed, false if excluded
// We want the opposite - return true if excluded
return !matchPath(requestPath, excludePaths, nil, true)
}
// staticResponseWriter wraps http.ResponseWriter to capture status codes
type staticResponseWriter struct {
http.ResponseWriter
statusCode int
bytesWritten int
}
func (w *staticResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hj, ok := w.ResponseWriter.(http.Hijacker); ok {
return hj.Hijack()
}
return nil, nil, fmt.Errorf("upstream ResponseWriter does not implement http.Hijacker")
}
func (w *staticResponseWriter) Flush() {
if fl, ok := w.ResponseWriter.(http.Flusher); ok {
fl.Flush()
}
}
func (w *staticResponseWriter) WriteHeader(code int) {
if w.statusCode == 0 {
w.statusCode = code
}
if code != http.StatusNotFound {
w.ResponseWriter.WriteHeader(code)
}
}
func (w *staticResponseWriter) Write(b []byte) (int, error) {
if w.statusCode == 0 {
w.statusCode = 200
}
if w.statusCode == http.StatusNotFound {
w.bytesWritten += len(b)
return len(b), nil
}
n, err := w.ResponseWriter.Write(b)
w.bytesWritten += n
return n, err
}
// AddStaticFileRoutes is a convenience method to add static file serving to a router.
// This can be used as an alternative to middleware if you prefer explicit routing.
func (s *Server) AddStaticFileRoutes(cfg StaticFileConfig) error {
if !cfg.Enabled || cfg.Dir == "" {
return nil
}
handler := createStaticFileHandler(cfg)
// Determine the route pattern
pattern := cfg.URLPrefix
if pattern == "" {
pattern = "/"
}
if !strings.HasSuffix(pattern, "/") {
pattern += "/"
}
pattern += "{file:.*}"
// Register the route
s.router.PathPrefix(pattern).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if cfg.SPAMode {
handler.serveSPA(w, r, http.NotFoundHandler())
} else {
handler.serveStatic(w, r, http.NotFoundHandler())
}
})
return nil
}
// isDirectoryTraversalAttempt checks if a path contains directory traversal patterns
func isDirectoryTraversalAttempt(path string) bool {
if path == "" {
return false
}
// Check for common directory traversal patterns
patterns := []string{
"..",
"%2e%2e",
"%2E%2E",
"%2e%2E", // Mixed case
"%2E%2e", // Mixed case
"%2e.",
"%2E.",
".%2e",
".%2E",
"..%2f",
"..%2F",
"%2e%2e%2f",
"%2E%2E%2F",
"%2e%2E%2f", // Mixed case
"%2E%2e%2F", // Mixed case
"..\\",
"%2e%2e%5c",
"%2E%2E%5C",
"%2e%2E%5c", // Mixed case
"%2E%2e%5C", // Mixed case
}
for _, pattern := range patterns {
if strings.Contains(path, pattern) {
return true
}
}
return false
}