Debian Codegraph @

ban/service_test.go

raw
1 package ban
2
3 import (
4 "net/netip"
5 "os"
6 "path/filepath"
7 "strings"
8 "testing"
9 "time"
10
11 "github.com/stretchr/testify/require"
12 )
13
14 var testIP = netip.MustParseAddr("1.2.3.4")
15
16 // newTestService creates a Service wired for testing, with the given ban file, weighted-bucket
17 // threshold, and weights, plus a 1-minute window (so the emit throttle only fires once per test).
18 func newTestService(t *testing.T, banFile string, threshold int, weights map[string]int) *Service {
19 t.Helper()
20 s := NewService(&Config{
21 File: banFile,
22 Window: time.Minute,
23 Threshold: threshold,
24 Weights: weights,
25 PrefixBitsIPv4: 32,
26 PrefixBitsIPv6: 64,
27 })
28 t.Cleanup(s.Close)
29 return s
30 }
31
32 // flushAndRead forces a synchronous flush of the buffered bans (writes are otherwise async, on the
33 // runWriteLoop ticker) and returns the ban file's lines.
34 func flushAndRead(t *testing.T, s *Service, path string) []string {
35 t.Helper()
36 s.flush()
37 data, err := os.ReadFile(path)
38 require.NoError(t, err)
39 return strings.Split(strings.TrimRight(string(data), "\n"), "\n")
40 }
41
42 func TestService_Record_Weight2BansAtHalfThreshold(t *testing.T) {
43 banFile := filepath.Join(t.TempDir(), "ban.log")
44 // Threshold 10, code weight 2 -> the budget covers exactly 5 hits, so the 6th breaches.
45 s := newTestService(t, banFile, 10, map[string]int{"*": 2})
46 for i := 0; i < 5; i++ {
47 s.Record(testIP, 400, 40001)
48 }
49 s.flush()
50 require.NoFileExists(t, banFile) // 5 hits * weight 2 = 10 == budget, exactly at the limit, not over
51 s.Record(testIP, 400, 40001) // 6th hit cannot be covered -> breach
52 lines := flushAndRead(t, s, banFile)
53 require.Len(t, lines, 1)
54 require.True(t, strings.HasSuffix(lines[0], " 1.2.3.4 1.2.3.4/32 400 40001")) // <ip> <prefix> <http> <ntfy-code>
55 }
56
57 func TestService_Record_Weight10BansFast(t *testing.T) {
58 banFile := filepath.Join(t.TempDir(), "ban.log")
59 // Threshold 10, code weight 10 -> a single hit drains the whole budget, so the 2nd breaches.
60 s := newTestService(t, banFile, 10, map[string]int{"42909": 10, "*": 1})
61 s.Record(testIP, 429, 42909)
62 s.flush()
63 require.NoFileExists(t, banFile)
64 s.Record(testIP, 429, 42909) // 2nd hit cannot be covered -> breach
65 lines := flushAndRead(t, s, banFile)
66 require.Len(t, lines, 1)
67 require.True(t, strings.HasSuffix(lines[0], " 1.2.3.4 1.2.3.4/32 429 42909"))
68 }
69
70 func TestService_Record_Weight0NeverBans(t *testing.T) {
71 banFile := filepath.Join(t.TempDir(), "ban.log")
72 // The legit-quota code is exempt (weight 0), so no number of hits ever bans.
73 s := newTestService(t, banFile, 10, map[string]int{"42908": 0, "*": 1})
74 for i := 0; i < 100; i++ {
75 s.Record(testIP, 429, 42908)
76 }
77 s.flush()
78 require.NoFileExists(t, banFile)
79 }
80
81 func TestService_Record_SingleBucketNoRelaxation(t *testing.T) {
82 banFile := filepath.Join(t.TempDir(), "ban.log")
83 // One shared bucket per prefix: different codes draw down the SAME budget, so mixing them creates
84 // no extra headroom (unlike per-code buckets, which would relax the effective limit for a mixed
85 // offender).
86 s := newTestService(t, banFile, 10, map[string]int{"403*": 2, "*": 1})
87 s.Record(testIP, 403, 40301) // weight 2 -> 8 left
88 s.Record(testIP, 403, 40301) // weight 2 -> 6 left
89 s.Record(testIP, 403, 40301) // weight 2 -> 4 left
90 s.flush()
91 require.NoFileExists(t, banFile)
92 for i := 0; i < 4; i++ {
93 s.Record(testIP, 400, 40001) // weight 1 each -> drains the remaining 4 -> 0 left
94 }
95 s.flush()
96 require.NoFileExists(t, banFile) // 6 + 4 = 10 == budget exactly, still not over
97 s.Record(testIP, 400, 40001) // one more cannot be covered -> breach
98 lines := flushAndRead(t, s, banFile)
99 require.Len(t, lines, 1)
100 }
101
102 func TestService_Record_ExactLineFormat(t *testing.T) {
103 banFile := filepath.Join(t.TempDir(), "ban.log")
104 s := newTestService(t, banFile, 1, map[string]int{"*": 1})
105 before := time.Now().UTC().Truncate(time.Second)
106 for i := 0; i < 3; i++ {
107 s.Record(testIP, 429, 42901)
108 }
109 after := time.Now().UTC()
110 lines := flushAndRead(t, s, banFile)
111 require.Len(t, lines, 1)
112 parts := strings.Split(lines[0], " ")
113 require.Len(t, parts, 5) // "<timestamp> <ip> <prefix> <http-code> <ntfy-code>"
114 ts, err := time.Parse(time.RFC3339, parts[0])
115 require.NoError(t, err)
116 require.Equal(t, time.UTC, ts.Location())
117 require.False(t, ts.Before(before))
118 require.False(t, ts.After(after.Add(time.Second)))
119 require.Equal(t, "1.2.3.4", parts[1]) // full IP
120 require.Equal(t, "1.2.3.4/32", parts[2]) // masked to the default IPv4 prefix (/32)
121 require.Equal(t, "429", parts[3]) // HTTP status
122 require.Equal(t, "42901", parts[4]) // ntfy code
123 }
124
125 func TestService_Record_IPv6MaskedToPrefix(t *testing.T) {
126 banFile := filepath.Join(t.TempDir(), "ban.log")
127 s := newTestService(t, banFile, 1, map[string]int{"*": 1})
128 ip := netip.MustParseAddr("2001:db8::abcd")
129 for i := 0; i < 3; i++ {
130 s.Record(ip, 429, 42901)
131 }
132 parts := strings.Split(flushAndRead(t, s, banFile)[0], " ")
133 require.Len(t, parts, 5)
134 require.Equal(t, "2001:db8::abcd", parts[1]) // full IPv6 address
135 require.Equal(t, "2001:db8::/64", parts[2]) // masked to the default IPv6 prefix (/64)
136 }
137
138 func TestService_Record_PerPrefixIsolation(t *testing.T) {
139 // Each source prefix gets its own bucket: one IP hammering to a breach must not push a different,
140 // quiet IP over the edge. This is the whole point of keying by prefix instead of by visitor.
141 banFile := filepath.Join(t.TempDir(), "ban.log")
142 s := newTestService(t, banFile, 2, map[string]int{"*": 1})
143 noisy := netip.MustParseAddr("1.1.1.1")
144 quiet := netip.MustParseAddr("2.2.2.2")
145 for i := 0; i < 5; i++ {
146 s.Record(noisy, 429, 42901) // breaches its own bucket
147 }
148 s.Record(quiet, 429, 42901) // single hit, well under threshold
149 lines := flushAndRead(t, s, banFile)
150 require.Len(t, lines, 1) // only the noisy prefix is written
151 require.True(t, strings.HasSuffix(lines[0], " 1.1.1.1 1.1.1.1/32 429 42901"))
152 }
153
154 func TestService_Record_OncePerWindowThrottle(t *testing.T) {
155 // Once a prefix has been written, further breaches within the window must not re-append it, so a
156 // persistent offender produces exactly one line per window (mirrors the old per-visitor banEmit).
157 banFile := filepath.Join(t.TempDir(), "ban.log")
158 s := newTestService(t, banFile, 1, map[string]int{"*": 1})
159 for i := 0; i < 50; i++ {
160 s.Record(testIP, 429, 42901)
161 }
162 lines := flushAndRead(t, s, banFile)
163 require.Len(t, lines, 1)
164 }
165
166 func TestService_Record_BansPassedIP(t *testing.T) {
167 // The Service bans the exact IP passed to Record -- the caller passes the offending request's IP,
168 // which for an account-keyed visitor is not the visitor's stored IP.
169 banFile := filepath.Join(t.TempDir(), "ban.log")
170 s := newTestService(t, banFile, 1, map[string]int{"*": 1})
171 offender := netip.MustParseAddr("5.6.7.8")
172 for i := 0; i < 3; i++ {
173 s.Record(offender, 429, 42901)
174 }
175 parts := strings.Split(flushAndRead(t, s, banFile)[0], " ")
176 require.Equal(t, "5.6.7.8", parts[1]) // the IP passed to Record
177 require.Equal(t, "5.6.7.8/32", parts[2]) // its prefix
178 }
179
180 func TestService_Record_Ignores2xx3xx(t *testing.T) {
181 banFile := filepath.Join(t.TempDir(), "ban.log")
182 s := newTestService(t, banFile, 3, map[string]int{"*": 1})
183 // Success and redirects must never count toward a ban, even over the threshold -- otherwise a
184 // legit high-volume publisher (lots of 200s) would get banned.
185 for i := 0; i < 20; i++ {
186 s.Record(testIP, 200, 20000)
187 s.Record(testIP, 302, 30000)
188 }
189 s.flush()
190 require.NoFileExists(t, banFile)
191 // A 4xx over the same budget still gets written.
192 for i := 0; i < 5; i++ {
193 s.Record(testIP, 400, 40001)
194 }
195 lines := flushAndRead(t, s, banFile)
196 require.Len(t, lines, 1)
197 require.True(t, strings.HasSuffix(lines[0], " 1.2.3.4 1.2.3.4/32 400 40001"))
198 }
199
200 func TestService_Record_BuffersUntilFlush(t *testing.T) {
201 // Writes are async: a breach buffers the ban line rather than writing it synchronously on the
202 // request path. The line only reaches the file when runWriteLoop (or an explicit flush) runs.
203 banFile := filepath.Join(t.TempDir(), "ban.log")
204 s := newTestService(t, banFile, 1, map[string]int{"*": 1})
205 for i := 0; i < 3; i++ {
206 s.Record(testIP, 429, 42901)
207 }
208 require.NoFileExists(t, banFile) // not written synchronously
209 s.mu.Lock()
210 require.Len(t, s.pending, 1) // one line buffered (throttled to once per window)
211 s.mu.Unlock()
212 lines := flushAndRead(t, s, banFile)
213 require.Len(t, lines, 1)
214 require.True(t, strings.HasSuffix(lines[0], " 1.2.3.4 1.2.3.4/32 429 42901"))
215 }
216
217 func TestService_Close_FlushesPending(t *testing.T) {
218 // Close must flush buffered bans so nothing is lost on shutdown, and must block until it has.
219 banFile := filepath.Join(t.TempDir(), "ban.log")
220 s := NewService(&Config{File: banFile, Window: time.Minute, Threshold: 1, Weights: Weights{"*": 1}, PrefixBitsIPv4: 32, PrefixBitsIPv6: 64})
221 for i := 0; i < 3; i++ {
222 s.Record(testIP, 429, 42901)
223 }
224 require.NoFileExists(t, banFile) // still buffered
225 s.Close() // blocks until the final flush completes
226 data, err := os.ReadFile(banFile)
227 require.NoError(t, err)
228 require.Len(t, strings.Split(strings.TrimRight(string(data), "\n"), "\n"), 1)
229 }
230
231 func TestService_Prune_DropsIdlePrefixes(t *testing.T) {
232 // A prefix idle for a full window has a refilled bucket, so prune drops it to bound memory. An
233 // active prefix (seen within the window) is kept.
234 banFile := filepath.Join(t.TempDir(), "ban.log")
235 s := newTestService(t, banFile, 10, map[string]int{"*": 1})
236 idle := netip.MustParseAddr("9.9.9.9")
237 s.Record(idle, 400, 40001)
238 s.Record(testIP, 400, 40001)
239 require.Len(t, s.trackers, 2)
240
241 // Backdate the idle prefix past the window, then prune.
242 idlePrefix := s.prefix(idle)
243 s.mu.Lock()
244 s.trackers[idlePrefix].seen = time.Now().Add(-2 * time.Minute)
245 s.mu.Unlock()
246 s.prune()
247
248 require.Len(t, s.trackers, 1)
249 _, ok := s.trackers[idlePrefix]
250 require.False(t, ok) // idle prefix dropped
251 _, ok = s.trackers[s.prefix(testIP)]
252 require.True(t, ok) // active prefix kept
253 }