|
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | +package web |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/btouchard/ackify-ce/backend/internal/domain/models" |
| 12 | + "github.com/btouchard/ackify-ce/backend/pkg/logger" |
| 13 | +) |
| 14 | + |
| 15 | +type docService interface { |
| 16 | + FindOrCreateDocument(ctx context.Context, ref string) (*models.Document, bool, error) |
| 17 | +} |
| 18 | + |
| 19 | +// webhookPublisher defines minimal publish capability |
| 20 | +type webhookPublisher interface { |
| 21 | + Publish(ctx context.Context, eventType string, payload map[string]interface{}) error |
| 22 | +} |
| 23 | + |
| 24 | +// EmbedDocumentMiddleware creates documents on /embed access with strict rate limiting |
| 25 | +// This ensures documents exist before the SPA renders, without requiring authentication |
| 26 | +// The docServiceFn should be a function that calls FindOrCreateDocument |
| 27 | +func EmbedDocumentMiddleware( |
| 28 | + docService docService, |
| 29 | + publisher webhookPublisher, |
| 30 | +) func(http.Handler) http.Handler { |
| 31 | + rateLimiter := newEmbedRateLimiter(2, time.Minute) |
| 32 | + |
| 33 | + return func(next http.Handler) http.Handler { |
| 34 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 35 | + // Only intercept /embed path |
| 36 | + if !strings.HasPrefix(r.URL.Path, "/embed") { |
| 37 | + next.ServeHTTP(w, r) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + // Check rate limit |
| 42 | + ip := getClientIP(r) |
| 43 | + if !rateLimiter.Allow(ip) { |
| 44 | + logger.Logger.Warn("Embed rate limit exceeded", |
| 45 | + "ip", ip, |
| 46 | + "path", r.URL.Path) |
| 47 | + // Let the request continue to SPA - frontend will handle the error display |
| 48 | + // The frontend can check for rate limit errors via API calls |
| 49 | + next.ServeHTTP(w, r) |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + // Get doc ID from query parameter |
| 54 | + docID := r.URL.Query().Get("doc") |
| 55 | + if docID == "" { |
| 56 | + // No doc parameter, let SPA handle it |
| 57 | + next.ServeHTTP(w, r) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + // Try to create document if it doesn't exist |
| 62 | + ctx := r.Context() |
| 63 | + doc, isNew, err := docService.FindOrCreateDocument(ctx, docID) |
| 64 | + if err != nil { |
| 65 | + logger.Logger.Error("Failed to find/create document for embed", |
| 66 | + "doc_id", docID, |
| 67 | + "error", err.Error(), |
| 68 | + "ip", ip) |
| 69 | + // Continue to SPA anyway - it will handle the error |
| 70 | + next.ServeHTTP(w, r) |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + if isNew { |
| 75 | + logger.Logger.Info("Document auto-created via embed view", |
| 76 | + "doc_id", docID, |
| 77 | + "ip", ip) |
| 78 | + |
| 79 | + // Publish webhook event for auto-created documents |
| 80 | + if publisher != nil { |
| 81 | + _ = publisher.Publish(ctx, "document.created", map[string]interface{}{ |
| 82 | + "doc_id": doc.GetDocID(), |
| 83 | + "title": doc.GetTitle(), |
| 84 | + "url": doc.GetURL(), |
| 85 | + "source": "embed_view", |
| 86 | + }) |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + // Continue to SPA |
| 91 | + next.ServeHTTP(w, r) |
| 92 | + }) |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +// embedRateLimiter implements a simple IP-based rate limiter |
| 97 | +type embedRateLimiter struct { |
| 98 | + attempts *sync.Map |
| 99 | + limit int |
| 100 | + window time.Duration |
| 101 | +} |
| 102 | + |
| 103 | +func newEmbedRateLimiter(limit int, window time.Duration) *embedRateLimiter { |
| 104 | + return &embedRateLimiter{ |
| 105 | + attempts: &sync.Map{}, |
| 106 | + limit: limit, |
| 107 | + window: window, |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +func (rl *embedRateLimiter) Allow(ip string) bool { |
| 112 | + now := time.Now() |
| 113 | + |
| 114 | + // Check current attempts |
| 115 | + if val, ok := rl.attempts.Load(ip); ok { |
| 116 | + attempts := val.([]time.Time) |
| 117 | + |
| 118 | + // Filter out old attempts |
| 119 | + var valid []time.Time |
| 120 | + for _, t := range attempts { |
| 121 | + if now.Sub(t) < rl.window { |
| 122 | + valid = append(valid, t) |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + if len(valid) >= rl.limit { |
| 127 | + return false |
| 128 | + } |
| 129 | + |
| 130 | + valid = append(valid, now) |
| 131 | + rl.attempts.Store(ip, valid) |
| 132 | + } else { |
| 133 | + rl.attempts.Store(ip, []time.Time{now}) |
| 134 | + } |
| 135 | + |
| 136 | + return true |
| 137 | +} |
| 138 | + |
| 139 | +func getClientIP(r *http.Request) string { |
| 140 | + // Try X-Forwarded-For first (for proxies) |
| 141 | + if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" { |
| 142 | + ips := strings.Split(forwarded, ",") |
| 143 | + return strings.TrimSpace(ips[0]) |
| 144 | + } |
| 145 | + |
| 146 | + // Try X-Real-IP |
| 147 | + if realIP := r.Header.Get("X-Real-IP"); realIP != "" { |
| 148 | + return realIP |
| 149 | + } |
| 150 | + |
| 151 | + // Fallback to RemoteAddr |
| 152 | + ip := r.RemoteAddr |
| 153 | + if idx := strings.LastIndex(ip, ":"); idx != -1 { |
| 154 | + ip = ip[:idx] |
| 155 | + } |
| 156 | + return ip |
| 157 | +} |
0 commit comments