Debian Codegraph @

server/ban_test.go

raw
1 package server
2
3 import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8 "time"
9
10 "github.com/stretchr/testify/require"
11 "heckel.io/ntfy/v2/ban"
12 )
13
14 // TestServer_BanFeed_WritesOffenderToFile is the end-to-end wiring test: a rejected request flows
15 // through s.handle -> the error responder -> s.ban.Record, and once the offender's prefix
16 // breaches, its ban line lands in the ban file (flushed on Close).
17 func TestServer_BanFeed_WritesOffenderToFile(t *testing.T) {
18 banFile := filepath.Join(t.TempDir(), "ban.log")
19 conf := newTestConfig(t, "")
20 conf.BanFile = banFile
21 conf.BanWindow = time.Minute
22 conf.BanThreshold = 1 // capacity 1: the 2nd rejection breaches
23 conf.BanWeights = ban.Weights{"*": 1} // any 4xx counts one strike
24 s := newTestServer(t, conf)
25 require.NotNil(t, s.ban)
26
27 // A delayed message with caching disabled is a deterministic 400 (errHTTPBadRequestDelayNoCache).
28 // request() sends from RemoteAddr 9.9.9.9.
29 reject := map[string]string{"Cache": "no", "In": "30 min"}
30 for i := 0; i < 3; i++ {
31 response := request(t, s, "PUT", "/mytopic", "", reject)
32 require.Equal(t, 400, response.Code)
33 }
34
35 // Writes are async; Close flushes the buffer. The offender's prefix must be in the feed exactly
36 // once (throttled to one line per window).
37 s.ban.Close()
38 data, err := os.ReadFile(banFile)
39 require.NoError(t, err)
40 lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")
41 require.Len(t, lines, 1)
42 require.Contains(t, lines[0], " 9.9.9.9 9.9.9.9/32 400 ") // <ip> <prefix> <http-code> <ntfy-code>
43 }
44
45 // TestServer_BanFeed_DisabledByDefault verifies the feature is off with no ban file: s.ban is
46 // nil and the error path skips it (guarded), so a rejected request must not panic.
47 func TestServer_BanFeed_DisabledByDefault(t *testing.T) {
48 conf := newTestConfig(t, "") // no BanFile
49 s := newTestServer(t, conf)
50 require.Nil(t, s.ban)
51
52 reject := map[string]string{"Cache": "no", "In": "30 min"}
53 response := request(t, s, "PUT", "/mytopic", "", reject) // guarded callsite, no Record
54 require.Equal(t, 400, response.Code)
55 }