Update to Anubis v1.28.2 (#1)

This upgrades the Masyunis fork from Anubis v1.25.0 to the latest stable release, **v1.28.2** (“Wuk Lamat Echo 2”), while keeping the fork’s custom styling and removals.

## Approach

The Gitea repo is a tree snapshot of v1.25.0, not a git-level fork of [TecharoHQ/anubis](https://github.com/TecharoHQ/anubis). The histories share no commits, so a merge or rebase onto the upstream tag is not usable.

The first commit on this branch replaces the tree with a snapshot of the **v1.28.2** tag (`git rm -r` plus `git checkout v1.28.2 -- .`; the import tree is identical to the tag). A short patch series on top restores the Masyunis customizations.

## Customizations kept

- Masyunya mascots (`web/static/img/{happy,pensive,reject}.webp`), hashes match current `master`.
- `web/static/img/ATTRIBUTIONS.txt` stays deleted.
- Challenge footer: drop the `made_with` (Canada / maple-leaf) line and the CELPHASE mascot credit; keep “Protected by Anubis from Techaro”. The generated `web/index_templ.go` matches `go generate ./web`.
- Short README (the old `anubisc` typo is fixed).
- Version stamped `v1.28.2/masyunis` via Makefile ldflags. `anubis.go` `init()` does not overwrite a link-time version; `go run` / `go test` still report `devel` on purpose.
- Upstream `.github`, `.devcontainer`, `.husky`, and `.vscode` stay deleted.
- `"uk"` is removed from `lib/localization/locales/manifest.json` **on purpose**, because of Alpine locale problems. `uk.json` and its test entry stay; the served manifest lists 27 languages.
- `package.json` `prepare` no longer runs `husky` (the hooks directory is gone). The rest of the script is unchanged. `husky` remains in devDependencies, as upstream left it.

## Deploy notes

- **Cookie rename (v1.27):** with the default `DYNAMIC_COOKIE_SUFFIX=true`, cookie names become e.g. `techaro.lol-anubis-auth-<hash>`. Existing clients get a **one-time re-challenge**. That is expected, not a loop.
- **Docker / ko / yeet builds** skip the Makefile ldflags, so the displayed version is `<git-version>/masyunis`. It is `v1.28.2/masyunis` only when built from a `v1.28.2` tag (or via `make build` / `make prebaked-build`).
- Go 1.27.3 is required (upstream bump in v1.28.2). Thoth (`THOTH_URL` / `THOTH_TOKEN`) was removed upstream; those settings now warn and do nothing. New WASM challenge methods stay disabled unless opted in.

## Verification

- `make build` succeeds. `./var/anubis --version` prints `Anubis v1.28.2/masyunis`.
- `SKIP_INTEGRATION=1 go test ./...` passes (unit tests; integration package is skipped).
- Local challenge/reject pages (en and ru) show Masyunya, version `v1.28.2/masyunis`, and no Canada / CELPHASE / mascot-credit text. Screenshots:

![Challenge page (en)](https://git.unvr.site/attachments/36112ff0-5155-495c-8bd2-59606ee3bd64)
![Reject page (en)](https://git.unvr.site/attachments/2cad0256-1b0e-4f71-8d06-d1a447fd5263)

- Upstream Playwright tests (`make test` without `SKIP_INTEGRATION`) fail on this box because the browser download fails. A clean v1.28.2 tree fails the same three Playwright tests here, so this is not a fork regression.
- `npm audit` reports **4** findings in upstream’s lockfile (2 moderate, 2 high: `brace-expansion`, `fast-uri`, `lodash.trim`, `source-map-js`). Left alone.

Please review and merge when ready. I will not merge this myself.

Reviewed-on: #1
Co-authored-by: Lead <3+lead_bot@noreply.git.unvr.site>
This commit was merged in pull request #1.
This commit is contained in:
sol_bot Bot authored and matiashik committed 2026-11-28 12:10:27 +00:00
1 parent eb3e46d8d0
commit caf4d72880
529 files changed
+33015 -6659

No files matched your search

+82 -73
View File
@@ -4,30 +4,29 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"net/url"
"regexp"
"strings"
"time"
"github.com/TecharoHQ/anubis/data"
"k8s.io/apimachinery/pkg/util/yaml"
)
var (
ErrNoBotRulesDefined = errors.New("config: must define at least one (1) bot rule")
ErrBotMustHaveName = errors.New("config.Bot: must set name")
ErrBotMustHaveUserAgentOrPath = errors.New("config.Bot: must set either user_agent_regex, path_regex, headers_regex, or remote_addresses")
ErrBotMustHaveUserAgentOrPath = errors.New("config.Bot: must set one of user_agent_regex, path_regex, headers_regex, remote_addresses, remote_addresses_url, expression, asns, or geoip")
ErrBotMustHaveUserAgentOrPathNotBoth = errors.New("config.Bot: must set either user_agent_regex, path_regex, and not both")
ErrBotMustHaveRemoteAddrOrURLNotBoth = errors.New("config.Bot: must set either remote_addresses or remote_addresses_url, and not both")
ErrInvalidRemoteAddressesURL = errors.New("config.Bot: invalid remote_addresses_url")
ErrUnknownAction = errors.New("config.Bot: unknown action")
ErrInvalidUserAgentRegex = errors.New("config.Bot: invalid user agent regex")
ErrInvalidPathRegex = errors.New("config.Bot: invalid path regex")
ErrInvalidHeadersRegex = errors.New("config.Bot: invalid headers regex")
ErrInvalidCIDR = errors.New("config.Bot: invalid CIDR")
ErrRegexEndsWithNewline = errors.New("config.Bot: regular expression ends with newline (try >- instead of > in yaml)")
ErrInvalidImportStatement = errors.New("config.ImportStatement: invalid source file")
ErrCantSetBotAndImportValuesAtOnce = errors.New("config.BotOrImport: can't set bot rules and import values at the same time")
ErrMustSetBotOrImportRules = errors.New("config.BotOrImport: rule definition is invalid, you must set either bot rules or an import statement, not both")
ErrStatusCodeNotValid = errors.New("config.StatusCode: status code not valid, must be between 100 and 599")
@@ -63,13 +62,14 @@ type BotConfig struct {
Challenge *ChallengeRules `json:"challenge,omitempty" yaml:"challenge,omitempty"`
Weight *Weight `json:"weight,omitempty" yaml:"weight,omitempty"`
// Thoth features
// IP metadata features, backed by the top-level geoip block
GeoIP *GeoIP `json:"geoip,omitempty"`
ASNs *ASNs `json:"asns,omitempty"`
Name string `json:"name" yaml:"name"`
Action Rule `json:"action" yaml:"action"`
RemoteAddr []string `json:"remote_addresses,omitempty" yaml:"remote_addresses,omitempty"`
Name string `json:"name" yaml:"name"`
Action Rule `json:"action" yaml:"action"`
RemoteAddr []string `json:"remote_addresses,omitempty" yaml:"remote_addresses,omitempty"`
RemoteAddressesURL *string `json:"remote_addresses_url,omitempty" yaml:"remote_addresses_url,omitempty"`
}
func (b BotConfig) Zero() bool {
@@ -80,6 +80,7 @@ func (b BotConfig) Zero() bool {
len(b.HeadersRegex) != 0,
b.Action != "",
len(b.RemoteAddr) != 0,
b.RemoteAddressesURL != nil,
b.Challenge != nil,
b.GeoIP != nil,
b.ASNs != nil,
@@ -102,6 +103,7 @@ func (b *BotConfig) Valid() error {
allFieldsEmpty := b.UserAgentRegex == nil &&
b.PathRegex == nil &&
len(b.RemoteAddr) == 0 &&
b.RemoteAddressesURL == nil &&
len(b.HeadersRegex) == 0 &&
b.ASNs == nil &&
b.GeoIP == nil
@@ -114,6 +116,10 @@ func (b *BotConfig) Valid() error {
errs = append(errs, ErrBotMustHaveUserAgentOrPathNotBoth)
}
if len(b.RemoteAddr) > 0 && b.RemoteAddressesURL != nil {
errs = append(errs, ErrBotMustHaveRemoteAddrOrURLNotBoth)
}
if b.UserAgentRegex != nil {
if strings.HasSuffix(*b.UserAgentRegex, "\n") {
errs = append(errs, fmt.Errorf("%w: user agent regex: %q", ErrRegexEndsWithNewline, *b.UserAgentRegex))
@@ -158,6 +164,12 @@ func (b *BotConfig) Valid() error {
}
}
if b.RemoteAddressesURL != nil {
if err := validateRemoteAddressesURL(*b.RemoteAddressesURL); err != nil {
errs = append(errs, err)
}
}
if b.Expression != nil {
if err := b.Expression.Valid(); err != nil {
errs = append(errs, err)
@@ -188,16 +200,29 @@ func (b *BotConfig) Valid() error {
return nil
}
func validateRemoteAddressesURL(raw string) error {
raw = strings.TrimSpace(raw)
u, err := url.Parse(raw)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return fmt.Errorf("%w: %q", ErrInvalidRemoteAddressesURL, raw)
}
return nil
}
type ChallengeRules struct {
Algorithm string `json:"algorithm,omitempty" yaml:"algorithm,omitempty"`
Difficulty int `json:"difficulty,omitempty" yaml:"difficulty,omitempty"`
ReportAs int `json:"report_as,omitempty" yaml:"report_as,omitempty"`
Algorithm string `json:"algorithm,omitempty" yaml:"algorithm,omitempty"`
Difficulty int `json:"difficulty,omitempty" yaml:"difficulty,omitempty"`
ReportAs int `json:"report_as,omitempty" yaml:"report_as,omitempty"`
Extensions []string `json:"extensions,omitempty" yaml:"extensions,omitempty"`
}
var (
ErrChallengeDifficultyTooLow = errors.New("config.ChallengeRules: difficulty is too low (must be >= 0)")
ErrChallengeDifficultyTooHigh = errors.New("config.ChallengeRules: difficulty is too high (must be <= 64)")
ErrChallengeMustHaveAlgorithm = errors.New("config.ChallengeRules: must have algorithm name set")
ErrChallengeExtensionUnknown = errors.New("config.ChallengeRules: unknown challenge extension")
ErrChallengeExtensionEmpty = errors.New("config.ChallengeRules: extension name must not be empty")
ErrChallengeExtensionRepeated = errors.New("config.ChallengeRules: extension name was repeated")
)
func (cr ChallengeRules) Valid() error {
@@ -215,6 +240,20 @@ func (cr ChallengeRules) Valid() error {
errs = append(errs, fmt.Errorf("%w, got: %d", ErrChallengeDifficultyTooHigh, cr.Difficulty))
}
if len(cr.Extensions) != 0 {
seen := make(map[string]struct{}, len(cr.Extensions))
for _, name := range cr.Extensions {
_, repeated := seen[name]
switch {
case name == "":
errs = append(errs, ErrChallengeExtensionEmpty)
case repeated:
errs = append(errs, fmt.Errorf("%w: %q", ErrChallengeExtensionRepeated, name))
}
seen[name] = struct{}{}
}
}
if len(errs) != 0 {
return fmt.Errorf("config: challenge rules entry is not valid:\n%w", errors.Join(errs...))
}
@@ -222,64 +261,6 @@ func (cr ChallengeRules) Valid() error {
return nil
}
type ImportStatement struct {
Import string `json:"import"`
Bots []BotConfig
}
func (is *ImportStatement) open() (fs.File, error) {
if strings.HasPrefix(is.Import, "(data)/") {
fname := strings.TrimPrefix(is.Import, "(data)/")
fin, err := data.BotPolicies.Open(fname)
return fin, err
}
return os.Open(is.Import)
}
func (is *ImportStatement) load() error {
fin, err := is.open()
if err != nil {
return fmt.Errorf("%w: %s: %w", ErrInvalidImportStatement, is.Import, err)
}
defer fin.Close()
var imported []BotOrImport
var result []BotConfig
if err := yaml.NewYAMLToJSONDecoder(fin).Decode(&imported); err != nil {
return fmt.Errorf("can't parse %s: %w", is.Import, err)
}
var errs []error
for _, b := range imported {
if err := b.Valid(); err != nil {
errs = append(errs, err)
}
if b.ImportStatement != nil {
result = append(result, b.ImportStatement.Bots...)
}
if b.BotConfig != nil {
result = append(result, *b.BotConfig)
}
}
if len(errs) != 0 {
return fmt.Errorf("config %s is not valid:\n%w", is.Import, errors.Join(errs...))
}
is.Bots = result
return nil
}
func (is *ImportStatement) Valid() error {
return is.load()
}
type BotOrImport struct {
*BotConfig `json:",inline"`
*ImportStatement `json:",inline"`
@@ -325,7 +306,7 @@ func (sc StatusCodes) Valid() error {
}
type fileConfig struct {
OpenGraph openGraphFileConfig `json:"openGraph,omitempty"`
OpenGraph openGraphFileConfig `json:"openGraph"`
Impressum *Impressum `json:"impressum,omitempty"`
Store *Store `json:"store"`
Bots []BotOrImport `json:"bots"`
@@ -334,6 +315,9 @@ type fileConfig struct {
DNSBL bool `json:"dnsbl"`
DNSTTL DnsTTL `json:"dns_ttl"`
Logging *Logging `json:"logging"`
Metrics *Metrics `json:"metrics,omitempty"`
Honeypot *Honeypot `json:"honeypot"`
GeoIP *GeoIPDatabases `json:"geoip,omitempty"`
}
func (c *fileConfig) Valid() error {
@@ -375,6 +359,24 @@ func (c *fileConfig) Valid() error {
}
}
if c.Metrics != nil {
if err := c.Metrics.Valid(); err != nil {
errs = append(errs, err)
}
}
if c.Honeypot != nil {
if err := c.Honeypot.Valid(); err != nil {
errs = append(errs, err)
}
}
if c.GeoIP != nil {
if err := c.GeoIP.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return fmt.Errorf("config is not valid:\n%w", errors.Join(errs...))
}
@@ -395,7 +397,8 @@ func Load(fin io.Reader, fname string) (*Config, error) {
Store: &Store{
Backend: "memory",
},
Logging: (Logging{}).Default(),
Logging: (Logging{}).Default(),
Honeypot: new((Honeypot{}).Default()),
}
if err := yaml.NewYAMLToJSONDecoder(fin).Decode(&c); err != nil {
@@ -417,6 +420,9 @@ func Load(fin io.Reader, fname string) (*Config, error) {
StatusCodes: c.StatusCodes,
Store: c.Store,
Logging: c.Logging,
Metrics: c.Metrics,
Honeypot: c.Honeypot,
GeoIP: c.GeoIP,
}
if c.OpenGraph.TimeToLive != "" {
@@ -434,7 +440,7 @@ func Load(fin io.Reader, fname string) (*Config, error) {
continue
}
result.Bots = append(result.Bots, boi.ImportStatement.Bots...)
result.Bots = append(result.Bots, boi.Bots...)
}
if boi.BotConfig != nil {
@@ -508,6 +514,9 @@ type Config struct {
Logging *Logging
DNSBL bool
DNSTTL DnsTTL
Metrics *Metrics
Honeypot *Honeypot
GeoIP *GeoIPDatabases
}
func (c Config) Valid() error {
+65 -64
View File
@@ -2,12 +2,10 @@ package config_test
import (
"errors"
"io/fs"
"os"
"path/filepath"
"testing"
"github.com/TecharoHQ/anubis/data"
. "github.com/TecharoHQ/anubis/lib/config"
)
@@ -166,6 +164,62 @@ func TestBotValid(t *testing.T) {
},
err: nil,
},
{
name: "only filter by remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p("https://openai.com/searchbot.json"),
},
err: nil,
},
{
name: "filter by user agent and remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
UserAgentRegex: p("OAI-SearchBot"),
RemoteAddressesURL: p("https://openai.com/searchbot.json"),
},
err: nil,
},
{
name: "invalid remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p("not a url"),
},
err: ErrInvalidRemoteAddressesURL,
},
{
name: "remote addresses url ftp scheme",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p("ftp://example.com/bots.json"),
},
err: ErrInvalidRemoteAddressesURL,
},
{
name: "remote addresses url empty",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p(""),
},
err: ErrInvalidRemoteAddressesURL,
},
{
name: "remote addresses and remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddr: []string{"0.0.0.0/0"},
RemoteAddressesURL: p("https://openai.com/searchbot.json"),
},
err: ErrBotMustHaveRemoteAddrOrURLNotBoth,
},
{
name: "weight rule without weight",
bot: BotConfig{
@@ -188,7 +242,6 @@ func TestBotValid(t *testing.T) {
}
for _, cs := range tests {
cs := cs
t.Run(cs.name, func(t *testing.T) {
err := cs.bot.Valid()
if err == nil && cs.err == nil {
@@ -216,13 +269,12 @@ func TestConfigValidKnownGood(t *testing.T) {
}
for _, st := range finfos {
st := st
t.Run(st.Name(), func(t *testing.T) {
fin, err := os.Open(filepath.Join("testdata", "good", st.Name()))
if err != nil {
t.Fatal(err)
}
defer fin.Close()
defer fin.Close() //nolint:errcheck
c, err := Load(fin, st.Name())
if err != nil {
@@ -240,62 +292,6 @@ func TestConfigValidKnownGood(t *testing.T) {
}
}
func TestImportStatement(t *testing.T) {
type testCase struct {
err error
name string
importPath string
}
var tests []testCase
for _, folderName := range []string{
"apps",
"bots",
"common",
"crawlers",
"meta",
} {
if err := fs.WalkDir(data.BotPolicies, folderName, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if d.Name() == "README.md" {
return nil
}
tests = append(tests, testCase{
name: "(data)/" + path,
importPath: "(data)/" + path,
err: nil,
})
return nil
}); err != nil {
t.Fatal(err)
}
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
is := &ImportStatement{
Import: tt.importPath,
}
if err := is.Valid(); err != nil {
t.Errorf("validation error: %v", err)
}
if len(is.Bots) == 0 {
t.Error("wanted bot definitions, but got none")
}
})
}
}
func TestConfigValidBad(t *testing.T) {
finfos, err := os.ReadDir("testdata/bad")
if err != nil {
@@ -303,17 +299,16 @@ func TestConfigValidBad(t *testing.T) {
}
for _, st := range finfos {
st := st
t.Run(st.Name(), func(t *testing.T) {
fin, err := os.Open(filepath.Join("testdata", "bad", st.Name()))
if err != nil {
t.Fatal(err)
}
defer fin.Close()
defer fin.Close() //nolint:errcheck
_, err = Load(fin, filepath.Join("testdata", "bad", st.Name()))
if err == nil {
t.Fatal("validation should have failed but didn't somehow")
t.Fatalf("validation should have failed but didn't somehow: %v", err)
} else {
t.Log(err)
}
@@ -357,6 +352,12 @@ func TestBotConfigZero(t *testing.T) {
t.Error("config.BotConfig with remote addresses is zero value")
}
var d BotConfig
d.RemoteAddressesURL = p("https://openai.com/searchbot.json")
if d.Zero() {
t.Error("config.BotConfig with remote_addresses_url is zero value")
}
b.Challenge = &ChallengeRules{
Difficulty: 4,
Algorithm: DefaultAlgorithm,
+218
View File
@@ -0,0 +1,218 @@
package config
import (
"errors"
"fmt"
"net/url"
"os"
"time"
)
var (
ErrGeoIPNoDatabases = errors.New("config.GeoIPDatabases: must define at least one of asn or country")
ErrGeoIPNoPath = errors.New("config.GeoIPDatabase: must define path")
ErrGeoIPCountryFieldOnASN = errors.New("config.GeoIPDatabase: country_field can only be set on the country database")
ErrGeoIPInvalidCountryField = errors.New("config.GeoIPDatabase: invalid country_field")
ErrGeoIPEmptyEditionID = errors.New("config.GeoIPDatabase: edition_id must not be empty when set")
ErrGeoIPNoAccountID = errors.New("config.GeoIPAutoUpdate: must define account_id")
ErrGeoIPNoLicenseKeyEnv = errors.New("config.GeoIPAutoUpdate: must define license_key_env")
ErrGeoIPLicenseKeyEnvNotSet = errors.New("config.GeoIPAutoUpdate: environment variable named by license_key_env is not set")
ErrGeoIPInvalidInterval = errors.New("config.GeoIPAutoUpdate: invalid interval")
ErrGeoIPIntervalTooShort = errors.New("config.GeoIPAutoUpdate: interval is too short")
ErrGeoIPInvalidEndpoint = errors.New("config.GeoIPAutoUpdate: invalid endpoint")
)
const (
DefaultGeoIPASNEditionID = "GeoLite2-ASN"
DefaultGeoIPCountryEditionID = "GeoLite2-Country"
DefaultGeoIPUpdateInterval = 24 * time.Hour
MinimumGeoIPUpdateInterval = time.Hour
DefaultGeoIPCountryField = CountryFieldCountry
)
// CountryField selects which country record in a MaxMind country database is
// used for geoip rules.
type CountryField string
const (
// CountryFieldCountry is the country where MaxMind believes the IP address is located.
CountryFieldCountry CountryField = "country"
// CountryFieldRegisteredCountry is the country the IP address is registered to.
CountryFieldRegisteredCountry CountryField = "registered_country"
)
func (cf CountryField) Valid() error {
switch cf {
case CountryFieldCountry, CountryFieldRegisteredCountry:
return nil
default:
return fmt.Errorf("%w: %q, must be one of %q or %q", ErrGeoIPInvalidCountryField, string(cf), CountryFieldCountry, CountryFieldRegisteredCountry)
}
}
// GeoIPDatabases configures the MaxMind databases used for asns and geoip
// rules and ASN logging.
type GeoIPDatabases struct {
ASN *GeoIPDatabase `json:"asn,omitempty" yaml:"asn,omitempty"`
Country *GeoIPDatabase `json:"country,omitempty" yaml:"country,omitempty"`
AutoUpdate *GeoIPAutoUpdate `json:"auto_update,omitempty" yaml:"auto_update,omitempty"`
}
func (g *GeoIPDatabases) Valid() error {
var errs []error
if g.ASN == nil && g.Country == nil {
errs = append(errs, ErrGeoIPNoDatabases)
}
if g.ASN != nil {
if err := g.ASN.Valid(); err != nil {
errs = append(errs, fmt.Errorf("asn: %w", err))
}
if g.ASN.CountryField != nil {
errs = append(errs, fmt.Errorf("asn: %w", ErrGeoIPCountryFieldOnASN))
}
}
if g.Country != nil {
if err := g.Country.Valid(); err != nil {
errs = append(errs, fmt.Errorf("country: %w", err))
}
}
if g.AutoUpdate != nil {
if err := g.AutoUpdate.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return fmt.Errorf("config.GeoIPDatabases: invalid geoip settings:\n%w", errors.Join(errs...))
}
return nil
}
// ASNEditionID returns the MaxMind edition ID for the ASN database.
func (g *GeoIPDatabases) ASNEditionID() string {
return g.ASN.editionID(DefaultGeoIPASNEditionID)
}
// CountryEditionID returns the MaxMind edition ID for the country database.
func (g *GeoIPDatabases) CountryEditionID() string {
return g.Country.editionID(DefaultGeoIPCountryEditionID)
}
// GeoIPDatabase is a single MaxMind database on disk.
type GeoIPDatabase struct {
Path string `json:"path" yaml:"path"`
EditionID *string `json:"edition_id,omitempty" yaml:"edition_id,omitempty"`
CountryField *CountryField `json:"country_field,omitempty" yaml:"country_field,omitempty"`
}
func (g *GeoIPDatabase) Valid() error {
var errs []error
if g.Path == "" {
errs = append(errs, ErrGeoIPNoPath)
}
if g.EditionID != nil && *g.EditionID == "" {
errs = append(errs, ErrGeoIPEmptyEditionID)
}
if g.CountryField != nil {
if err := g.CountryField.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Join(errs...)
}
return nil
}
// GetCountryField returns the configured country field or the default.
func (g *GeoIPDatabase) GetCountryField() CountryField {
if g == nil || g.CountryField == nil {
return DefaultGeoIPCountryField
}
return *g.CountryField
}
func (g *GeoIPDatabase) editionID(def string) string {
if g == nil || g.EditionID == nil {
return def
}
return *g.EditionID
}
// GeoIPAutoUpdate configures automatic database updates from MaxMind.
type GeoIPAutoUpdate struct {
AccountID int `json:"account_id" yaml:"account_id"`
LicenseKeyEnv string `json:"license_key_env" yaml:"license_key_env"`
Interval *string `json:"interval,omitempty" yaml:"interval,omitempty"`
Endpoint *string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"`
}
func (g *GeoIPAutoUpdate) Valid() error {
var errs []error
if g.AccountID <= 0 {
errs = append(errs, ErrGeoIPNoAccountID)
}
switch {
case g.LicenseKeyEnv == "":
errs = append(errs, ErrGeoIPNoLicenseKeyEnv)
case os.Getenv(g.LicenseKeyEnv) == "":
errs = append(errs, fmt.Errorf("%w: %s", ErrGeoIPLicenseKeyEnvNotSet, g.LicenseKeyEnv))
}
if g.Interval != nil {
d, err := time.ParseDuration(*g.Interval)
switch {
case err != nil:
errs = append(errs, fmt.Errorf("%w: %w", ErrGeoIPInvalidInterval, err))
case d < MinimumGeoIPUpdateInterval:
errs = append(errs, fmt.Errorf("%w: %s is less than %s", ErrGeoIPIntervalTooShort, d, MinimumGeoIPUpdateInterval))
}
}
if g.Endpoint != nil {
u, err := url.Parse(*g.Endpoint)
switch {
case err != nil:
errs = append(errs, fmt.Errorf("%w: %w", ErrGeoIPInvalidEndpoint, err))
case u.Scheme != "http" && u.Scheme != "https", u.Host == "":
errs = append(errs, fmt.Errorf("%w: %q must be an absolute http or https URL", ErrGeoIPInvalidEndpoint, *g.Endpoint))
}
}
if len(errs) != 0 {
return fmt.Errorf("auto_update: %w", errors.Join(errs...))
}
return nil
}
// GetInterval returns the parsed update interval or the default. Call Valid first.
func (g *GeoIPAutoUpdate) GetInterval() time.Duration {
if g.Interval == nil {
return DefaultGeoIPUpdateInterval
}
// XXX(Xe): already validated in Valid()
d, _ := time.ParseDuration(*g.Interval)
return d
}
// LicenseKey reads the license key from the configured environment variable.
func (g *GeoIPAutoUpdate) LicenseKey() string {
return os.Getenv(g.LicenseKeyEnv)
}
+214
View File
@@ -0,0 +1,214 @@
package config
import (
"errors"
"os"
"path/filepath"
"testing"
"time"
)
const testLicenseKeyEnv = "ANUBIS_TEST_MAXMIND_LICENSE_KEY"
func TestGeoIPDatabasesValid(t *testing.T) {
for _, tt := range []struct {
name string
input *GeoIPDatabases
setEnv bool
errs []error
}{
{
name: "asn only",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
},
},
{
name: "country only with registered_country",
input: &GeoIPDatabases{
Country: &GeoIPDatabase{
Path: "/tmp/country.mmdb",
CountryField: new(CountryFieldRegisteredCountry),
},
},
},
{
name: "both with auto update",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
Country: &GeoIPDatabase{Path: "/tmp/country.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
Interval: new("72h"),
Endpoint: new("https://updates.maxmind.com"),
},
},
setEnv: true,
},
{
name: "no databases",
input: &GeoIPDatabases{},
errs: []error{ErrGeoIPNoDatabases},
},
{
name: "no path",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{},
Country: &GeoIPDatabase{},
},
errs: []error{ErrGeoIPNoPath},
},
{
name: "empty edition id",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb", EditionID: new("")},
},
errs: []error{ErrGeoIPEmptyEditionID},
},
{
name: "country field on asn",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb", CountryField: new(CountryFieldCountry)},
},
errs: []error{ErrGeoIPCountryFieldOnASN},
},
{
name: "invalid country field",
input: &GeoIPDatabases{
Country: &GeoIPDatabase{Path: "/tmp/country.mmdb", CountryField: new(CountryField("continent"))},
},
errs: []error{ErrGeoIPInvalidCountryField},
},
{
name: "auto update missing everything",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{},
},
errs: []error{ErrGeoIPNoAccountID, ErrGeoIPNoLicenseKeyEnv},
},
{
name: "auto update license env not set",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
},
},
errs: []error{ErrGeoIPLicenseKeyEnvNotSet},
},
{
name: "auto update bad interval and endpoint",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
Interval: new("soon"),
Endpoint: new("updates.maxmind.com"),
},
},
setEnv: true,
errs: []error{ErrGeoIPInvalidInterval, ErrGeoIPInvalidEndpoint},
},
{
name: "auto update interval too short",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
Interval: new("5m"),
},
},
setEnv: true,
errs: []error{ErrGeoIPIntervalTooShort},
},
} {
t.Run(tt.name, func(t *testing.T) {
if tt.setEnv {
t.Setenv(testLicenseKeyEnv, "hunter2")
} else {
t.Setenv(testLicenseKeyEnv, "")
}
err := tt.input.Valid()
if len(tt.errs) == 0 && err != nil {
t.Fatalf("wanted no error, got: %v", err)
}
if len(tt.errs) != 0 && err == nil {
t.Fatalf("wanted errors %v, got nil", tt.errs)
}
for _, want := range tt.errs {
if !errors.Is(err, want) {
t.Logf("want: %v", want)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
}
})
}
}
func TestGeoIPDatabasesDefaults(t *testing.T) {
g := &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
Country: &GeoIPDatabase{Path: "/tmp/country.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{},
}
if got := g.ASNEditionID(); got != DefaultGeoIPASNEditionID {
t.Errorf("ASNEditionID: want %q, got %q", DefaultGeoIPASNEditionID, got)
}
if got := g.CountryEditionID(); got != DefaultGeoIPCountryEditionID {
t.Errorf("CountryEditionID: want %q, got %q", DefaultGeoIPCountryEditionID, got)
}
if got := g.Country.GetCountryField(); got != CountryFieldCountry {
t.Errorf("GetCountryField: want %q, got %q", CountryFieldCountry, got)
}
if got := g.AutoUpdate.GetInterval(); got != DefaultGeoIPUpdateInterval {
t.Errorf("GetInterval: want %s, got %s", DefaultGeoIPUpdateInterval, got)
}
g.AutoUpdate.Interval = new("2h")
if got := g.AutoUpdate.GetInterval(); got != 2*time.Hour {
t.Errorf("GetInterval: want %s, got %s", 2*time.Hour, got)
}
}
func TestGeoIPDatabasesLoad(t *testing.T) {
fin, err := os.Open(filepath.Join("testdata", "geoip_databases.yaml"))
if err != nil {
t.Fatal(err)
}
defer fin.Close() //nolint:errcheck
c, err := Load(fin, "geoip_databases.yaml")
if err != nil {
t.Fatal(err)
}
if c.GeoIP == nil {
t.Fatal("wanted geoip block to be loaded, got nil")
}
if got := c.GeoIP.ASN.Path; got != "/var/lib/anubis/GeoLite2-ASN.mmdb" {
t.Errorf("asn path: got %q", got)
}
if got := c.GeoIP.Country.GetCountryField(); got != CountryFieldRegisteredCountry {
t.Errorf("country field: want %q, got %q", CountryFieldRegisteredCountry, got)
}
if c.GeoIP.AutoUpdate != nil {
t.Errorf("auto_update: want nil, got %+v", c.GeoIP.AutoUpdate)
}
}
+44
View File
@@ -0,0 +1,44 @@
package config
import (
"errors"
"fmt"
)
var ErrInvalidHoneypotMethod = errors.New("config.Honeypot: invalid implementation selected (try: \"naive\")")
type Honeypot struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Implementation string `json:"implementation" yaml:"implementation"`
IPLogFile string `json:"ip_log_file" yaml:"ip_log_file"`
}
func (h Honeypot) Valid() error {
var errs []error
// Short-circuit, if disabled then the implementation is moot.
if !h.Enabled {
return nil
}
if h.Implementation == "" {
errs = append(errs, fmt.Errorf("config.Honeypot: missing field \"implementation\": %w", ErrMissingValue))
}
if h.Implementation != "naive" {
errs = append(errs, fmt.Errorf("%w: got: %q", ErrInvalidHoneypotMethod, h.Implementation))
}
if len(errs) != 0 {
return errors.Join(errs...)
}
return nil
}
func (h Honeypot) Default() Honeypot {
return Honeypot{
Enabled: true,
Implementation: "naive",
}
}
+87
View File
@@ -0,0 +1,87 @@
package config
import (
"errors"
"testing"
)
func TestHoneypotValid(t *testing.T) {
for _, cs := range []struct {
err error
name string
inp Honeypot
}{
{
name: "naive enabled",
inp: Honeypot{
Enabled: true,
Implementation: "naive",
},
err: nil,
},
{
name: "naive disabled",
inp: Honeypot{
Enabled: false,
Implementation: "naive",
},
err: nil,
},
{
name: "empty implementation",
inp: Honeypot{
Enabled: true,
Implementation: "",
},
err: ErrInvalidHoneypotMethod,
},
{
name: "unknown implementation",
inp: Honeypot{
Enabled: true,
Implementation: "sophisticated",
},
err: ErrInvalidHoneypotMethod,
},
{
name: "wrong case implementation",
inp: Honeypot{
Enabled: true,
Implementation: "Naive",
},
err: ErrInvalidHoneypotMethod,
},
{
name: "zero value",
inp: Honeypot{},
err: nil,
},
} {
t.Run(cs.name, func(t *testing.T) {
if err := cs.inp.Valid(); !errors.Is(err, cs.err) {
t.Logf("want: %v", cs.err)
t.Logf("got: %v", err)
t.Error("validation returned an unexpected error")
}
})
}
}
func TestHoneypotDefault(t *testing.T) {
want := Honeypot{
Enabled: true,
Implementation: "naive",
}
got := (Honeypot{}).Default()
if got != want {
t.Errorf("Default() = %+v, want %+v", got, want)
}
}
func TestHoneypotDefaultIsValid(t *testing.T) {
h := (Honeypot{}).Default()
if err := h.Valid(); err != nil {
t.Fatal(err)
}
}
+155
View File
@@ -0,0 +1,155 @@
package config
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"github.com/TecharoHQ/anubis/data"
"github.com/TecharoHQ/anubis/internal/multifile"
"github.com/fvbommel/sortorder"
"github.com/goreleaser/fileglob"
"k8s.io/apimachinery/pkg/util/yaml"
)
var (
ErrInvalidImportStatement = errors.New("config.ImportStatement: invalid source file")
ErrCantReadImportedFile = errors.New("config.ImportStatement: can't read imported file")
ErrGlobMatchedNothing = errors.New("config.ImportStatement: glob pattern matched no files")
)
type ImportStatement struct {
Import string `json:"import"`
Bots []BotConfig
}
const globHints = `recursive wildcards ("**") and alternation ("{yaml,yml}") are not supported`
func globMatch(globbedPath string) (fs.FS, []string, error) {
var fsys fs.FS = nil
if after, ok := strings.CutPrefix(globbedPath, "(data)/"); ok {
globbedPath = after
fsys = data.BotPolicies
}
var matches []string
var err error
switch {
case fsys == nil:
matches, err = filepath.Glob(globbedPath)
case fsys != nil:
matches, err = fs.Glob(fsys, globbedPath)
}
if err != nil {
return nil, nil, fmt.Errorf("%w: %w", ErrInvalidImportStatement, err)
}
if len(matches) == 0 {
if strings.Contains(globbedPath, "**") || strings.Contains(globbedPath, "{") {
return nil, nil, fmt.Errorf("%w: note that %s", ErrGlobMatchedNothing, globHints)
}
return nil, nil, ErrGlobMatchedNothing
}
sort.Sort(sortorder.Natural(matches))
var errs []error
for _, fname := range matches {
switch {
case fsys == nil:
if _, err := os.Stat(fname); err != nil {
errs = append(errs, fmt.Errorf("%w: %q", ErrCantReadImportedFile, fname))
}
case fsys != nil:
if _, err := fs.Stat(fsys, fname); err != nil {
errs = append(errs, fmt.Errorf("%w: %q", ErrCantReadImportedFile, fname))
}
}
}
if len(errs) != 0 {
return nil, nil, fmt.Errorf("%w: %w", ErrInvalidImportStatement, errors.Join(errs...))
}
return fsys, matches, nil
}
func (is *ImportStatement) open() (fs.File, error) {
if fileglob.ContainsMatchers(is.Import) {
fsys, fnames, err := globMatch(is.Import)
if err != nil {
return nil, err
}
return multifile.YAMLList(fsys, fnames)
}
if after, ok := strings.CutPrefix(is.Import, "(data)/"); ok {
fname := after
fin, err := data.BotPolicies.Open(fname)
return fin, err
}
return os.Open(is.Import)
}
func (is *ImportStatement) load() error {
fin, err := is.open()
if err != nil {
return fmt.Errorf("%w: %s: %w", ErrInvalidImportStatement, is.Import, err)
}
defer fin.Close() //nolint:errcheck
var imported []BotOrImport
var result []BotConfig
dec := yaml.NewYAMLToJSONDecoder(fin)
for {
var doc []BotOrImport
if err := dec.Decode(&doc); err != nil {
if errors.Is(err, io.EOF) {
break
}
return fmt.Errorf("%w: can't parse %s: %w", ErrInvalidImportStatement, is.Import, err)
}
imported = append(imported, doc...)
}
var errs []error
for _, b := range imported {
if err := b.Valid(); err != nil {
errs = append(errs, err)
}
if b.ImportStatement != nil {
result = append(result, b.Bots...)
}
if b.BotConfig != nil {
result = append(result, *b.BotConfig)
}
}
if len(errs) != 0 {
return fmt.Errorf("config %s is not valid:\n%w", is.Import, errors.Join(errs...))
}
is.Bots = result
return nil
}
func (is *ImportStatement) Valid() error {
return is.load()
}
+146
View File
@@ -0,0 +1,146 @@
package config
import (
"errors"
"io/fs"
"path/filepath"
"slices"
"testing"
"github.com/TecharoHQ/anubis/data"
)
func TestGlobMatch(t *testing.T) {
for _, tt := range []struct {
globbedPath string
matches []string
err error
}{
{
globbedPath: "(data)/apps/allow-api-routes*.yaml",
matches: []string{"apps/allow-api-routes.yaml"},
},
{
globbedPath: "./testdata/hack-test.*",
matches: []string{"testdata/hack-test.json", "testdata/hack-test.yaml"},
},
{
globbedPath: "/does/not/exist/*",
err: ErrGlobMatchedNothing,
},
{
// filepath.Match has no alternation syntax, so the braces are
// matched literally and nothing is found.
globbedPath: "(data)/bots/*.{yaml,yml}",
err: ErrGlobMatchedNothing,
},
} {
t.Run(tt.globbedPath, func(t *testing.T) {
_, matches, err := globMatch(tt.globbedPath)
if !errors.Is(err, tt.err) {
t.Logf("wanted error: %v", tt.err)
t.Logf(" got error: %v", err)
t.Error("unexpected error received")
}
if !slices.Equal(tt.matches, matches) {
t.Logf("wanted files: %#v", tt.matches)
t.Logf(" got files: %#v", matches)
t.Error("unexpected file matches")
}
})
}
}
func TestImportMultiDocument(t *testing.T) {
for _, tt := range []struct {
name string
globbedPath string
botCount int
}{
{"multi-document", "./testdata/multi-document/*.yaml", 3},
{"single-file", "./testdata/multi-document/small-internet-browsers.yaml", 2},
} {
t.Run(tt.name, func(t *testing.T) {
is := &ImportStatement{Import: tt.globbedPath}
if err := is.Valid(); err != nil {
t.Fatal(err)
}
if len(is.Bots) != tt.botCount {
t.Errorf("wanted bot count: %d, got: %d", tt.botCount, len(is.Bots))
}
})
}
}
// TestImportStatementGlobMatchedNothing asserts that an import statement whose
// glob pattern matches no files fails with ErrGlobMatchedNothing instead of the
// io.EOF that the YAML decoder would return for an empty document.
func TestImportStatementGlobMatchedNothing(t *testing.T) {
for _, globbedPath := range []string{
"(data)/bots/*.yml",
"(data)/does-not-exist/*.yaml",
"./testdata/does-not-exist/*.yaml",
} {
t.Run(globbedPath, func(t *testing.T) {
is := &ImportStatement{Import: globbedPath}
err := is.Valid()
if !errors.Is(err, ErrGlobMatchedNothing) {
t.Logf("wanted error: %v", ErrGlobMatchedNothing)
t.Logf(" got error: %v", err)
t.Error("unexpected error received")
}
})
}
}
// TestImportStatement asserts that every policy snippet in the data folder can
// be imported and is valid. The list of files is discovered by walking the
// embedded filesystem so that new folders and new snippets are covered without
// having to remember to add them here.
func TestImportStatement(t *testing.T) {
var importPaths []string
if err := fs.WalkDir(data.BotPolicies, ".", func(path string, d fs.DirEntry, err error) error {
switch {
case err != nil:
return err
case d.IsDir():
return nil
case path == "botPolicies.yaml": // an entire config, not a list of bots
return nil
}
switch filepath.Ext(path) {
case ".yaml", ".yml":
importPaths = append(importPaths, "(data)/"+path)
}
return nil
}); err != nil {
t.Fatal(err)
}
if len(importPaths) == 0 {
t.Fatal("no policy snippets found in the embedded data folder")
}
for _, importPath := range importPaths {
t.Run(importPath, func(t *testing.T) {
is := &ImportStatement{
Import: importPath,
}
if err := is.Valid(); err != nil {
t.Errorf("validation error: %v", err)
}
if len(is.Bots) == 0 {
t.Error("wanted bot definitions, but got none")
}
})
}
}
+1
View File
@@ -17,6 +17,7 @@ type Logging struct {
Sink string `json:"sink"` // Logging sink, either "stdio" or "file"
Level *slog.Level `json:"level"` // Log level, if set supersedes the level in flags
Parameters *LoggingFileConfig `json:"parameters"` // Logging parameters, to be dynamic in the future
LogASN bool `json:"asn" yaml:"asn"`
}
const (
+170
View File
@@ -0,0 +1,170 @@
package config
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"strconv"
)
var (
ErrInvalidMetricsConfig = errors.New("config: invalid metrics configuration")
ErrInvalidMetricsTLSConfig = errors.New("config: invalid metrics TLS configuration")
ErrInvalidMetricsBasicAuthConfig = errors.New("config: invalid metrics basic auth configuration")
ErrNoMetricsBind = errors.New("config.Metrics: must define bind")
ErrNoMetricsNetwork = errors.New("config.Metrics: must define network")
ErrNoMetricsSocketMode = errors.New("config.Metrics: must define socket mode when using unix sockets")
ErrInvalidMetricsSocketMode = errors.New("config.Metrics: invalid unix socket mode")
ErrInvalidMetricsNetwork = errors.New("config.Metrics: invalid metrics network")
ErrNoMetricsTLSCertificate = errors.New("config.Metrics.TLS: must define certificate file")
ErrNoMetricsTLSKey = errors.New("config.Metrics.TLS: must define key file")
ErrInvalidMetricsTLSKeypair = errors.New("config.Metrics.TLS: keypair is invalid")
ErrInvalidMetricsCACertificate = errors.New("config.Metrics.TLS: invalid CA certificate")
ErrCantReadFile = errors.New("config: can't read required file")
ErrNoMetricsBasicAuthUsername = errors.New("config.Metrics.BasicAuth: must define username")
ErrNoMetricsBasicAuthPassword = errors.New("config.Metrics.BasicAuth: must define password")
)
type Metrics struct {
Bind string `json:"bind" yaml:"bind"`
Network string `json:"network" yaml:"network"`
SocketMode string `json:"socketMode" yaml:"socketMode"`
TLS *MetricsTLS `json:"tls" yaml:"tls"`
Debug bool `json:"debug" yaml:"debug"`
BasicAuth *MetricsBasicAuth `json:"basicAuth" yaml:"basicAuth"`
}
func (m *Metrics) Valid() error {
var errs []error
if m.Bind == "" {
errs = append(errs, ErrNoMetricsBind)
}
if m.Network == "" {
errs = append(errs, ErrNoMetricsNetwork)
}
switch m.Network {
case "tcp", "tcp4", "tcp6": // https://pkg.go.dev/net#Listen
case "unix":
if m.SocketMode == "" {
errs = append(errs, ErrNoMetricsSocketMode)
}
if _, err := strconv.ParseUint(m.SocketMode, 8, 0); err != nil {
errs = append(errs, fmt.Errorf("%w: %w", ErrInvalidMetricsSocketMode, err))
}
default:
errs = append(errs, ErrInvalidMetricsNetwork)
}
if m.TLS != nil {
if err := m.TLS.Valid(); err != nil {
errs = append(errs, err)
}
}
if m.BasicAuth != nil {
if err := m.BasicAuth.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Join(ErrInvalidMetricsConfig, errors.Join(errs...))
}
return nil
}
type MetricsTLS struct {
Certificate string `json:"certificate" yaml:"certificate"`
Key string `json:"key" yaml:"key"`
CA string `json:"ca" yaml:"ca"`
}
func (mt *MetricsTLS) Valid() error {
var errs []error
if mt.Certificate == "" {
errs = append(errs, ErrNoMetricsTLSCertificate)
}
if err := canReadFile(mt.Certificate); err != nil {
errs = append(errs, fmt.Errorf("%w %s: %w", ErrCantReadFile, mt.Certificate, err))
}
if mt.Key == "" {
errs = append(errs, ErrNoMetricsTLSKey)
}
if err := canReadFile(mt.Key); err != nil {
errs = append(errs, fmt.Errorf("%w %s: %w", ErrCantReadFile, mt.Key, err))
}
if _, err := tls.LoadX509KeyPair(mt.Certificate, mt.Key); err != nil {
errs = append(errs, fmt.Errorf("%w: %w", ErrInvalidMetricsTLSKeypair, err))
}
if mt.CA != "" {
caCert, err := os.ReadFile(mt.CA)
if err != nil {
errs = append(errs, fmt.Errorf("%w %s: %w", ErrCantReadFile, mt.CA, err))
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(caCert) {
errs = append(errs, fmt.Errorf("%w %s", ErrInvalidMetricsCACertificate, mt.CA))
}
}
if len(errs) != 0 {
return errors.Join(ErrInvalidMetricsTLSConfig, errors.Join(errs...))
}
return nil
}
func canReadFile(fname string) error {
fin, err := os.Open(fname)
if err != nil {
return err
}
data := make([]byte, 64)
if _, err := fin.Read(data); err != nil {
return fmt.Errorf("can't read %s: %w", fname, err)
}
if err := fin.Close(); err != nil {
return err
}
return nil
}
type MetricsBasicAuth struct {
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
}
func (mba *MetricsBasicAuth) Valid() error {
var errs []error
if mba.Username == "" {
errs = append(errs, ErrNoMetricsBasicAuthUsername)
}
if mba.Password == "" {
errs = append(errs, ErrNoMetricsBasicAuthPassword)
}
if len(errs) != 0 {
return errors.Join(ErrInvalidMetricsBasicAuthConfig, errors.Join(errs...))
}
return nil
}
+242
View File
@@ -0,0 +1,242 @@
package config
import (
"errors"
"testing"
)
func TestMetricsValid(t *testing.T) {
for _, tt := range []struct {
name string
input *Metrics
err error
}{
{
name: "basic TCP",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
},
},
{
name: "basic TCP4",
input: &Metrics{
Bind: ":9090",
Network: "tcp4",
},
},
{
name: "basic TCP6",
input: &Metrics{
Bind: ":9090",
Network: "tcp6",
},
},
{
name: "basic unix",
input: &Metrics{
Bind: "/tmp/anubis-metrics.sock",
Network: "unix",
SocketMode: "0770",
},
},
{
name: "no bind",
input: &Metrics{},
err: ErrNoMetricsBind,
},
{
name: "no network",
input: &Metrics{},
err: ErrNoMetricsNetwork,
},
{
name: "no unix socket mode",
input: &Metrics{
Bind: "/tmp/anubis-metrics.sock",
Network: "unix",
},
err: ErrNoMetricsSocketMode,
},
{
name: "invalid unix socket mode",
input: &Metrics{
Bind: "/tmp/anubis-metrics.sock",
Network: "unix",
SocketMode: "taco bell",
},
err: ErrInvalidMetricsSocketMode,
},
{
name: "invalid network",
input: &Metrics{
Bind: ":9090",
Network: "taco",
},
err: ErrInvalidMetricsNetwork,
},
{
name: "invalid TLS config",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{},
},
err: ErrInvalidMetricsTLSConfig,
},
{
name: "selfsigned TLS cert",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
},
},
},
{
name: "wrong path to selfsigned TLS cert",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls2/selfsigned.crt",
Key: "./testdata/tls2/selfsigned.key",
},
},
err: ErrCantReadFile,
},
{
name: "unparseable TLS cert",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/invalid.crt",
Key: "./testdata/tls/invalid.key",
},
},
err: ErrInvalidMetricsTLSKeypair,
},
{
name: "mTLS with CA",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
CA: "./testdata/tls/minica.pem",
},
},
},
{
name: "mTLS with nonexistent CA",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
CA: "./testdata/tls/nonexistent.crt",
},
},
err: ErrCantReadFile,
},
{
name: "mTLS with invalid CA",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
CA: "./testdata/tls/invalid.crt",
},
},
err: ErrInvalidMetricsCACertificate,
},
{
name: "basic auth credentials set",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
BasicAuth: &MetricsBasicAuth{
Username: "admin",
Password: "hunter2",
},
},
},
{
name: "invalid basic auth config",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
BasicAuth: &MetricsBasicAuth{},
},
err: ErrInvalidMetricsBasicAuthConfig,
},
} {
t.Run(tt.name, func(t *testing.T) {
if err := tt.input.Valid(); !errors.Is(err, tt.err) {
t.Logf("wanted error: %v", tt.err)
t.Logf("got error: %v", err)
t.Error("validation failed")
}
})
}
}
func TestMetricsBasicAuthValid(t *testing.T) {
for _, tt := range []struct {
name string
input *MetricsBasicAuth
err error
}{
{
name: "both set",
input: &MetricsBasicAuth{
Username: "admin",
Password: "hunter2",
},
},
{
name: "empty username and password",
input: &MetricsBasicAuth{},
err: ErrInvalidMetricsBasicAuthConfig,
},
{
name: "missing username",
input: &MetricsBasicAuth{
Password: "hunter2",
},
err: ErrNoMetricsBasicAuthUsername,
},
{
name: "missing password",
input: &MetricsBasicAuth{
Username: "admin",
},
err: ErrNoMetricsBasicAuthPassword,
},
{
name: "missing both surfaces wrapper error",
input: &MetricsBasicAuth{},
err: ErrNoMetricsBasicAuthUsername,
},
{
name: "missing both surfaces password error",
input: &MetricsBasicAuth{},
err: ErrNoMetricsBasicAuthPassword,
},
} {
t.Run(tt.name, func(t *testing.T) {
if err := tt.input.Valid(); !errors.Is(err, tt.err) {
t.Logf("wanted error: %v", tt.err)
t.Logf("got error: %v", err)
t.Error("validation failed")
}
})
}
}
@@ -0,0 +1,9 @@
bots:
- name: everyone
user_agent_regex: .
action: CHALLENGE
challenge:
algorithm: metarefresh
difficulty: 1
extensions:
- ""
@@ -0,0 +1,10 @@
bots:
- name: everyone
user_agent_regex: .
action: CHALLENGE
challenge:
algorithm: metarefresh
difficulty: 1
extensions:
- test-extension
- test-extension
@@ -0,0 +1,11 @@
bots:
- name: everything
action: CHALLENGE
path_regex: .*
geoip:
asn:
path: /var/lib/anubis/GeoLite2-ASN.mmdb
auto_update:
license_key_env: ANUBIS_TEST_MAXMIND_LICENSE_KEY_THAT_IS_NOT_SET
interval: 5m
@@ -0,0 +1,9 @@
bots:
- name: everything
action: CHALLENGE
path_regex: .*
geoip:
country:
path: /var/lib/anubis/GeoLite2-Country.mmdb
country_field: continent
+8
View File
@@ -0,0 +1,8 @@
bots:
- name: everything
action: CHALLENGE
path_regex: .*
geoip:
asn:
edition_id: GeoLite2-ASN
@@ -0,0 +1,8 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: true
implementation: ""
@@ -0,0 +1,13 @@
{
"bots": [
{
"name": "everything",
"user_agent_regex": ".*",
"action": "DENY"
}
],
"honeypot": {
"enabled": true,
"implementation": "sophisticated"
}
}
@@ -0,0 +1,8 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: true
implementation: sophisticated
+2
View File
@@ -0,0 +1,2 @@
bots:
- import: (data)/bots/never-matches/*[abc]abc]\.yaml
+2
View File
@@ -0,0 +1,2 @@
bots:
- import: (data)/bots/never-matches/*.yaml
+3
View File
@@ -0,0 +1,3 @@
metrics:
bind: ":9090"
network: taco
+6
View File
@@ -0,0 +1,6 @@
bots:
- name: both-addr-kinds
action: ALLOW
remote_addresses:
- "0.0.0.0/0"
remote_addresses_url: "https://openai.com/searchbot.json"
+23
View File
@@ -0,0 +1,23 @@
bots:
- name: countries-with-aggressive-scrapers
action: WEIGH
geoip:
countries:
- BR
- CN
weight:
adjust: 10
- name: aggressive-asns-without-functional-abuse-contact
action: WEIGH
asns:
match:
- 13335
weight:
adjust: 10
geoip:
asn:
path: /var/lib/anubis/GeoLite2-ASN.mmdb
country:
path: /var/lib/anubis/GeoLite2-Country.mmdb
country_field: registered_country
+5 -1
View File
@@ -5,5 +5,9 @@
"remote_addresses": ["0.0.0.0/0", "::/0"],
"action": "ALLOW"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -4,3 +4,7 @@ bots:
- "0.0.0.0/0"
- "::/0"
action: ALLOW
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -8,5 +8,9 @@
"action": "DENY"
}
],
"dnsbl": false
"dnsbl": false,
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -3,3 +3,7 @@ bots:
headers_regex:
CF-Worker: .*
action: DENY
metrics:
bind: ":9090"
network: "tcp"
+19
View File
@@ -0,0 +1,19 @@
bots:
- name: everyone
user_agent_regex: .
action: CHALLENGE
challenge:
algorithm: fast
difficulty: 2
extensions:
- test-extension
thresholds:
- name: extreme-suspicion
expression: weight >= 20
action: CHALLENGE
challenge:
algorithm: preact
difficulty: 1
extensions:
- test-extension
+4
View File
@@ -4,3 +4,7 @@ bots:
asns:
match:
- 13335 # Cloudflare
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -5,5 +5,9 @@
"user_agent_regex": "Mozilla",
"action": "CHALLENGE"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -2,3 +2,7 @@ bots:
- name: generic-browser
user_agent_regex: Mozilla
action: CHALLENGE
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -6,3 +6,7 @@ bots:
- name: "test"
user_agent_regex: ".*"
action: "DENY"
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -6,3 +6,7 @@ bots:
- '"Accept" in headers'
- headers["Accept"].contains("text/html")
- randInt(1) == 0
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -6,5 +6,9 @@
"action": "DENY"
}
],
"dnsbl": false
"dnsbl": false,
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -2,3 +2,7 @@ bots:
- name: everything
user_agent_regex: .*
action: DENY
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -4,3 +4,7 @@ bots:
geoip:
countries:
- US
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -10,5 +10,9 @@
]
}
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -6,3 +6,7 @@ bots:
- userAgent.startsWith("git/") || userAgent.contains("libgit")
- >
"Git-Protocol" in headers && headers["Git-Protocol"] == "version=2"
metrics:
bind: ":9090"
network: "tcp"
+7
View File
@@ -0,0 +1,7 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: false
+13
View File
@@ -0,0 +1,13 @@
{
"bots": [
{
"name": "everything",
"user_agent_regex": ".*",
"action": "DENY"
}
],
"honeypot": {
"enabled": true,
"implementation": "naive"
}
}
+8
View File
@@ -0,0 +1,8 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: true
implementation: naive
+2
View File
@@ -0,0 +1,2 @@
bots:
- import: (data)/bots/*.yaml
+5 -1
View File
@@ -3,5 +3,9 @@
{
"import": "./testdata/hack-test.json"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -1,2 +1,6 @@
bots:
- import: ./testdata/hack-test.yaml
metrics:
bind: ":9090"
network: "tcp"
@@ -0,0 +1,6 @@
bots:
- import: (data)/clients/google-user-triggered-fetchers.yaml
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -3,5 +3,9 @@
{
"import": "(data)/common/keep-internet-working.yaml"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
@@ -1,2 +1,6 @@
bots:
- import: (data)/common/keep-internet-working.yaml
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -8,3 +8,7 @@ impressum:
page:
title: Test
body: <p>This is a test</p>
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -13,3 +13,7 @@ logs:
oldFileTimeFormat: 2006-01-02T15-04-05 # RFC 3339-ish
compress: true
useLocalTime: false # timezone for rotated files is UTC
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -5,3 +5,7 @@ bots:
logging:
sink: "stdio"
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -6,3 +6,7 @@ bots:
adjust: 5
thresholds: []
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -75,5 +75,9 @@
"user_agent_regex": "Mozilla",
"action": "CHALLENGE"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -10,3 +10,7 @@ openGraph:
default:
"og:title": "Xe's magic land of fun"
"og:description": "We're no strangers to love, you know the rules and so do I"
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -4,3 +4,7 @@ bots:
user_agent_regex: Mozilla
weight:
adjust: 5
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -9,5 +9,9 @@
"status_codes": {
"CHALLENGE": 200,
"DENY": 200
},
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -6,3 +6,7 @@ bots:
status_codes:
CHALLENGE: 200
DENY: 200
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -9,5 +9,9 @@
"status_codes": {
"CHALLENGE": 403,
"DENY": 403
},
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -6,3 +6,7 @@ bots:
status_codes:
CHALLENGE: 403
DENY: 403
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -33,3 +33,7 @@ thresholds:
challenge:
algorithm: fast
difficulty: 4
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -2,3 +2,7 @@ bots:
- name: weight
action: WEIGH
user_agent_regex: Mozilla
metrics:
bind: ":9090"
network: "tcp"
+21
View File
@@ -0,0 +1,21 @@
---
- name: allow-git-clients
action: ALLOW
expression:
all:
- >
(
userAgent.startsWith("git/") ||
userAgent.contains("libgit") ||
userAgent.startsWith("go-git") ||
userAgent.startsWith("JGit/") ||
userAgent.startsWith("JGit-")
)
- '"Accept" in headers'
- headers["Accept"] == "*/*"
- '"Cache-Control" in headers'
- headers["Cache-Control"] == "no-cache"
- '"Pragma" in headers'
- headers["Pragma"] == "no-cache"
- '"Accept-Encoding" in headers'
- headers["Accept-Encoding"].contains("gzip")
@@ -0,0 +1,11 @@
- name: "reduce-weight-palemoon"
user_agent_regex: "PaleMoon"
action: WEIGH
weight:
adjust: -5
---
- name: "reduce-weight-dillo"
user_agent_regex: "Dillo"
action: WEIGH
weight:
adjust: -5
+12
View File
@@ -0,0 +1,12 @@
-----BEGIN CERTIFICATE-----
MIIB1zCCAVygAwIBAgIIYO0SAFtXlVgwCgYIKoZIzj0EAwMwIDEeMBwGA1UEAxMV
bWluaWNhIHJvb3QgY2EgNDE2MmMwMB4XDTI2MDQyMjIzMjUwMVoXDTI4MDUyMjIz
MjUwMVowEjEQMA4GA1UEAxMHMS4xLjEuMTB2MBAGByqGSM49AgEGBSuBBAAiA2IA
BLsuA2LKGbEBuSA4LTm1KaKc7/QCkUOsipXR4+D5/3sWBZiAH7iWUgHwpx5YZf2q
kZn6oRda+ks0JLTQ6VhteQedmb7l86bMeDMR8p4Lg2b38l/xEr7S25UfUDKudXrO
AqNxMG8wDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEF
BQcDAjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFE/7VDxF2+cUs9bu0pJM3xoC
L1TSMA8GA1UdEQQIMAaHBAEBAQEwCgYIKoZIzj0EAwMDaQAwZgIxAPLXds9MMH4K
F5FxTf9i0PKPsLQARsABVTgwB94hMR70rqW8Pwbjl7ZGNaYlaeRHUwIxAPMQ8zoF
nim+YS1xLqQek/LXuJto8jxcfkQQBsboVzcTa5uaNRhNd5YwrpomGl3lKA==
-----END CERTIFICATE-----
+6
View File
@@ -0,0 +1,6 @@
-----BEGIN PRIVATE KEY-----
MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBN8QsHxxHGJpStu8K7
D/FmaBBNo6c514KGFSIfqGFuREF5aOL3gN/W11yk2OIibdWhZANiAAS7LgNiyhmx
AbkgOC05tSminO/0ApFDrIqV0ePg+f97FgWYgB+4llIB8KceWGX9qpGZ+qEXWvpL
NCS00OlYbXkHnZm+5fOmzHgzEfKeC4Nm9/Jf8RK+0tuVH1AyrnV6zgI=
-----END PRIVATE KEY-----
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+6
View File
@@ -0,0 +1,6 @@
-----BEGIN PRIVATE KEY-----
MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDr9QQo7ZaTgUL6d73G
2BG7+YRTFJHAZa0FogRglfc+jYttL1J4/xTig3RmHoqSgrehZANiAASDhijM9Xe0
G9Vam6AJMeKC6aWDNSLwrxNVmPxemsY/yJ1urBgnxRd9GFH6YW1ki/B8rS+Xl1UX
NnhBrukLaXvgAQQq782/5IUYGsvK5jw8+dSscYVMCQJwGfmQuaNeczQ=
-----END PRIVATE KEY-----
+13
View File
@@ -0,0 +1,13 @@
-----BEGIN CERTIFICATE-----
MIIB+zCCAYKgAwIBAgIIQWLAtv4ijQ0wCgYIKoZIzj0EAwMwIDEeMBwGA1UEAxMV
bWluaWNhIHJvb3QgY2EgNDE2MmMwMCAXDTI2MDQyMjIzMjUwMVoYDzIxMjYwNDIy
MjMyNTAxWjAgMR4wHAYDVQQDExVtaW5pY2Egcm9vdCBjYSA0MTYyYzAwdjAQBgcq
hkjOPQIBBgUrgQQAIgNiAASDhijM9Xe0G9Vam6AJMeKC6aWDNSLwrxNVmPxemsY/
yJ1urBgnxRd9GFH6YW1ki/B8rS+Xl1UXNnhBrukLaXvgAQQq782/5IUYGsvK5jw8
+dSscYVMCQJwGfmQuaNeczSjgYYwgYMwDgYDVR0PAQH/BAQDAgKEMB0GA1UdJQQW
MBQGCCsGAQUFBwMBBggrBgEFBQcDAjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1Ud
DgQWBBRP+1Q8RdvnFLPW7tKSTN8aAi9U0jAfBgNVHSMEGDAWgBRP+1Q8RdvnFLPW
7tKSTN8aAi9U0jAKBggqhkjOPQQDAwNnADBkAjBfY7vb7cuLTjg7uoe+kl07FMYT
BGMSnWdhN3yXqMUS3A6XZxD/LntXT6V7yFOlAJYCMH7w8/ATYaTqbk2jBRyQt9/x
ajN+kZ6ZK+fKttqE8CD62mbHg09xoNxRq+K2I3PVyQ==
-----END CERTIFICATE-----
+11
View File
@@ -0,0 +1,11 @@
-----BEGIN CERTIFICATE-----
MIIBnzCCAVGgAwIBAgIUK39B3Ft+kU5o81IuISs79O4u1ncwBQYDK2VwMEUxCzAJ
BgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5l
dCBXaWRnaXRzIFB0eSBMdGQwHhcNMjYwNDIyMTQyNjE4WhcNMjYwNTIyMTQyNjE4
WjBFMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwY
SW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMCowBQYDK2VwAyEAfgpAUpp8MIOOdQpH
fxaw3R7mFKQRMR6Kmxzk1Xn/2VujUzBRMB0GA1UdDgQWBBSmkBmzo0RiZ2iocMR8
uIIpz9cZyTAfBgNVHSMEGDAWgBSmkBmzo0RiZ2iocMR8uIIpz9cZyTAPBgNVHRMB
Af8EBTADAQH/MAUGAytlcANBAG37XXZrVUUzGyy3T9qsPIzvJQAGpGhdjJ7bt9O6
sBhzrliTONPrudYuyUggWsHgFb0JlN2xs4/2HhKU+PY7AAQ=
-----END CERTIFICATE-----
+3
View File
@@ -0,0 +1,3 @@
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIL0HxjjfVlg6zQPB9/zTLq0IBzfp8gEoifEYzQZYIj+T
-----END PRIVATE KEY-----
+1 -1
View File
@@ -97,7 +97,7 @@ func TestLoadActuallyLoadsThresholds(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer fin.Close()
defer fin.Close() //nolint:errcheck
c, err := Load(fin, fin.Name())
if err != nil {