ratelimit.go

47 lines
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
package security

import (
	"fmt"
	"net/http"
	"time"

	"congo.gg/pkg/database"
)

// rateLimit returns middleware that limits requests per IP using the database.
func rateLimit(db *database.Database, maxRequests, windowSeconds int, next http.Handler) http.Handler {
	// Ensure the rate limit table exists
	db.CreateTable("RateLimit", []database.Column{
		{Name: "IP", Type: "TEXT", Primary: true},
		{Name: "Count", Type: "INTEGER", Default: "0"},
		{Name: "WindowStart", Type: "INTEGER", Default: "0"},
	})

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ip := ClientIP(r)
		now := time.Now().Unix()
		windowStart := now - int64(windowSeconds)

		// Clean old entries and check count
		db.Exec(`DELETE FROM "RateLimit" WHERE WindowStart < ?`, windowStart)

		var count int
		err := db.QueryRow(`SELECT Count FROM "RateLimit" WHERE IP = ? AND WindowStart >= ?`, ip, windowStart).Scan(&count)
		if err != nil {
			// No record — insert
			db.Exec(`INSERT OR REPLACE INTO "RateLimit" (IP, Count, WindowStart) VALUES (?, 1, ?)`, ip, now)
			next.ServeHTTP(w, r)
			return
		}

		if count >= maxRequests {
			w.Header().Set("Retry-After", fmt.Sprintf("%d", windowSeconds))
			http.Error(w, "Too many requests", http.StatusTooManyRequests)
			return
		}

		// Increment
		db.Exec(`UPDATE "RateLimit" SET Count = Count + 1 WHERE IP = ?`, ip)
		next.ServeHTTP(w, r)
	})
}