Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
782eb7c34c |
No files matched your search
@@ -93,6 +93,9 @@ never as a time.
|
||||
imports no other package of this repository: `waf` gives it what it needs
|
||||
to count and report failures.
|
||||
- `internal/lookup`: looks clients up in the lookup database.
|
||||
- `internal/dirwatch`: watches a directory, and calls a function once it has
|
||||
gone a short time without a change. `internal/rules` and `internal/lookup`
|
||||
read their files again this way.
|
||||
- `internal/reputation`: fetches the lists, asks the DNS blocklists and
|
||||
AbuseIPDB in the background, and keeps their answers. It also fetches
|
||||
AbuseIPDB's blacklist, which `internal/waf` bans.
|
||||
|
||||
+32
-93
@@ -75,7 +75,7 @@ type WAF struct {
|
||||
BytesLimitPerMinute int64
|
||||
BytesLimitPerHour int64
|
||||
BytesLimitPerDay int64
|
||||
BytesCounted BytesCounted
|
||||
BytesCounted string
|
||||
// LookupSource is where each client's AS number and country are looked
|
||||
// up (SWW_WAF_LOOKUP_SOURCE): geojs, file, or off for nowhere.
|
||||
// LookupDBPath is the lookup database, the IPinfo Lite file looked up in
|
||||
@@ -86,7 +86,7 @@ type WAF struct {
|
||||
// AddLookupHeaders is true when the app is passed the client's AS number
|
||||
// and country in headers (SWW_WAF_ADD_LOOKUP_HEADERS), by default unless
|
||||
// LookupSource is off.
|
||||
LookupSource LookupSource
|
||||
LookupSource string
|
||||
LookupDBPath string
|
||||
ASNAndCountryLookupTimeout time.Duration
|
||||
AddLookupHeaders bool
|
||||
@@ -131,7 +131,7 @@ type WAF struct {
|
||||
// BlocklistLimitPercent is the percentage of every limit it gets.
|
||||
BlocklistURLs []string
|
||||
BlocklistRefresh time.Duration
|
||||
BlocklistAction ReputationAction
|
||||
BlocklistAction string
|
||||
BlocklistLimitPercent int64
|
||||
// DNSBLZones are the DNSBL zones clients are asked about
|
||||
// (SWW_WAF_DNSBL_ZONES), through DNSBLResolver (SWW_WAF_DNSBL_RESOLVER), or
|
||||
@@ -154,7 +154,7 @@ type WAF struct {
|
||||
AbuseIPDBKey string
|
||||
AbuseIPDBMinScore int64
|
||||
AbuseIPDBDailyBudget int
|
||||
DNSBLAbuseIPDBAction ReputationAction
|
||||
DNSBLAbuseIPDBAction string
|
||||
DNSBLAbuseIPDBLimitPercent int64
|
||||
IPReputationCacheTTL time.Duration
|
||||
DNSBLAbuseIPDBTimeout time.Duration
|
||||
@@ -237,7 +237,7 @@ type WAF struct {
|
||||
// reads none.
|
||||
// CoreRuleSetExclusionsFile is the path of the file of its exclusions
|
||||
// (SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE), "" while there is none.
|
||||
CoreRuleSetMode CoreRuleSetMode
|
||||
CoreRuleSetMode string
|
||||
CoreRuleSetParanoiaLevel int
|
||||
CoreRuleSetScoreThreshold int
|
||||
CoreRuleSetDisabledRules []int
|
||||
@@ -316,66 +316,20 @@ type WAF struct {
|
||||
settings []slog.Attr
|
||||
}
|
||||
|
||||
// BytesCounted is which body bytes count toward the byte limits and the
|
||||
// byte anomaly thresholds, a value of SWW_WAF_BYTES_COUNTED.
|
||||
type BytesCounted string
|
||||
|
||||
// The values of SWW_WAF_BYTES_COUNTED.
|
||||
const (
|
||||
// BytesCountedResponse counts the response's body bytes.
|
||||
BytesCountedResponse BytesCounted = "response"
|
||||
// BytesCountedRequest counts the request's body bytes.
|
||||
BytesCountedRequest BytesCounted = "request"
|
||||
// BytesCountedBoth counts the body bytes of both.
|
||||
BytesCountedBoth BytesCounted = "both"
|
||||
)
|
||||
|
||||
// LookupSource is where each client's AS number and country are looked up,
|
||||
// a value of SWW_WAF_LOOKUP_SOURCE.
|
||||
type LookupSource string
|
||||
|
||||
// The values of SWW_WAF_LOOKUP_SOURCE.
|
||||
const (
|
||||
// LookupSourceGeoJS asks GeoJS.
|
||||
LookupSourceGeoJS LookupSource = "geojs"
|
||||
// LookupSourceFile looks clients up in the lookup database, the file
|
||||
// SWW_WAF_LOOKUP_DB_PATH names.
|
||||
LookupSourceFile LookupSource = "file"
|
||||
// LookupSourceOff looks no client up.
|
||||
LookupSourceOff LookupSource = "off"
|
||||
)
|
||||
|
||||
// ReputationAction is what is done with a client a reputation source
|
||||
// lists, a value of SWW_WAF_BLOCKLIST_ACTION and of
|
||||
// SWW_WAF_DNSBL_ABUSEIPDB_ACTION.
|
||||
type ReputationAction string
|
||||
|
||||
// The values of SWW_WAF_BLOCKLIST_ACTION and SWW_WAF_DNSBL_ABUSEIPDB_ACTION.
|
||||
const (
|
||||
// ReputationActionDeny refuses the client's requests.
|
||||
ReputationActionDeny ReputationAction = "deny"
|
||||
// ReputationActionLimit gives the client a percentage of every limit,
|
||||
// written limit:<percent> in the setting.
|
||||
ReputationActionLimit ReputationAction = "limit"
|
||||
// ReputationActionLog only notes the hit in the log line and raises an
|
||||
// alert.
|
||||
ReputationActionLog ReputationAction = "log"
|
||||
)
|
||||
|
||||
// CoreRuleSetMode is what the Core Rule Set does, a value of
|
||||
// SWW_WAF_CORE_RULE_SET_MODE.
|
||||
type CoreRuleSetMode string
|
||||
|
||||
// The values of SWW_WAF_CORE_RULE_SET_MODE.
|
||||
const (
|
||||
// CoreRuleSetModeOff runs no request through the Core Rule Set.
|
||||
CoreRuleSetModeOff CoreRuleSetMode = "off"
|
||||
CoreRuleSetModeOff = off
|
||||
// CoreRuleSetModeDetect logs and alerts a match, and refuses nothing.
|
||||
CoreRuleSetModeDetect CoreRuleSetMode = "detect"
|
||||
CoreRuleSetModeDetect = "detect"
|
||||
// CoreRuleSetModeBlock refuses a match with 403.
|
||||
CoreRuleSetModeBlock CoreRuleSetMode = "block"
|
||||
CoreRuleSetModeBlock = "block"
|
||||
)
|
||||
|
||||
// fileSource is the SWW_WAF_LOOKUP_SOURCE that looks clients up in the
|
||||
// lookup database, the file SWW_WAF_LOOKUP_DB_PATH names.
|
||||
const fileSource = "file"
|
||||
|
||||
const (
|
||||
day = 24 * time.Hour
|
||||
ipv4Bits = 32
|
||||
@@ -604,13 +558,10 @@ func WAFFromEnvironment(v *viper.Viper) (*WAF, error) {
|
||||
),
|
||||
BytesLimitPerHour: env.size("SWW_WAF_BYTES_LIMIT_PER_HOUR", "50G"),
|
||||
BytesLimitPerDay: env.size("SWW_WAF_BYTES_LIMIT_PER_DAY", "100G"),
|
||||
BytesCounted: env.bytesCounted(
|
||||
"SWW_WAF_BYTES_COUNTED",
|
||||
BytesCountedBoth,
|
||||
),
|
||||
BytesCounted: env.bytesCounted("SWW_WAF_BYTES_COUNTED", "both"),
|
||||
LookupSource: env.lookupSource(
|
||||
"SWW_WAF_LOOKUP_SOURCE",
|
||||
LookupSourceGeoJS,
|
||||
"geojs",
|
||||
),
|
||||
LookupDBPath: env.value("SWW_WAF_LOOKUP_DB_PATH", ""),
|
||||
ASNAndCountryLookupTimeout: env.milliseconds(
|
||||
@@ -807,9 +758,9 @@ func WAFFromEnvironment(v *viper.Viper) (*WAF, error) {
|
||||
cfg.InstanceName, cfg.LogRemoteURL != nil)
|
||||
// The app gets the headers by default, unless no client is looked up.
|
||||
cfg.AddLookupHeaders = env.boolean("SWW_WAF_ADD_LOOKUP_HEADERS",
|
||||
strconv.FormatBool(cfg.LookupSource != LookupSourceOff))
|
||||
strconv.FormatBool(cfg.LookupSource != off))
|
||||
cfg.BlocklistAction, cfg.BlocklistLimitPercent = env.action(
|
||||
"SWW_WAF_BLOCKLIST_ACTION", string(ReputationActionDeny))
|
||||
"SWW_WAF_BLOCKLIST_ACTION", "deny")
|
||||
cfg.DNSBLAbuseIPDBAction, cfg.DNSBLAbuseIPDBLimitPercent = env.action(
|
||||
"SWW_WAF_DNSBL_ABUSEIPDB_ACTION", "limit:25")
|
||||
|
||||
@@ -907,12 +858,9 @@ func (e *environment) count(name, defaultValue string) int64 {
|
||||
|
||||
// bytesCounted reads the setting that is which body bytes count toward the
|
||||
// byte limits and the byte anomaly thresholds: response, request or both.
|
||||
func (e *environment) bytesCounted(
|
||||
name string, defaultValue BytesCounted,
|
||||
) BytesCounted {
|
||||
value := BytesCounted(e.value(name, string(defaultValue)))
|
||||
if value != BytesCountedResponse && value != BytesCountedRequest &&
|
||||
value != BytesCountedBoth {
|
||||
func (e *environment) bytesCounted(name, defaultValue string) string {
|
||||
value := e.value(name, defaultValue)
|
||||
if value != "response" && value != "request" && value != "both" {
|
||||
e.check(name, fmt.Errorf("%q %w", value, errNotBytesCounted))
|
||||
}
|
||||
|
||||
@@ -957,10 +905,8 @@ func (e *environment) trapPaths(name string) []string {
|
||||
|
||||
// coreRuleSetMode reads the setting that is what the Core Rule Set does: off,
|
||||
// detect or block.
|
||||
func (e *environment) coreRuleSetMode(
|
||||
name string, defaultValue CoreRuleSetMode,
|
||||
) CoreRuleSetMode {
|
||||
mode := CoreRuleSetMode(e.value(name, string(defaultValue)))
|
||||
func (e *environment) coreRuleSetMode(name, defaultValue string) string {
|
||||
mode := e.value(name, defaultValue)
|
||||
if mode != CoreRuleSetModeOff && mode != CoreRuleSetModeDetect &&
|
||||
mode != CoreRuleSetModeBlock {
|
||||
e.check(name, fmt.Errorf("%q %w", mode, errNotCoreRuleSetMode))
|
||||
@@ -1110,24 +1056,20 @@ func (e *environment) refresh(name, defaultValue string) time.Duration {
|
||||
// action reads a setting that is what is done with a client a blocklist
|
||||
// or a DNSBL zone lists: deny, log, or limit:<percent>, which it returns
|
||||
// as limit and the percentage.
|
||||
func (e *environment) action(
|
||||
name, defaultValue string,
|
||||
) (ReputationAction, int64) {
|
||||
value := ReputationAction(e.value(name, defaultValue))
|
||||
if value == ReputationActionDeny || value == ReputationActionLog {
|
||||
func (e *environment) action(name, defaultValue string) (string, int64) {
|
||||
value := e.value(name, defaultValue)
|
||||
if value == "deny" || value == "log" {
|
||||
return value, 0
|
||||
}
|
||||
|
||||
percentText, isLimit := strings.CutPrefix(
|
||||
string(value), string(ReputationActionLimit)+":",
|
||||
)
|
||||
percentText, isLimit := strings.CutPrefix(value, "limit:")
|
||||
|
||||
percent, err := ParsePercent(percentText)
|
||||
if !isLimit || err != nil {
|
||||
e.check(name, fmt.Errorf("%q %w", value, errNotAction))
|
||||
}
|
||||
|
||||
return ReputationActionLimit, percent
|
||||
return "limit", percent
|
||||
}
|
||||
|
||||
// zones reads the setting that is the list of DNSBL zones. It is empty by
|
||||
@@ -1178,12 +1120,9 @@ func (e *environment) routeWatchURL(name string) string {
|
||||
|
||||
// lookupSource reads the setting that is where clients are looked up:
|
||||
// geojs, file, or off.
|
||||
func (e *environment) lookupSource(
|
||||
name string, defaultValue LookupSource,
|
||||
) LookupSource {
|
||||
source := LookupSource(e.value(name, string(defaultValue)))
|
||||
if source != LookupSourceGeoJS && source != LookupSourceFile &&
|
||||
source != LookupSourceOff {
|
||||
func (e *environment) lookupSource(name, defaultValue string) string {
|
||||
source := e.value(name, defaultValue)
|
||||
if source != "geojs" && source != fileSource && source != off {
|
||||
e.check(name, fmt.Errorf("%q %w", source, errNotLookupSource))
|
||||
}
|
||||
|
||||
@@ -1195,12 +1134,12 @@ func (e *environment) lookupSource(
|
||||
// one source at a time.
|
||||
func (e *environment) checkLookupDBPath(cfg *WAF) {
|
||||
switch {
|
||||
case cfg.LookupSource == LookupSourceFile && cfg.LookupDBPath == "":
|
||||
case cfg.LookupSource == fileSource && cfg.LookupDBPath == "":
|
||||
e.check("SWW_WAF_LOOKUP_SOURCE", fmt.Errorf(
|
||||
"is file while SWW_WAF_LOOKUP_DB_PATH is unset; %w",
|
||||
errNeedsDBPath,
|
||||
))
|
||||
case cfg.LookupSource != LookupSourceFile && cfg.LookupDBPath != "":
|
||||
case cfg.LookupSource != fileSource && cfg.LookupDBPath != "":
|
||||
e.check("SWW_WAF_LOOKUP_DB_PATH", fmt.Errorf(
|
||||
"is set while SWW_WAF_LOOKUP_SOURCE is %s; %w",
|
||||
cfg.LookupSource,
|
||||
@@ -1225,7 +1164,7 @@ func (e *environment) checkCountriesAndLookups(cfg *WAF) {
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.LookupSource != LookupSourceOff {
|
||||
if cfg.LookupSource != off {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -614,7 +614,7 @@ func TestCoreRuleSetSettings(t *testing.T) {
|
||||
},
|
||||
{
|
||||
environment{
|
||||
coreRuleSetMode: string(config.CoreRuleSetModeDetect),
|
||||
coreRuleSetMode: config.CoreRuleSetModeDetect,
|
||||
coreRuleSetParanoiaLevel: "4",
|
||||
coreRuleSetScoreThreshold: "10",
|
||||
coreRuleSetDisabledRules: "942100, 920350",
|
||||
@@ -2033,9 +2033,8 @@ func TestReputationSettingsAsSet(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
value string
|
||||
action config.ReputationAction
|
||||
percent int64
|
||||
value, action string
|
||||
percent int64
|
||||
}{
|
||||
{actionDeny, actionDeny, 0},
|
||||
{actionLog, actionLog, 0},
|
||||
@@ -2168,7 +2167,7 @@ func TestDNSBLSettingsAsSet(t *testing.T) {
|
||||
// want are the zones, resolver, action and percent config.WAF gives.
|
||||
want []string
|
||||
wantResolver string
|
||||
wantAction config.ReputationAction
|
||||
wantAction string
|
||||
wantPercent int64
|
||||
}{
|
||||
{
|
||||
@@ -3050,7 +3049,7 @@ func TestLogsEachSettingWithItsValue(t *testing.T) {
|
||||
logLevel: "info",
|
||||
ruleFilesDir: "/etc/sww/rules.d",
|
||||
ruleFilesEnabled: "true",
|
||||
coreRuleSetMode: string(config.CoreRuleSetModeBlock),
|
||||
coreRuleSetMode: config.CoreRuleSetModeBlock,
|
||||
coreRuleSetParanoiaLevel: "1",
|
||||
coreRuleSetScoreThreshold: "5",
|
||||
coreRuleSetDisabledRules: defaultCoreRuleSetDisabledRules,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Package dirwatch watches a directory, and calls a function once the
|
||||
// directory has gone a short time without a change after one. The rule
|
||||
// files and the lookup database are read again this way.
|
||||
package dirwatch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
)
|
||||
|
||||
// quietTime is how long the directory must go without a change before the
|
||||
// function is called, so that a file still being written, such as one
|
||||
// saved in place, appended to or copied in with scp, is read only once
|
||||
// whole.
|
||||
const quietTime = 2 * time.Second
|
||||
|
||||
// Watcher watches one directory. The directory is watched, rather than a
|
||||
// file in it, so that a file replaced by a rename is seen.
|
||||
type Watcher struct {
|
||||
watcher *fsnotify.Watcher
|
||||
}
|
||||
|
||||
// New starts watching dir, or returns why it cannot.
|
||||
func New(dir string) (*Watcher, error) {
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = watcher.Add(dir)
|
||||
if err != nil {
|
||||
_ = watcher.Close()
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Watcher{watcher: watcher}, nil
|
||||
}
|
||||
|
||||
// Close stops watching the directory.
|
||||
func (w *Watcher) Close() error {
|
||||
return w.watcher.Close()
|
||||
}
|
||||
|
||||
// CallWhenQuiet calls changed each time the directory has gone quietTime
|
||||
// without a change, after a change to a path for which counts is true, until
|
||||
// ctx is done. It also calls failed with each error the watch reports. The
|
||||
// wait starts at once, as if for a change, so that a change made before the
|
||||
// watch began is taken in too.
|
||||
func (w *Watcher) CallWhenQuiet(
|
||||
ctx context.Context,
|
||||
counts func(path string) bool,
|
||||
changed func(),
|
||||
failed func(error),
|
||||
) {
|
||||
callWhenQuiet(
|
||||
ctx, w.watcher.Events, w.watcher.Errors, counts, changed, failed,
|
||||
)
|
||||
}
|
||||
|
||||
// callWhenQuiet is CallWhenQuiet, for the changes from events and the
|
||||
// errors from errs.
|
||||
func callWhenQuiet(
|
||||
ctx context.Context,
|
||||
events <-chan fsnotify.Event,
|
||||
errs <-chan error,
|
||||
counts func(path string) bool,
|
||||
changed func(),
|
||||
failed func(error),
|
||||
) {
|
||||
quiet := time.NewTimer(quietTime)
|
||||
defer quiet.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case event := <-events:
|
||||
if counts(event.Name) {
|
||||
quiet.Reset(quietTime)
|
||||
}
|
||||
case <-quiet.C:
|
||||
changed()
|
||||
case err := <-errs:
|
||||
failed(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package dirwatch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
)
|
||||
|
||||
// errWatch is an error the watch reports.
|
||||
var errWatch = errors.New("too many changes")
|
||||
|
||||
// The tests below run callWhenQuiet in a synctest bubble, where time is a
|
||||
// clock of the test's own: time.Sleep moves it on at once, and
|
||||
// synctest.Wait returns once callWhenQuiet waits again, so that every call
|
||||
// due by then is made. The test sends the changes itself, as the watch of
|
||||
// a directory cannot run in a bubble.
|
||||
|
||||
func TestSecondChangeStartsTheWaitAgain(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
loop := start(t, everyPath)
|
||||
|
||||
loop.changes <- fsnotify.Event{Name: "50-app.rules", Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime - time.Nanosecond)
|
||||
synctest.Wait()
|
||||
loop.wantCalls(t, 0)
|
||||
|
||||
// The second part starts the wait again.
|
||||
loop.changes <- fsnotify.Event{Name: "50-app.rules", Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime - time.Nanosecond)
|
||||
synctest.Wait()
|
||||
loop.wantCalls(t, 0)
|
||||
|
||||
time.Sleep(time.Nanosecond)
|
||||
synctest.Wait()
|
||||
loop.wantCalls(t, 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCalledOnceQuietAfterTheStart(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
// An edit saved before the watch began sends no change, and is
|
||||
// taken in by this call.
|
||||
loop := start(t, everyPath)
|
||||
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
loop.wantCalls(t, 1)
|
||||
|
||||
// Long after, it has been called only once.
|
||||
time.Sleep(time.Hour)
|
||||
synctest.Wait()
|
||||
loop.wantCalls(t, 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestChangeThatDoesNotCountIsNoChange(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
loop := start(t, func(path string) bool {
|
||||
return path == "ipinfo_lite.mmdb"
|
||||
})
|
||||
|
||||
// The wait that starts with the watch ends with a call.
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
|
||||
loop.changes <- fsnotify.Event{Name: "other.mmdb", Op: fsnotify.Create}
|
||||
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
loop.wantCalls(t, 1)
|
||||
|
||||
loop.changes <- fsnotify.Event{Name: "ipinfo_lite.mmdb", Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
loop.wantCalls(t, 2)
|
||||
})
|
||||
}
|
||||
|
||||
func TestErrorsOfTheWatchHandedOn(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
loop := start(t, everyPath)
|
||||
|
||||
loop.errs <- errWatch
|
||||
|
||||
synctest.Wait()
|
||||
|
||||
if !errors.Is(loop.failure, errWatch) {
|
||||
t.Errorf("failed with %v, want %v", loop.failure, errWatch)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDirectoryThatCannotBeWatchedIsAnError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := New(filepath.Join(t.TempDir(), "missing"))
|
||||
if err == nil {
|
||||
t.Error("a missing directory is watched, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
// loop is a callWhenQuiet that a test runs.
|
||||
type loop struct {
|
||||
// changes and errs send it changes and errors.
|
||||
changes chan fsnotify.Event
|
||||
errs chan error
|
||||
// calls counts its calls of changed, and failure is the last error it
|
||||
// handed to failed.
|
||||
calls atomic.Int32
|
||||
failure error
|
||||
}
|
||||
|
||||
// start runs callWhenQuiet, with counts, until the test ends.
|
||||
func start(t *testing.T, counts func(path string) bool) *loop {
|
||||
t.Helper()
|
||||
|
||||
l := &loop{changes: make(chan fsnotify.Event), errs: make(chan error)}
|
||||
ctx, stop := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
callWhenQuiet(ctx, l.changes, l.errs, counts,
|
||||
func() { l.calls.Add(1) },
|
||||
func(err error) { l.failure = err },
|
||||
)
|
||||
close(stopped)
|
||||
}()
|
||||
|
||||
t.Cleanup(func() {
|
||||
stop()
|
||||
<-stopped
|
||||
})
|
||||
|
||||
return l
|
||||
}
|
||||
|
||||
// everyPath counts a change to any path.
|
||||
func everyPath(string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// wantCalls checks how many times changed has been called.
|
||||
func (l *loop) wantCalls(t *testing.T, want int32) {
|
||||
t.Helper()
|
||||
|
||||
got := l.calls.Load()
|
||||
if got != want {
|
||||
t.Errorf("changed called %d times, want %d", got, want)
|
||||
}
|
||||
}
|
||||
+18
-49
@@ -13,18 +13,13 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/oschwald/maxminddb-golang/v2"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/dirwatch"
|
||||
"sneak.berlin/go/smallwebwaf/internal/geojs"
|
||||
)
|
||||
|
||||
// quietTime is how long the lookup database must go without a change
|
||||
// before it is read again, so that a file still being copied in is read
|
||||
// only once whole.
|
||||
const quietTime = 2 * time.Second
|
||||
|
||||
// FileParams are what OpenFile needs.
|
||||
type FileParams struct {
|
||||
// Path is the lookup database, the IPinfo Lite file in its .mmdb form
|
||||
@@ -122,20 +117,13 @@ func (f *File) ReadFailures() int {
|
||||
}
|
||||
|
||||
// Watch watches the directory of the lookup database until ctx is done,
|
||||
// and reads the file again once it has gone without a change for
|
||||
// quietTime, after it is replaced, written or removed, and after Watch
|
||||
// starts watching. If the directory cannot be watched, that is logged, and
|
||||
// the database read at start stays in use.
|
||||
// and reads the file again once it has gone without a change for a short
|
||||
// time, after it is replaced, written or removed, and after Watch starts
|
||||
// watching, as dirwatch describes. A change to another file in its
|
||||
// directory does not count. If the directory cannot be watched, that is
|
||||
// logged, and the database read at start stays in use.
|
||||
func (f *File) Watch(ctx context.Context) {
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err == nil {
|
||||
defer func() {
|
||||
_ = watcher.Close()
|
||||
}()
|
||||
|
||||
err = watcher.Add(filepath.Dir(f.params.Path))
|
||||
}
|
||||
|
||||
watcher, err := dirwatch.New(filepath.Dir(f.params.Path))
|
||||
if err != nil {
|
||||
f.params.ProcessLog.Error(
|
||||
"cannot watch the lookup database for replacements",
|
||||
@@ -146,41 +134,22 @@ func (f *File) Watch(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = watcher.Close()
|
||||
}()
|
||||
|
||||
f.params.ProcessLog.Info("watching the lookup database for replacements",
|
||||
"file", f.params.Path)
|
||||
|
||||
f.readAfterChanges(ctx, watcher.Events, watcher.Errors)
|
||||
watcher.CallWhenQuiet(ctx, f.isDatabase, f.readAgain, func(err error) {
|
||||
f.params.ProcessLog.Warn("watching the lookup database failed",
|
||||
"error", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
// readAfterChanges reads the lookup database again once quietTime has
|
||||
// passed without a change to it from events, until ctx is done, and logs
|
||||
// the errors from errs. A change to another file in its directory does not
|
||||
// count. The wait starts at once, as if for a change, so that a file
|
||||
// replaced after OpenFile read it, and before its directory was watched,
|
||||
// is read too.
|
||||
func (f *File) readAfterChanges(
|
||||
ctx context.Context, events <-chan fsnotify.Event, errs <-chan error,
|
||||
) {
|
||||
path := filepath.Clean(f.params.Path)
|
||||
|
||||
quiet := time.NewTimer(quietTime)
|
||||
defer quiet.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case event := <-events:
|
||||
if filepath.Clean(event.Name) == path {
|
||||
quiet.Reset(quietTime)
|
||||
}
|
||||
case <-quiet.C:
|
||||
f.readAgain()
|
||||
case err := <-errs:
|
||||
f.params.ProcessLog.Warn("watching the lookup database failed",
|
||||
"error", err.Error())
|
||||
}
|
||||
}
|
||||
// isDatabase reports whether path names the lookup database.
|
||||
func (f *File) isDatabase(path string) bool {
|
||||
return filepath.Clean(path) == filepath.Clean(f.params.Path)
|
||||
}
|
||||
|
||||
// readAgain reads the lookup database again, in place of the one in use,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package lookup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
@@ -12,7 +11,6 @@ import (
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/maxmind/mmdbwriter/mmdbtype"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
@@ -133,66 +131,23 @@ func TestFileThatCannotBeReadIsAnError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The tests below run readAfterChanges in a synctest bubble, where time is
|
||||
// a clock of the test's own: time.Sleep moves it on at once, and
|
||||
// synctest.Wait returns once readAfterChanges waits again, so that every
|
||||
// reading due by then is done. The test sends the changes itself, as the
|
||||
// watch of a directory cannot run in a bubble.
|
||||
// The tests below run in a synctest bubble, where time is a clock of the
|
||||
// test's own, so that the time a file is read can be checked. The wait for
|
||||
// the directory to go quiet before a reading is tested in dirwatch.
|
||||
|
||||
func TestReplacementCopiedOverTheFileInTwoPartsIsReadOnlyWhole(
|
||||
t *testing.T,
|
||||
) {
|
||||
func TestReplacementIsReadAgain(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "ipinfo_lite.mmdb")
|
||||
path := filepath.Join(t.TempDir(), "ipinfo_lite.mmdb")
|
||||
writeDatabase(t, path, "DE")
|
||||
|
||||
queue := newQueue()
|
||||
f := openFile(t, path, queue)
|
||||
changes := watch(t, f)
|
||||
|
||||
other := filepath.Join(dir, "replacement.mmdb")
|
||||
writeDatabase(t, other, "KP")
|
||||
|
||||
//nolint:gosec // a file the test wrote
|
||||
replacement, err := os.ReadFile(other)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", other, err)
|
||||
}
|
||||
|
||||
// The file in use is overwritten in place, and keeps giving what
|
||||
// it gave. Its first part alone is not a .mmdb file.
|
||||
file, err := os.Create(path) //nolint:gosec // a file the test wrote
|
||||
if err != nil {
|
||||
t.Fatalf("create %s: %v", path, err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = file.Close()
|
||||
}()
|
||||
|
||||
half := len(replacement) / 2
|
||||
write(t, file, replacement[:half])
|
||||
|
||||
changes <- fsnotify.Event{Name: path, Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime - time.Nanosecond)
|
||||
synctest.Wait()
|
||||
wantCountry(t, f, "DE")
|
||||
|
||||
// The second part starts the wait again.
|
||||
write(t, file, replacement[half:])
|
||||
|
||||
changes <- fsnotify.Event{Name: path, Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime - time.Nanosecond)
|
||||
synctest.Wait()
|
||||
wantCountry(t, f, "DE")
|
||||
|
||||
time.Sleep(time.Nanosecond)
|
||||
synctest.Wait()
|
||||
writeDatabase(t, path, "KP")
|
||||
time.Sleep(time.Hour)
|
||||
f.readAgain()
|
||||
wantCountry(t, f, "KP")
|
||||
|
||||
if !f.LastRead().Equal(time.Now()) || f.ReadFailures() != 0 {
|
||||
@@ -219,15 +174,10 @@ func TestReplacementThatCannotBeReadLeavesTheFileInUseWithOneAlert(
|
||||
queue := newQueue()
|
||||
f := openFile(t, path, queue)
|
||||
read := f.LastRead()
|
||||
changes := watch(t, f)
|
||||
|
||||
writeFile(t, path, "not a lookup database\n")
|
||||
|
||||
changes <- fsnotify.Event{Name: path, Op: fsnotify.Write}
|
||||
|
||||
// Long after, the replacement has been read once.
|
||||
time.Sleep(time.Hour)
|
||||
synctest.Wait()
|
||||
f.readAgain()
|
||||
wantCountry(t, f, "DE")
|
||||
|
||||
if !f.LastRead().Equal(read) || f.ReadFailures() != 1 {
|
||||
@@ -240,7 +190,7 @@ func TestReplacementThatCannotBeReadLeavesTheFileInUseWithOneAlert(
|
||||
}
|
||||
|
||||
wantAlerts(t, queue, alerts.Alert{
|
||||
Time: read.Add(quietTime),
|
||||
Time: read.Add(time.Hour),
|
||||
Event: alerts.EventFileError,
|
||||
Reason: "the lookup database cannot be read, and the one read before stays in use",
|
||||
Detail: map[string]any{
|
||||
@@ -255,50 +205,26 @@ func TestReplacementThatCannotBeReadLeavesTheFileInUseWithOneAlert(
|
||||
func TestChangeOfAnotherFileInTheDirectoryIsNoReplacement(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "ipinfo_lite.mmdb")
|
||||
writeDatabase(t, path, "DE")
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "ipinfo_lite.mmdb")
|
||||
writeDatabase(t, path, "DE")
|
||||
|
||||
f := openFile(t, path, newQueue())
|
||||
changes := watch(t, f)
|
||||
f := openFile(t, path, newQueue())
|
||||
|
||||
// The wait that starts with the watch ends with a reading.
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
writeDatabase(t, path, "KP")
|
||||
|
||||
changes <- fsnotify.Event{Name: filepath.Join(dir, "other.mmdb"), Op: fsnotify.Create}
|
||||
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
wantCountry(t, f, "DE")
|
||||
|
||||
changes <- fsnotify.Event{Name: path, Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
wantCountry(t, f, "KP")
|
||||
})
|
||||
}
|
||||
|
||||
func TestReplacementSavedBeforeTheWatchStartsIsRead(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "ipinfo_lite.mmdb")
|
||||
writeDatabase(t, path, "DE")
|
||||
|
||||
f := openFile(t, path, newQueue())
|
||||
|
||||
// Saved after OpenFile read the file, and before its directory was
|
||||
// watched, so that no change is seen for it.
|
||||
writeDatabase(t, path, "KP")
|
||||
watch(t, f)
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
wantCountry(t, f, "KP")
|
||||
})
|
||||
for changed, want := range map[string]bool{
|
||||
path: true,
|
||||
dir + "/./ipinfo_lite.mmdb": true,
|
||||
filepath.Join(dir, "other.mmdb"): false,
|
||||
} {
|
||||
if f.isDatabase(changed) != want {
|
||||
t.Errorf(
|
||||
"a change to %s counts: %t, want %t",
|
||||
changed,
|
||||
!want,
|
||||
want,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newQueue returns a queue of alerts for a webhook that is never sent
|
||||
@@ -344,28 +270,6 @@ func openFile(t *testing.T, path string, queue *alerts.Queue) *File {
|
||||
return f
|
||||
}
|
||||
|
||||
// watch runs f's readAfterChanges until the test ends, and returns the
|
||||
// channel that sends it changes.
|
||||
func watch(t *testing.T, f *File) chan<- fsnotify.Event {
|
||||
t.Helper()
|
||||
|
||||
changes := make(chan fsnotify.Event)
|
||||
ctx, stop := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
f.readAfterChanges(ctx, changes, nil)
|
||||
close(stopped)
|
||||
}()
|
||||
|
||||
t.Cleanup(func() {
|
||||
stop()
|
||||
<-stopped
|
||||
})
|
||||
|
||||
return changes
|
||||
}
|
||||
|
||||
// wantCountry checks the country f gives testClient.
|
||||
func wantCountry(t *testing.T, f *File, want string) {
|
||||
t.Helper()
|
||||
@@ -401,13 +305,3 @@ func writeFile(t *testing.T, path, content string) {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// write writes data to the end of file.
|
||||
func write(t *testing.T, file *os.File, data []byte) {
|
||||
t.Helper()
|
||||
|
||||
_, err := file.Write(data)
|
||||
if err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
}
|
||||
+19
-49
@@ -18,12 +18,10 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/dirwatch"
|
||||
)
|
||||
|
||||
// The actions a rule takes when it matches.
|
||||
@@ -40,12 +38,6 @@ const (
|
||||
// extension ends the name of every rule file.
|
||||
const extension = ".rules"
|
||||
|
||||
// quietTime is how long SWW_WAF_RULE_FILES_DIR must go without a change before
|
||||
// the rule files are read again, so that a file still being written, such
|
||||
// as one saved in place, appended to or copied in with scp, is read only
|
||||
// once whole.
|
||||
const quietTime = 2 * time.Second
|
||||
|
||||
// headerTarget starts the target that is one request header,
|
||||
// header:<Name>.
|
||||
const headerTarget = "header:"
|
||||
@@ -176,26 +168,18 @@ func (f *Files) Len() int {
|
||||
}
|
||||
|
||||
// Watch watches Dir until ctx is done, and reads the rule files again
|
||||
// once Dir has had no change for quietTime, after one is edited, added or
|
||||
// removed, and after Watch starts watching. If they then hold an error,
|
||||
// the rules stay as they were, the error is logged with its file and
|
||||
// line, and the files are read again after the next change. If Dir cannot
|
||||
// be watched, that is logged, and the rules stay as they were loaded.
|
||||
// While Enabled is false, Watch returns at once.
|
||||
// once Dir has had no change for a short time, after one is edited, added
|
||||
// or removed, and after Watch starts watching, as dirwatch describes. If
|
||||
// they then hold an error, the rules stay as they were, the error is
|
||||
// logged with its file and line, and the files are read again after the
|
||||
// next change. If Dir cannot be watched, that is logged, and the rules
|
||||
// stay as they were loaded. While Enabled is false, Watch returns at once.
|
||||
func (f *Files) Watch(ctx context.Context) {
|
||||
if !f.params.Enabled {
|
||||
return
|
||||
}
|
||||
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err == nil {
|
||||
defer func() {
|
||||
_ = watcher.Close()
|
||||
}()
|
||||
|
||||
err = watcher.Add(f.params.Dir)
|
||||
}
|
||||
|
||||
watcher, err := dirwatch.New(f.params.Dir)
|
||||
if err != nil {
|
||||
f.params.ProcessLog.Error("cannot watch the rule files for edits",
|
||||
"error", err.Error())
|
||||
@@ -203,36 +187,22 @@ func (f *Files) Watch(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = watcher.Close()
|
||||
}()
|
||||
|
||||
f.params.ProcessLog.Info("watching the rule files for edits",
|
||||
"directory", f.params.Dir)
|
||||
|
||||
f.readAfterChanges(ctx, watcher.Events, watcher.Errors)
|
||||
}
|
||||
|
||||
// readAfterChanges reads the rule files again once quietTime has passed
|
||||
// without a change from events, until ctx is done, and logs the errors
|
||||
// from errs. The wait starts at once, as if for a change, so that an edit
|
||||
// saved after Load read the files, and before Dir was watched, is taken
|
||||
// in too.
|
||||
func (f *Files) readAfterChanges(
|
||||
ctx context.Context, events <-chan fsnotify.Event, errs <-chan error,
|
||||
) {
|
||||
quiet := time.NewTimer(quietTime)
|
||||
defer quiet.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-events:
|
||||
quiet.Reset(quietTime)
|
||||
case <-quiet.C:
|
||||
f.readAgain()
|
||||
case err := <-errs:
|
||||
// A change to any file in Dir counts.
|
||||
watcher.CallWhenQuiet(ctx,
|
||||
func(string) bool { return true },
|
||||
f.readAgain,
|
||||
func(err error) {
|
||||
f.params.ProcessLog.Warn("watching the rule files failed",
|
||||
"error", err.Error())
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// readAgain reads the rule files again, in place of the rules loaded, or
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
)
|
||||
|
||||
// The tests below run readAfterChanges in a synctest bubble, where time is
|
||||
// a clock of the test's own: time.Sleep moves it on at once, and
|
||||
// synctest.Wait returns once readAfterChanges waits again, so that every
|
||||
// reading due by then is done. The test sends the changes itself, as the
|
||||
// watch of a directory cannot run in a bubble.
|
||||
|
||||
func TestFileWrittenInTwoPartsTakenInOnlyWhole(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "50-app.rules")
|
||||
writeFile(t, path, "first path block ^/first\n")
|
||||
files := load(t, dir)
|
||||
changes := run(t, files)
|
||||
|
||||
file, err := os.Create(path) //nolint:gosec // a file the test wrote
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = file.Close()
|
||||
}()
|
||||
|
||||
// The first part ends in the middle of a ban rule's regex, which,
|
||||
// read then, would ban every request.
|
||||
write(t, file, "first path block ^/first\nprobe path ban ^/")
|
||||
|
||||
changes <- fsnotify.Event{Name: path, Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime - time.Nanosecond)
|
||||
synctest.Wait()
|
||||
wantMatched(t, files, "/anything")
|
||||
|
||||
// The second part starts the wait again.
|
||||
write(t, file, `\.env$`+"\n")
|
||||
|
||||
changes <- fsnotify.Event{Name: path, Op: fsnotify.Write}
|
||||
|
||||
time.Sleep(quietTime - time.Nanosecond)
|
||||
synctest.Wait()
|
||||
wantMatched(t, files, "/.env")
|
||||
|
||||
time.Sleep(time.Nanosecond)
|
||||
synctest.Wait()
|
||||
wantMatched(t, files, "/.env", "probe")
|
||||
wantMatched(t, files, "/anything")
|
||||
})
|
||||
}
|
||||
|
||||
func TestEditSavedBeforeTheWatchStartsTakenIn(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "50-app.rules")
|
||||
writeFile(t, path, "first path block ^/first\n")
|
||||
files := load(t, dir)
|
||||
|
||||
// Saved after Load read the files, and before the directory was
|
||||
// watched, so that no change is seen for it.
|
||||
writeFile(t, path, "first path block ^/edited\n")
|
||||
run(t, files)
|
||||
time.Sleep(quietTime)
|
||||
synctest.Wait()
|
||||
wantMatched(t, files, "/edited", "first")
|
||||
})
|
||||
}
|
||||
|
||||
// load loads the rules in dir.
|
||||
func load(t *testing.T, dir string) *Files {
|
||||
t.Helper()
|
||||
|
||||
files, err := Load(Params{
|
||||
Dir: dir, Enabled: true, ProcessLog: slog.New(slog.DiscardHandler),
|
||||
Alerts: alerts.New(alerts.Params{}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("load: %v", err)
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
// run runs files' readAfterChanges until the test ends, and returns the
|
||||
// channel that sends it changes.
|
||||
func run(t *testing.T, files *Files) chan<- fsnotify.Event {
|
||||
t.Helper()
|
||||
|
||||
changes := make(chan fsnotify.Event)
|
||||
ctx, stop := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
files.readAfterChanges(ctx, changes, nil)
|
||||
close(stopped)
|
||||
}()
|
||||
|
||||
t.Cleanup(func() {
|
||||
stop()
|
||||
<-stopped
|
||||
})
|
||||
|
||||
return changes
|
||||
}
|
||||
|
||||
// writeFile writes content to the file at path.
|
||||
func writeFile(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
|
||||
err := os.WriteFile(path, []byte(content), 0o600)
|
||||
if err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// write writes text to the end of file.
|
||||
func write(t *testing.T, file *os.File, text string) {
|
||||
t.Helper()
|
||||
|
||||
_, err := file.WriteString(text)
|
||||
if err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// wantMatched checks the ids of the rules that a GET request for path
|
||||
// matches, in order.
|
||||
func wantMatched(t *testing.T, files *Files, path string, want ...string) {
|
||||
t.Helper()
|
||||
|
||||
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
|
||||
"http://app.example"+path, nil)
|
||||
|
||||
matched := files.Match(r)
|
||||
|
||||
got := make([]string, 0, len(matched))
|
||||
for _, rule := range matched {
|
||||
got = append(got, rule.ID)
|
||||
}
|
||||
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("%s matched %v, want %v", path, got, want)
|
||||
}
|
||||
}
|
||||
@@ -660,9 +660,7 @@ func TestCoreRuleSetExclusionsFileThatCannotBeUsedStopsTheStartWhileTheCoreRuleS
|
||||
|
||||
status := run(t.Context(), map[string]string{
|
||||
listenAddr: localhost + ":0", stateDir: t.TempDir(), ruleFilesDir: t.TempDir(),
|
||||
"SWW_WAF_CORE_RULE_SET_MODE": string(
|
||||
config.CoreRuleSetModeOff,
|
||||
),
|
||||
"SWW_WAF_CORE_RULE_SET_MODE": config.CoreRuleSetModeOff,
|
||||
"SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE": path,
|
||||
}, out)
|
||||
if status != 1 {
|
||||
|
||||
+1
-1
@@ -192,7 +192,7 @@ func newLookupFile(
|
||||
lc fx.Lifecycle, cfg *config.WAF, processLog *slog.Logger,
|
||||
alertQueue *alerts.Queue,
|
||||
) (*lookup.File, error) {
|
||||
if cfg.LookupSource != config.LookupSourceFile {
|
||||
if cfg.LookupSource != "file" {
|
||||
return nil, nil //nolint:nilnil // no lookup database, and no error
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ func (abuseIPDB) check(
|
||||
"scored by AbuseIPDB at or over SWW_WAF_ABUSEIPDB_MIN_SCORE",
|
||||
)
|
||||
|
||||
if rq.h.config.DNSBLAbuseIPDBAction != config.ReputationActionDeny {
|
||||
if rq.h.config.DNSBLAbuseIPDBAction != deny {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -86,14 +86,13 @@ func (rq *request) countedBytes() int64 {
|
||||
response, request := rq.out.bytes, rq.requestBytes
|
||||
|
||||
switch rq.h.config.BytesCounted {
|
||||
case config.BytesCountedResponse:
|
||||
case "response":
|
||||
return response
|
||||
case config.BytesCountedRequest:
|
||||
case "request":
|
||||
return request
|
||||
case config.BytesCountedBoth:
|
||||
default: // both
|
||||
return response + request
|
||||
}
|
||||
|
||||
return response + request
|
||||
}
|
||||
|
||||
// banForLimit bans the client's netblock at now for a broken limit, the
|
||||
|
||||
@@ -63,8 +63,7 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
}
|
||||
|
||||
blocklisted := percentage{percent: whole}
|
||||
if rq.blocklisted &&
|
||||
cfg.BlocklistAction == config.ReputationActionLimit {
|
||||
if rq.blocklisted && cfg.BlocklistAction == "limit" {
|
||||
blocklisted = percentage{
|
||||
cfg.BlocklistLimitPercent,
|
||||
"SWW_WAF_BLOCKLIST_ACTION",
|
||||
@@ -73,7 +72,7 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
|
||||
dnsblAbuseIPDBListed := percentage{percent: whole}
|
||||
if (rq.dnsblListed || rq.abuseIPDBHit) &&
|
||||
cfg.DNSBLAbuseIPDBAction == config.ReputationActionLimit {
|
||||
cfg.DNSBLAbuseIPDBAction == "limit" {
|
||||
dnsblAbuseIPDBListed = percentage{
|
||||
cfg.DNSBLAbuseIPDBLimitPercent,
|
||||
"SWW_WAF_DNSBL_ABUSEIPDB_ACTION",
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
)
|
||||
|
||||
@@ -42,6 +41,5 @@ func (blocklists) check(
|
||||
// client, given listedBy, the blocklists that list it: it does when one lists
|
||||
// it and SWW_WAF_BLOCKLIST_ACTION is deny.
|
||||
func (rq *request) refusedByBlocklists(listedBy []string) bool {
|
||||
return len(listedBy) > 0 && rq.h.config.BlocklistAction ==
|
||||
config.ReputationActionDeny
|
||||
return len(listedBy) > 0 && rq.h.config.BlocklistAction == deny
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func (coreRuleSet) check(
|
||||
rq.line.CoreRuleSetScore = &result.Score
|
||||
|
||||
for _, id := range result.RuleIDs {
|
||||
rq.h.metrics.CoreRuleSetMatched(string(cfg.CoreRuleSetMode), id)
|
||||
rq.h.metrics.CoreRuleSetMatched(cfg.CoreRuleSetMode, id)
|
||||
}
|
||||
|
||||
threshold := cfg.CoreRuleSetScoreThreshold
|
||||
@@ -99,7 +99,7 @@ func (rq *request) alertCoreRuleSetMatch(result coreruleset.Result) {
|
||||
|
||||
switch {
|
||||
case rq.h.config.CoreRuleSetMode == config.CoreRuleSetModeDetect:
|
||||
detail["mode"] = string(config.CoreRuleSetModeDetect)
|
||||
detail["mode"] = config.CoreRuleSetModeDetect
|
||||
case rq.h.config.Observe:
|
||||
detail["mode"] = "observe"
|
||||
}
|
||||
|
||||
@@ -32,8 +32,7 @@ func (dnsbl) check(ctx context.Context, rq *request, _ time.Time) *verdict {
|
||||
rq.addTag(config.DNSBLTagPrefix + strings.ToLower(zone))
|
||||
}
|
||||
|
||||
if !rq.dnsblListed ||
|
||||
rq.h.config.DNSBLAbuseIPDBAction != config.ReputationActionDeny {
|
||||
if !rq.dnsblListed || rq.h.config.DNSBLAbuseIPDBAction != deny {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -49,8 +49,7 @@ func (rq *request) startLookUp(
|
||||
) <-chan lookupResult {
|
||||
result := make(chan lookupResult, 1)
|
||||
|
||||
if rq.h.config.LookupSource == config.LookupSourceOff ||
|
||||
!canBePlaced(rq.client) {
|
||||
if rq.h.config.LookupSource == "off" || !canBePlaced(rq.client) {
|
||||
result <- lookupResult{}
|
||||
|
||||
return result
|
||||
@@ -58,7 +57,7 @@ func (rq *request) startLookUp(
|
||||
|
||||
client := clientGroup(rq.h.config, rq.client)
|
||||
|
||||
if rq.h.config.LookupSource == config.LookupSourceFile {
|
||||
if rq.h.config.LookupSource == "file" {
|
||||
result <- lookupResult{
|
||||
lookedUp: true, answer: rq.h.lookupFile.LookUp(client),
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@ import (
|
||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||
)
|
||||
|
||||
// deny is the SWW_WAF_BLOCKLIST_ACTION and the SWW_WAF_DNSBL_ABUSEIPDB_ACTION that
|
||||
// refuses the requests of a client a source lists.
|
||||
const deny = "deny"
|
||||
|
||||
// noteListed notes each of sources, the URLs of the blocklists or the
|
||||
// DNSBL zones, their keys masked, that list the client, as noteHit does,
|
||||
// with reason.
|
||||
|
||||
@@ -421,7 +421,7 @@ func (rq *request) answerAtTheEnd() (geojs.Answer, bool) {
|
||||
return geojs.Answer{}, false
|
||||
}
|
||||
|
||||
if rq.h.config.LookupSource == config.LookupSourceFile {
|
||||
if rq.h.config.LookupSource == "file" {
|
||||
return rq.lookupAnswer, true
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user