middleware.go80 lines, 2.2 KB
| 1 | package ratelimit |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "math" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/netip" |
| 10 | "slices" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | |
| 14 | "github.com/fiston-user/murmur/internal/platform/httpx" |
| 15 | ) |
| 16 | |
| 17 | // A Key says whose bucket a request takes its token from. |
| 18 | type Key func(r *http.Request) string |
| 19 | |
| 20 | // ByIP is the address a request came from, without the port. |
| 21 | func ByIP(r *http.Request) string { |
| 22 | host, _, err := net.SplitHostPort(r.RemoteAddr) |
| 23 | if err != nil { |
| 24 | return r.RemoteAddr |
| 25 | } |
| 26 | return host |
| 27 | } |
| 28 | |
| 29 | // Proxies are the addresses our own load balancers connect from. |
| 30 | type Proxies []netip.Prefix |
| 31 | |
| 32 | // has says if addr is one of ours. |
| 33 | func (ps Proxies) has(addr string) bool { |
| 34 | ip, err := netip.ParseAddr(addr) |
| 35 | inside := func(p netip.Prefix) bool { return p.Contains(ip.Unmap()) } |
| 36 | return err == nil && slices.ContainsFunc(ps, inside) |
| 37 | } |
| 38 | |
| 39 | // ByIP is the client's address, for an API behind proxies of its own. |
| 40 | func (ps Proxies) ByIP(r *http.Request) string { |
| 41 | peer := ByIP(r) |
| 42 | if !ps.has(peer) { |
| 43 | return peer |
| 44 | } |
| 45 | hops := strings.Split(strings.Join(r.Header.Values("X-Forwarded-For"), ","), ",") |
| 46 | for _, hop := range slices.Backward(hops) { |
| 47 | if hop = strings.TrimSpace(hop); hop != "" && !ps.has(hop) { |
| 48 | return hop |
| 49 | } |
| 50 | } |
| 51 | return peer |
| 52 | } |
| 53 | |
| 54 | // An Allower takes one token from a key's bucket, wherever the buckets live. It can fail. |
| 55 | type Allower interface { |
| 56 | Allow(ctx context.Context, key string) (Result, error) |
| 57 | Policy() (name string, perMinute int) |
| 58 | } |
| 59 | |
| 60 | // Limit lets a request through to next when its bucket has a token. |
| 61 | func Limit(l Allower, key Key, next http.HandlerFunc) http.HandlerFunc { |
| 62 | name, perMinute := l.Policy() |
| 63 | policy := fmt.Sprintf("%q;q=%d;w=60", name, perMinute) |
| 64 | return func(w http.ResponseWriter, r *http.Request) { |
| 65 | res, err := l.Allow(r.Context(), key(r)) |
| 66 | if err != nil { |
| 67 | httpx.Error(w, http.StatusServiceUnavailable, "the rate limiter is not answering") |
| 68 | return |
| 69 | } |
| 70 | w.Header().Add("RateLimit-Policy", policy) |
| 71 | w.Header().Add("RateLimit", fmt.Sprintf("%q;a=%d", name, res.Remaining)) |
| 72 | if !res.Allowed { |
| 73 | wait := math.Ceil(res.RetryAfter.Seconds()) |
| 74 | w.Header().Set("Retry-After", strconv.Itoa(int(wait))) |
| 75 | httpx.Error(w, http.StatusTooManyRequests, "too many requests") |
| 76 | return |
| 77 | } |
| 78 | next(w, r) |
| 79 | } |
| 80 | } |