From 99af37c01bbe789ffe60233d3882e5134b38ac58 Mon Sep 17 00:00:00 2001 From: sneak Date: Thu, 19 Nov 2026 16:31:29 +0000 Subject: [PATCH] config: give the fixed-value settings named types (closes #427) BytesCounted, LookupSource, BlocklistAction, DNSBLAbuseIPDBAction and CoreRuleSetMode become named string types declared in config, with constants for their values. Every comparison in waf and sww uses the constants, and the private duplicates fileSource and deny go. The two action settings share ReputationAction. The values and the strings written to logs, metrics and alerts are unchanged. Model: opus-5-5 --- internal/config/waf.go | 125 +++++++++++++++++++++++++++--------- internal/config/waf_test.go | 11 ++-- internal/sww/sww_test.go | 4 +- internal/sww/waf.go | 2 +- internal/waf/abuseipdb.go | 2 +- internal/waf/bans.go | 9 +-- internal/waf/biased.go | 5 +- internal/waf/blocklists.go | 4 +- internal/waf/coreruleset.go | 4 +- internal/waf/dnsbl.go | 3 +- internal/waf/lookup.go | 5 +- internal/waf/reputation.go | 4 -- internal/waf/request.go | 2 +- 13 files changed, 123 insertions(+), 57 deletions(-) diff --git a/internal/config/waf.go b/internal/config/waf.go index 0691438..50dc897 100644 --- a/internal/config/waf.go +++ b/internal/config/waf.go @@ -75,7 +75,7 @@ type WAF struct { BytesLimitPerMinute int64 BytesLimitPerHour int64 BytesLimitPerDay int64 - BytesCounted string + BytesCounted BytesCounted // 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 string + LookupSource LookupSource 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 string + BlocklistAction ReputationAction 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 string + DNSBLAbuseIPDBAction ReputationAction 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 string + CoreRuleSetMode CoreRuleSetMode CoreRuleSetParanoiaLevel int CoreRuleSetScoreThreshold int CoreRuleSetDisabledRules []int @@ -316,20 +316,66 @@ 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: 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 = off + CoreRuleSetModeOff CoreRuleSetMode = "off" // CoreRuleSetModeDetect logs and alerts a match, and refuses nothing. - CoreRuleSetModeDetect = "detect" + CoreRuleSetModeDetect CoreRuleSetMode = "detect" // CoreRuleSetModeBlock refuses a match with 403. - CoreRuleSetModeBlock = "block" + CoreRuleSetModeBlock CoreRuleSetMode = "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 @@ -558,10 +604,13 @@ 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", "both"), + BytesCounted: env.bytesCounted( + "SWW_WAF_BYTES_COUNTED", + BytesCountedBoth, + ), LookupSource: env.lookupSource( "SWW_WAF_LOOKUP_SOURCE", - "geojs", + LookupSourceGeoJS, ), LookupDBPath: env.value("SWW_WAF_LOOKUP_DB_PATH", ""), ASNAndCountryLookupTimeout: env.milliseconds( @@ -758,9 +807,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 != off)) + strconv.FormatBool(cfg.LookupSource != LookupSourceOff)) cfg.BlocklistAction, cfg.BlocklistLimitPercent = env.action( - "SWW_WAF_BLOCKLIST_ACTION", "deny") + "SWW_WAF_BLOCKLIST_ACTION", string(ReputationActionDeny)) cfg.DNSBLAbuseIPDBAction, cfg.DNSBLAbuseIPDBLimitPercent = env.action( "SWW_WAF_DNSBL_ABUSEIPDB_ACTION", "limit:25") @@ -858,9 +907,12 @@ 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, defaultValue string) string { - value := e.value(name, defaultValue) - if value != "response" && value != "request" && value != "both" { +func (e *environment) bytesCounted( + name string, defaultValue BytesCounted, +) BytesCounted { + value := BytesCounted(e.value(name, string(defaultValue))) + if value != BytesCountedResponse && value != BytesCountedRequest && + value != BytesCountedBoth { e.check(name, fmt.Errorf("%q %w", value, errNotBytesCounted)) } @@ -905,8 +957,10 @@ 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, defaultValue string) string { - mode := e.value(name, defaultValue) +func (e *environment) coreRuleSetMode( + name string, defaultValue CoreRuleSetMode, +) CoreRuleSetMode { + mode := CoreRuleSetMode(e.value(name, string(defaultValue))) if mode != CoreRuleSetModeOff && mode != CoreRuleSetModeDetect && mode != CoreRuleSetModeBlock { e.check(name, fmt.Errorf("%q %w", mode, errNotCoreRuleSetMode)) @@ -1056,20 +1110,24 @@ 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:, which it returns // as limit and the percentage. -func (e *environment) action(name, defaultValue string) (string, int64) { - value := e.value(name, defaultValue) - if value == "deny" || value == "log" { +func (e *environment) action( + name, defaultValue string, +) (ReputationAction, int64) { + value := ReputationAction(e.value(name, defaultValue)) + if value == ReputationActionDeny || value == ReputationActionLog { return value, 0 } - percentText, isLimit := strings.CutPrefix(value, "limit:") + percentText, isLimit := strings.CutPrefix( + string(value), string(ReputationActionLimit)+":", + ) percent, err := ParsePercent(percentText) if !isLimit || err != nil { e.check(name, fmt.Errorf("%q %w", value, errNotAction)) } - return "limit", percent + return ReputationActionLimit, percent } // zones reads the setting that is the list of DNSBL zones. It is empty by @@ -1120,9 +1178,12 @@ 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, defaultValue string) string { - source := e.value(name, defaultValue) - if source != "geojs" && source != fileSource && source != off { +func (e *environment) lookupSource( + name string, defaultValue LookupSource, +) LookupSource { + source := LookupSource(e.value(name, string(defaultValue))) + if source != LookupSourceGeoJS && source != LookupSourceFile && + source != LookupSourceOff { e.check(name, fmt.Errorf("%q %w", source, errNotLookupSource)) } @@ -1134,12 +1195,12 @@ func (e *environment) lookupSource(name, defaultValue string) string { // one source at a time. func (e *environment) checkLookupDBPath(cfg *WAF) { switch { - case cfg.LookupSource == fileSource && cfg.LookupDBPath == "": + case cfg.LookupSource == LookupSourceFile && 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 != fileSource && cfg.LookupDBPath != "": + case cfg.LookupSource != LookupSourceFile && cfg.LookupDBPath != "": e.check("SWW_WAF_LOOKUP_DB_PATH", fmt.Errorf( "is set while SWW_WAF_LOOKUP_SOURCE is %s; %w", cfg.LookupSource, @@ -1164,7 +1225,7 @@ func (e *environment) checkCountriesAndLookups(cfg *WAF) { } } - if cfg.LookupSource != off { + if cfg.LookupSource != LookupSourceOff { return } diff --git a/internal/config/waf_test.go b/internal/config/waf_test.go index 2f98d7f..8f4b862 100644 --- a/internal/config/waf_test.go +++ b/internal/config/waf_test.go @@ -614,7 +614,7 @@ func TestCoreRuleSetSettings(t *testing.T) { }, { environment{ - coreRuleSetMode: config.CoreRuleSetModeDetect, + coreRuleSetMode: string(config.CoreRuleSetModeDetect), coreRuleSetParanoiaLevel: "4", coreRuleSetScoreThreshold: "10", coreRuleSetDisabledRules: "942100, 920350", @@ -2033,8 +2033,9 @@ func TestReputationSettingsAsSet(t *testing.T) { } for _, tc := range []struct { - value, action string - percent int64 + value string + action config.ReputationAction + percent int64 }{ {actionDeny, actionDeny, 0}, {actionLog, actionLog, 0}, @@ -2167,7 +2168,7 @@ func TestDNSBLSettingsAsSet(t *testing.T) { // want are the zones, resolver, action and percent config.WAF gives. want []string wantResolver string - wantAction string + wantAction config.ReputationAction wantPercent int64 }{ { @@ -3049,7 +3050,7 @@ func TestLogsEachSettingWithItsValue(t *testing.T) { logLevel: "info", ruleFilesDir: "/etc/sww/rules.d", ruleFilesEnabled: "true", - coreRuleSetMode: config.CoreRuleSetModeBlock, + coreRuleSetMode: string(config.CoreRuleSetModeBlock), coreRuleSetParanoiaLevel: "1", coreRuleSetScoreThreshold: "5", coreRuleSetDisabledRules: defaultCoreRuleSetDisabledRules, diff --git a/internal/sww/sww_test.go b/internal/sww/sww_test.go index dbe7571..5e1a4ae 100644 --- a/internal/sww/sww_test.go +++ b/internal/sww/sww_test.go @@ -660,7 +660,9 @@ func TestCoreRuleSetExclusionsFileThatCannotBeUsedStopsTheStartWhileTheCoreRuleS status := run(t.Context(), map[string]string{ listenAddr: localhost + ":0", stateDir: t.TempDir(), ruleFilesDir: t.TempDir(), - "SWW_WAF_CORE_RULE_SET_MODE": config.CoreRuleSetModeOff, + "SWW_WAF_CORE_RULE_SET_MODE": string( + config.CoreRuleSetModeOff, + ), "SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE": path, }, out) if status != 1 { diff --git a/internal/sww/waf.go b/internal/sww/waf.go index 72f8685..f492026 100644 --- a/internal/sww/waf.go +++ b/internal/sww/waf.go @@ -192,7 +192,7 @@ func newLookupFile( lc fx.Lifecycle, cfg *config.WAF, processLog *slog.Logger, alertQueue *alerts.Queue, ) (*lookup.File, error) { - if cfg.LookupSource != "file" { + if cfg.LookupSource != config.LookupSourceFile { return nil, nil //nolint:nilnil // no lookup database, and no error } diff --git a/internal/waf/abuseipdb.go b/internal/waf/abuseipdb.go index 0802ee2..fe1d75a 100644 --- a/internal/waf/abuseipdb.go +++ b/internal/waf/abuseipdb.go @@ -54,7 +54,7 @@ func (abuseIPDB) check( "scored by AbuseIPDB at or over SWW_WAF_ABUSEIPDB_MIN_SCORE", ) - if rq.h.config.DNSBLAbuseIPDBAction != deny { + if rq.h.config.DNSBLAbuseIPDBAction != config.ReputationActionDeny { return nil } diff --git a/internal/waf/bans.go b/internal/waf/bans.go index bf19d96..f6ca9a8 100644 --- a/internal/waf/bans.go +++ b/internal/waf/bans.go @@ -86,13 +86,14 @@ func (rq *request) countedBytes() int64 { response, request := rq.out.bytes, rq.requestBytes switch rq.h.config.BytesCounted { - case "response": + case config.BytesCountedResponse: return response - case "request": + case config.BytesCountedRequest: return request - default: // both - return response + request + case config.BytesCountedBoth: } + + return response + request } // banForLimit bans the client's netblock at now for a broken limit, the diff --git a/internal/waf/biased.go b/internal/waf/biased.go index 3e729df..7f5739d 100644 --- a/internal/waf/biased.go +++ b/internal/waf/biased.go @@ -63,7 +63,8 @@ func (rq *request) limitPercentages() (percentage, percentage) { } blocklisted := percentage{percent: whole} - if rq.blocklisted && cfg.BlocklistAction == "limit" { + if rq.blocklisted && + cfg.BlocklistAction == config.ReputationActionLimit { blocklisted = percentage{ cfg.BlocklistLimitPercent, "SWW_WAF_BLOCKLIST_ACTION", @@ -72,7 +73,7 @@ func (rq *request) limitPercentages() (percentage, percentage) { dnsblAbuseIPDBListed := percentage{percent: whole} if (rq.dnsblListed || rq.abuseIPDBHit) && - cfg.DNSBLAbuseIPDBAction == "limit" { + cfg.DNSBLAbuseIPDBAction == config.ReputationActionLimit { dnsblAbuseIPDBListed = percentage{ cfg.DNSBLAbuseIPDBLimitPercent, "SWW_WAF_DNSBL_ABUSEIPDB_ACTION", diff --git a/internal/waf/blocklists.go b/internal/waf/blocklists.go index 9598cd9..7879634 100644 --- a/internal/waf/blocklists.go +++ b/internal/waf/blocklists.go @@ -7,6 +7,7 @@ import ( "context" "time" + "sneak.berlin/go/smallwebwaf/internal/config" "sneak.berlin/go/smallwebwaf/internal/requestlog" ) @@ -41,5 +42,6 @@ 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 == deny + return len(listedBy) > 0 && rq.h.config.BlocklistAction == + config.ReputationActionDeny } diff --git a/internal/waf/coreruleset.go b/internal/waf/coreruleset.go index 049bc6c..5c401cf 100644 --- a/internal/waf/coreruleset.go +++ b/internal/waf/coreruleset.go @@ -47,7 +47,7 @@ func (coreRuleSet) check( rq.line.CoreRuleSetScore = &result.Score for _, id := range result.RuleIDs { - rq.h.metrics.CoreRuleSetMatched(cfg.CoreRuleSetMode, id) + rq.h.metrics.CoreRuleSetMatched(string(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"] = config.CoreRuleSetModeDetect + detail["mode"] = string(config.CoreRuleSetModeDetect) case rq.h.config.Observe: detail["mode"] = "observe" } diff --git a/internal/waf/dnsbl.go b/internal/waf/dnsbl.go index b0bb4b4..51572f7 100644 --- a/internal/waf/dnsbl.go +++ b/internal/waf/dnsbl.go @@ -32,7 +32,8 @@ 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 != deny { + if !rq.dnsblListed || + rq.h.config.DNSBLAbuseIPDBAction != config.ReputationActionDeny { return nil } diff --git a/internal/waf/lookup.go b/internal/waf/lookup.go index a6fc5e4..9451299 100644 --- a/internal/waf/lookup.go +++ b/internal/waf/lookup.go @@ -49,7 +49,8 @@ func (rq *request) startLookUp( ) <-chan lookupResult { result := make(chan lookupResult, 1) - if rq.h.config.LookupSource == "off" || !canBePlaced(rq.client) { + if rq.h.config.LookupSource == config.LookupSourceOff || + !canBePlaced(rq.client) { result <- lookupResult{} return result @@ -57,7 +58,7 @@ func (rq *request) startLookUp( client := clientGroup(rq.h.config, rq.client) - if rq.h.config.LookupSource == "file" { + if rq.h.config.LookupSource == config.LookupSourceFile { result <- lookupResult{ lookedUp: true, answer: rq.h.lookupFile.LookUp(client), } diff --git a/internal/waf/reputation.go b/internal/waf/reputation.go index b760666..ddee4b7 100644 --- a/internal/waf/reputation.go +++ b/internal/waf/reputation.go @@ -7,10 +7,6 @@ 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. diff --git a/internal/waf/request.go b/internal/waf/request.go index 9c6dbc8..bc900aa 100644 --- a/internal/waf/request.go +++ b/internal/waf/request.go @@ -421,7 +421,7 @@ func (rq *request) answerAtTheEnd() (geojs.Answer, bool) { return geojs.Answer{}, false } - if rq.h.config.LookupSource == "file" { + if rq.h.config.LookupSource == config.LookupSourceFile { return rq.lookupAnswer, true }