ratelimiting!!!!

This commit is contained in:
2026-11-22 19:07:55 -05:00
parent 80a5ae1f69
commit 26fe94ca45
9 changed files with 199 additions and 14 deletions
+9
View File
@@ -27,3 +27,12 @@ MINIBIN_POW_DIFFICULTY=10
# options show in the order they are written # options show in the order they are written
# leading spaces WILL be included, so make sure you dont include them # leading spaces WILL be included, so make sure you dont include them
MINIBIN_REPORT_OPTIONS="Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud" MINIBIN_REPORT_OPTIONS="Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud"
# chose where minibin gets the client's ip from
# available options: remote, cloudflare, xff
# remote: the ip connecting to minibin
# cloudflare: uses the CF-Connecting-IP header
# xff: uses the X-Forwarded-For header, ignores trusted proxies
MINIBIN_IP_ADDRESS_SOURCE=remote
# comma separated list of trusted CIDRs
# cloudflares: https://cloudflare.com/ips/
MINIBIN_TRUSTED_PROXIES=127.0.0.1/32
+1
View File
@@ -8,6 +8,7 @@ require (
github.com/glebarez/sqlite v1.11.0 github.com/glebarez/sqlite v1.11.0
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
golang.org/x/crypto v0.59.0 golang.org/x/crypto v0.59.0
golang.org/x/time v0.16.0
gorm.io/gorm v1.31.2 gorm.io/gorm v1.31.2
) )
+2
View File
@@ -30,6 +30,8 @@ golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
+21
View File
@@ -3,7 +3,9 @@ package config
import ( import (
"fmt" "fmt"
"log" "log"
"net/netip"
"os" "os"
"slices"
"strconv" "strconv"
"strings" "strings"
@@ -24,6 +26,8 @@ type Config struct {
// public host like "https://bin.zip", NOT the address minbin listens on // public host like "https://bin.zip", NOT the address minbin listens on
Host string Host string
Addr string Addr string
IPAdressSource string
TrustedProxies []netip.Prefix
} }
func LoadConfig() (Config, error) { func LoadConfig() (Config, error) {
@@ -70,6 +74,21 @@ func LoadConfig() (Config, error) {
if len(reportOptions) == 0 { if len(reportOptions) == 0 {
return Config{}, fmt.Errorf("no valid report options set") return Config{}, fmt.Errorf("no valid report options set")
} }
ipAddressSource := envOrDefault("MINIBIN_IP_ADDRESS_SOURCE", "remote")
if !slices.Contains([]string{"remote", "cloudflare", "xff"}, ipAddressSource) {
return Config{}, fmt.Errorf("%s is not a valid MINIBIN_IP_ADDRESS_SOURCE option", ipAddressSource)
}
var trustedProxies []netip.Prefix
if rawTrusted := envOrDefault("MINIBIN_TRUSTED_PROXIES", ""); rawTrusted != "" {
for entry := range strings.SplitSeq(rawTrusted, ",") {
entry = strings.TrimSpace(entry)
prefix, err := netip.ParsePrefix(entry)
if err != nil {
return Config{}, fmt.Errorf("MINIBIN_TRUSTED_PROXIES: invalid cidr %q: %w", entry, err)
}
trustedProxies = append(trustedProxies, prefix)
}
}
return Config{ return Config{
UploadDir: envOrDefault("MINIBIN_UPLOAD_DIR", "uploads"), UploadDir: envOrDefault("MINIBIN_UPLOAD_DIR", "uploads"),
@@ -84,6 +103,8 @@ func LoadConfig() (Config, error) {
DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"), DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"),
Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"), Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"),
Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"), Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"),
IPAdressSource: ipAddressSource,
TrustedProxies: trustedProxies,
}, nil }, nil
} }
+65
View File
@@ -0,0 +1,65 @@
package middleware
import (
"fmt"
"net/http"
"sync"
"time"
p "git.whoswhip.dev/whoswhip/minibin/internal/pages"
"golang.org/x/time/rate"
)
type bucket struct {
limiter *rate.Limiter
lastAccessedAt time.Time
}
type RateLimiter struct {
buckets map[string]*bucket
refillEvery time.Duration
burst int
pages *p.Pages
resolveIP func(*http.Request) (string, error)
mu sync.Mutex
}
func NewRateLimiter(refillEvery time.Duration, burst int, pages *p.Pages, resolveIP func(*http.Request) (string, error)) *RateLimiter {
return &RateLimiter{
buckets: make(map[string]*bucket),
refillEvery: refillEvery,
burst: burst,
pages: pages,
resolveIP: resolveIP,
}
}
func (rl *RateLimiter) LimitRequest(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ip, err := rl.resolveIP(r)
if err != nil {
rl.pages.HTTPError(w, r, "couldn't idenitify client address", http.StatusInternalServerError)
return
}
rl.mu.Lock()
b, ok := rl.buckets[ip]
if !ok {
b = &bucket{
limiter: rate.NewLimiter(rate.Every(rl.refillEvery), rl.burst),
}
rl.buckets[ip] = b
}
b.lastAccessedAt = time.Now()
rl.mu.Unlock()
if !b.limiter.Allow() {
w.Header().Set("Retry-After", fmt.Sprintf("%.0f", rl.refillEvery.Seconds()))
rl.pages.HTTPError(
w, r,
fmt.Sprintf("too many requests, try again in %.0f seconds", rl.refillEvery.Seconds()),
http.StatusTooManyRequests, "429, slow down!",
)
return
}
next(w, r)
}
}
+7 -2
View File
@@ -2,6 +2,7 @@ package pages
import ( import (
"errors" "errors"
"fmt"
"html/template" "html/template"
"log" "log"
"math/rand/v2" "math/rand/v2"
@@ -137,12 +138,16 @@ func FaqHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
} }
} }
func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int) { func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int, title ...string) {
if strings.Contains(r.Header.Get("Accept"), "text/html") { if strings.Contains(r.Header.Get("Accept"), "text/html") {
t := fmt.Sprintf("%c", status)
if len(title) > 0 {
t = title[0]
}
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status) w.WriteHeader(status)
_ = pages.Templates.ExecuteTemplate(w, "result.html", map[string]any{ _ = pages.Templates.ExecuteTemplate(w, "result.html", map[string]any{
"Title": status, "Title": t,
"Message": message, "Message": message,
}) })
return return
+70
View File
@@ -0,0 +1,70 @@
package server
import (
"fmt"
"net"
"net/http"
"net/netip"
"slices"
"strings"
)
func newClientIPResolve(source string, trustedProxies []netip.Prefix) func(*http.Request) (string, error) {
isTrusted := func(ip netip.Addr) bool {
for _, prefix := range trustedProxies {
if prefix.Contains(ip) {
return true
}
}
return false
}
return func(r *http.Request) (string, error) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
peer, err := netip.ParseAddr(host)
if err != nil {
return "", err
}
if source == "remote" || !isTrusted(peer) {
return peer.String(), nil
}
switch source {
case "cloudflare":
value := r.Header.Values("CF-Connecting-IP")
if len(value) != 1 {
return "", fmt.Errorf("expected a single CF-Connecting-IP header")
}
ip, err := netip.ParseAddr(value[0])
if err != nil {
return "", fmt.Errorf("invalid CF-Connecting-IP: %w", err)
}
return ip.Unmap().String(), nil
case "xff":
values := r.Header.Values("X-Forwarded-For")
hops := strings.Split(strings.Join(values, ","), ",")
// walk backwards (right to left), while skipping trusted proxies, the first untrusted ip will be assumed to be the client ip
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For#syntax
for _, hop := range slices.Backward(hops) {
if hop == "" {
continue
}
ip, err := netip.ParseAddr(strings.TrimSpace(hop))
if err != nil {
return "", fmt.Errorf("invalid X-Forwarded-For hop: %w", err)
}
ip = ip.Unmap()
if !isTrusted(ip) {
return ip.String(), nil
}
}
return "", fmt.Errorf("no client ip in X-Forwarded-For")
}
return "", fmt.Errorf("unknown client ip source %q", source)
}
}
+17 -5
View File
@@ -3,8 +3,10 @@ package server
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"time"
"git.whoswhip.dev/whoswhip/minibin/internal/config" "git.whoswhip.dev/whoswhip/minibin/internal/config"
"git.whoswhip.dev/whoswhip/minibin/internal/middleware"
"git.whoswhip.dev/whoswhip/minibin/internal/pages" "git.whoswhip.dev/whoswhip/minibin/internal/pages"
"git.whoswhip.dev/whoswhip/minibin/internal/reports" "git.whoswhip.dev/whoswhip/minibin/internal/reports"
"git.whoswhip.dev/whoswhip/minibin/internal/uploads" "git.whoswhip.dev/whoswhip/minibin/internal/uploads"
@@ -18,6 +20,7 @@ func health(w http.ResponseWriter, r *http.Request) {
func NewRouter(db *gorm.DB, cfg config.Config, p *pages.Pages, tracker *uploads.AccessTracker, cStore *reports.ChallengeStore) http.Handler { func NewRouter(db *gorm.DB, cfg config.Config, p *pages.Pages, tracker *uploads.AccessTracker, cStore *reports.ChallengeStore) http.Handler {
mux := http.NewServeMux() mux := http.NewServeMux()
fs := http.FileServer(http.Dir("web/static")) fs := http.FileServer(http.Dir("web/static"))
mux.Handle("GET /css/", fs) mux.Handle("GET /css/", fs)
mux.Handle("GET /js/", fs) mux.Handle("GET /js/", fs)
@@ -26,20 +29,29 @@ func NewRouter(db *gorm.DB, cfg config.Config, p *pages.Pages, tracker *uploads.
"/qts/", "/qts/",
http.FileServer((http.Dir("qts"))), http.FileServer((http.Dir("qts"))),
)) ))
mux.HandleFunc("GET /{$}", pages.HomeHandler(p, cfg)) mux.HandleFunc("GET /{$}", pages.HomeHandler(p, cfg))
mux.HandleFunc("GET /tos", pages.StaticPage(p, "tos.html")) mux.HandleFunc("GET /tos", pages.StaticPage(p, "tos.html"))
mux.HandleFunc("GET /privacy", pages.StaticPage(p, "privacy.html")) mux.HandleFunc("GET /privacy", pages.StaticPage(p, "privacy.html"))
mux.HandleFunc("GET /faq", pages.FaqHandler(p, cfg)) mux.HandleFunc("GET /faq", pages.FaqHandler(p, cfg))
clientIpResolver := newClientIPResolve(cfg.IPAdressSource, cfg.TrustedProxies)
reportLimiter := middleware.NewRateLimiter(12*time.Second, 2, p, clientIpResolver)
mux.HandleFunc("GET /report", reports.ReportPageHandler(p, cStore, cfg)) mux.HandleFunc("GET /report", reports.ReportPageHandler(p, cStore, cfg))
mux.HandleFunc("POST /report", reports.ReportUploadHandler(db, cfg, p, cStore)) mux.HandleFunc("POST /report", reportLimiter.LimitRequest(reports.ReportUploadHandler(db, cfg, p, cStore)))
u := http.NewServeMux() u := http.NewServeMux()
u.HandleFunc("GET /{id}", uploads.ContentHandler(db, cfg, tracker, p)) u.HandleFunc("GET /{id}", uploads.ContentHandler(db, cfg, tracker, p))
u.HandleFunc("GET /{id}/info", uploads.ContentInfoHandler(db, tracker, p)) u.HandleFunc("GET /{id}/info", uploads.ContentInfoHandler(db, tracker, p))
mux.Handle("/", u) mux.Handle("/", u)
mux.HandleFunc("POST /upload", uploads.UploadHandler(db, cfg, p))
mux.HandleFunc("PUT /upload", uploads.UploadHandler(db, cfg, p)) uploadLimiter := middleware.NewRateLimiter(6*time.Second, 3, p, clientIpResolver)
mux.HandleFunc("DELETE /{id}", uploads.DeleteHandler(db, cfg, p)) ulr := uploadLimiter.LimitRequest
mux.HandleFunc("POST /{id}/delete", uploads.DeleteHandler(db, cfg, p)) mux.HandleFunc("POST /upload", ulr(uploads.UploadHandler(db, cfg, p)))
mux.HandleFunc("PUT /upload", ulr(uploads.UploadHandler(db, cfg, p)))
mux.HandleFunc("DELETE /{id}", ulr(uploads.DeleteHandler(db, cfg, p)))
mux.HandleFunc("POST /{id}/delete", ulr(uploads.DeleteHandler(db, cfg, p)))
mux.HandleFunc("GET /health", health) mux.HandleFunc("GET /health", health)
return mux return mux
} }
+1 -1
View File
@@ -41,7 +41,7 @@ goals:
- ~~local access from a specifc ip or range only~~ - ~~local access from a specifc ip or range only~~
- [ ] prometheus metrics - [ ] prometheus metrics
- [x] [switch mime type detection library](https://git.whoswhip.dev/whoswhip/minibin/src/commit/47518993577f94d7cf9c0743042d2ac133055924/handlers.go#L273-L276) - [x] [switch mime type detection library](https://git.whoswhip.dev/whoswhip/minibin/src/commit/47518993577f94d7cf9c0743042d2ac133055924/handlers.go#L273-L276)
- [ ] ratelimits - [x] ratelimits
- [ ] simplify rendering & serving pages (too much duplicate code rn) - [ ] simplify rendering & serving pages (too much duplicate code rn)
- [x] reports - [x] reports
- [x] PoW challenges/captchas - [x] PoW challenges/captchas