Debian Codegraph @

ban/weights.go

raw
1 package ban
2
3 import (
4 "fmt"
5 "strconv"
6 "strings"
7 )
8
9 // Weights maps a matcher key to a strike weight for the abuse ban-feed (see ParseWeights, WeightFor).
10 type Weights map[string]int
11
12 // ParseWeights normalizes a list like ["42909:10","403:2","*:1"] into a Weights map. A key is an
13 // exact ntfy code, a family ("429*"), a bare HTTP status ("403" -> "403*"), or "*"; weights are ints
14 // >= 0 (0 = exempt). Malformed entries are rejected so misconfiguration fails at startup.
15 func ParseWeights(entries []string) (Weights, error) {
16 out := make(Weights, len(entries))
17 for _, entry := range entries {
18 key, weightStr, ok := strings.Cut(entry, ":")
19 if !ok {
20 return nil, fmt.Errorf("invalid ban-weight %q, want KEY:WEIGHT", entry)
21 }
22 weight, err := strconv.Atoi(strings.TrimSpace(weightStr))
23 if err != nil || weight < 0 {
24 return nil, fmt.Errorf("invalid ban-weight value in %q, want a non-negative integer", entry)
25 }
26 key = strings.TrimSpace(key)
27 if !validWeightKey(key) {
28 return nil, fmt.Errorf("invalid ban-weight key in %q, want %q, an ntfy code, an HTTP status, or a PREFIX*", entry, "*")
29 }
30 // A bare 3-digit HTTP status is shorthand for the whole family (e.g. "403" -> "403*").
31 if len(key) == 3 && isAllDigits(key) {
32 key += "*"
33 }
34 out[key] = weight
35 }
36 return out, nil
37 }
38
39 // WeightFor returns the strike weight for an ntfy error code, longest-match-wins (exact > family > "*").
40 // If nothing matches (no "*" catch-all) it returns the implied default 1, so a forgotten "*" still
41 // bans; use "*:0" to exempt everything not explicitly weighted.
42 func (w Weights) WeightFor(errorCode int) int {
43 code := strconv.Itoa(errorCode)
44 weight, bestLen, matched := 0, -1, false
45 for key, wt := range w {
46 matchLen := -1
47 switch {
48 case key == "*":
49 matchLen = 0
50 case strings.HasSuffix(key, "*"):
51 if prefix := strings.TrimSuffix(key, "*"); strings.HasPrefix(code, prefix) {
52 matchLen = len(prefix)
53 }
54 case key == code:
55 matchLen = len(code)
56 }
57 if matchLen > bestLen {
58 weight, bestLen, matched = wt, matchLen, true
59 }
60 }
61 if !matched {
62 return 1
63 }
64 return weight
65 }
66
67 // validWeightKey reports whether key is a legal matcher: "*", an all-digits code, or DIGITS*.
68 func validWeightKey(key string) bool {
69 if key == "*" {
70 return true
71 }
72 digits := strings.TrimSuffix(key, "*")
73 return digits != "" && isAllDigits(digits)
74 }
75
76 func isAllDigits(s string) bool {
77 for _, r := range s {
78 if r < '0' || r > '9' {
79 return false
80 }
81 }
82 return s != ""
83 }