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:   - 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:
1 parent
eb3e46d8d0
commit
caf4d72880
529 files changed
+33015
-6659
No files matched your search
+15
-4
@@ -1,8 +1,6 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/TecharoHQ/anubis/internal"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/TecharoHQ/anubis/lib/policy/checker"
|
||||
@@ -13,9 +11,22 @@ type Bot struct {
|
||||
Challenge *config.ChallengeRules
|
||||
Weight *config.Weight
|
||||
Name string
|
||||
Action config.Rule
|
||||
// hash caches the result of Hash() when populated at parse time, see ParseConfig
|
||||
hash string
|
||||
Action config.Rule
|
||||
}
|
||||
|
||||
// Hash returns a stable identifier for this Bot derived from its Name
|
||||
// and Rules. When the cached value is present (populated by
|
||||
// ParseConfig) it is returned directly; otherwise the hash is
|
||||
// recomputed on demand so callers do not have to know about the cache.
|
||||
func (b Bot) Hash() string {
|
||||
return internal.FastHash(fmt.Sprintf("%s::%s", b.Name, b.Rules.Hash()))
|
||||
if b.hash != "" {
|
||||
return b.hash
|
||||
}
|
||||
var rulesHash string
|
||||
if b.Rules != nil { // defensive, should never happen
|
||||
rulesHash = b.Rules.Hash()
|
||||
}
|
||||
return internal.FastHash(b.Name + "::" + rulesHash)
|
||||
}
|
||||
+28
-11
@@ -3,21 +3,23 @@ package policy
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"cel.dev/cel-go/cel"
|
||||
"cel.dev/cel-go/common/types"
|
||||
"github.com/TecharoHQ/anubis/internal"
|
||||
"github.com/TecharoHQ/anubis/internal/dns"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/TecharoHQ/anubis/lib/policy/expressions"
|
||||
"github.com/google/cel-go/cel"
|
||||
"github.com/google/cel-go/common/types"
|
||||
)
|
||||
|
||||
type CELChecker struct {
|
||||
program cel.Program
|
||||
src string
|
||||
program cel.Program
|
||||
src string
|
||||
subRequestMode bool
|
||||
}
|
||||
|
||||
func NewCELChecker(cfg *config.ExpressionOrList, dnsObj *dns.Dns) (*CELChecker, error) {
|
||||
func NewCELChecker(cfg *config.ExpressionOrList, dnsObj *dns.Dns, subRequestMode bool) (*CELChecker, error) {
|
||||
env, err := expressions.BotEnvironment(dnsObj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -29,8 +31,9 @@ func NewCELChecker(cfg *config.ExpressionOrList, dnsObj *dns.Dns) (*CELChecker,
|
||||
}
|
||||
|
||||
return &CELChecker{
|
||||
src: cfg.String(),
|
||||
program: program,
|
||||
src: cfg.String(),
|
||||
program: program,
|
||||
subRequestMode: subRequestMode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -39,7 +42,7 @@ func (cc *CELChecker) Hash() string {
|
||||
}
|
||||
|
||||
func (cc *CELChecker) Check(r *http.Request) (bool, error) {
|
||||
result, _, err := cc.program.ContextEval(r.Context(), &CELRequest{r})
|
||||
result, _, err := cc.program.ContextEval(r.Context(), &CELRequest{r, cc.subRequestMode})
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -54,6 +57,7 @@ func (cc *CELChecker) Check(r *http.Request) (bool, error) {
|
||||
|
||||
type CELRequest struct {
|
||||
*http.Request
|
||||
subRequestMode bool
|
||||
}
|
||||
|
||||
func (cr *CELRequest) Parent() cel.Activation { return nil }
|
||||
@@ -61,7 +65,7 @@ func (cr *CELRequest) Parent() cel.Activation { return nil }
|
||||
func (cr *CELRequest) ResolveName(name string) (any, bool) {
|
||||
switch name {
|
||||
case "remoteAddress":
|
||||
return cr.Header.Get("X-Real-Ip"), true
|
||||
return cr.Header.Get("X-Real-IP"), true
|
||||
case "contentLength":
|
||||
return cr.ContentLength, true
|
||||
case "host":
|
||||
@@ -71,7 +75,20 @@ func (cr *CELRequest) ResolveName(name string) (any, bool) {
|
||||
case "userAgent":
|
||||
return cr.UserAgent(), true
|
||||
case "path":
|
||||
return cr.URL.Path, true
|
||||
if cr.subRequestMode {
|
||||
original := cr.Header.Get("X-Original-Uri")
|
||||
if original == "" {
|
||||
original = cr.Header.Get("X-Forwarded-Uri")
|
||||
}
|
||||
if original != "" {
|
||||
u, err := url.ParseRequestURI(original)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return pathForPolicy(u.Path), true
|
||||
}
|
||||
}
|
||||
return pathForPolicy(cr.URL.Path), true
|
||||
case "query":
|
||||
return expressions.URLValues{Values: cr.URL.Query()}, true
|
||||
case "headers":
|
||||
@@ -83,6 +100,6 @@ func (cr *CELRequest) ResolveName(name string) (any, bool) {
|
||||
case "load_15m":
|
||||
return expressions.Load15(), true
|
||||
default:
|
||||
return nil, false
|
||||
return expressions.ResolveBotVariable(name, cr.Request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/TecharoHQ/anubis/internal/dns"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/TecharoHQ/anubis/lib/store/memory"
|
||||
"github.com/neilotoole/slogt/v2"
|
||||
)
|
||||
|
||||
func newTestDNS(t *testing.T) *dns.Dns {
|
||||
t.Helper()
|
||||
|
||||
ctx := t.Context()
|
||||
memStore := memory.New(ctx)
|
||||
cache := dns.NewDNSCache(300, 300, memStore)
|
||||
return dns.New(ctx, cache, slogt.New(t))
|
||||
}
|
||||
|
||||
func TestCELChecker_MapIterationWrappers(t *testing.T) {
|
||||
cfg := &config.ExpressionOrList{
|
||||
Expression: `headers.exists(k, k == "Accept") && query.exists(k, k == "format")`,
|
||||
}
|
||||
|
||||
checker, err := NewCELChecker(cfg, newTestDNS(t), false)
|
||||
if err != nil {
|
||||
t.Fatalf("creating CEL checker failed: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "https://example.com/?format=json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("making request failed: %v", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
got, err := checker.Check(req)
|
||||
if err != nil {
|
||||
t.Fatalf("checking expression failed: %v", err)
|
||||
}
|
||||
if !got {
|
||||
t.Fatal("expected expression to evaluate true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCELChecker_PathWithForwardedUri(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
expression string
|
||||
xForwardedUri string
|
||||
urlPath string
|
||||
subRequestMode bool
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "path matches X-Forwarded-Uri in subrequest mode",
|
||||
expression: `path.startsWith("/admin")`,
|
||||
xForwardedUri: "/admin/secret",
|
||||
urlPath: "/.within.website/x/cmd/anubis/api/check",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "path with query string",
|
||||
expression: `path.startsWith("/api/secret")`,
|
||||
xForwardedUri: "/api/secret?token=abc",
|
||||
urlPath: "/.within.website/x/cmd/anubis/api/check",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "path falls back to url path when no header",
|
||||
expression: `path == "/public/page"`,
|
||||
urlPath: "/public/page",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "non-subrequest mode ignores X-Forwarded-Uri",
|
||||
expression: `path.startsWith("/admin")`,
|
||||
xForwardedUri: "/admin/secret",
|
||||
urlPath: "/public/page",
|
||||
subRequestMode: false,
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := &config.ExpressionOrList{
|
||||
Expression: tt.expression,
|
||||
}
|
||||
checker, err := NewCELChecker(cfg, newTestDNS(t), tt.subRequestMode)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCELChecker() error: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://example.com"+tt.urlPath, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("http.NewRequest: %v", err)
|
||||
}
|
||||
|
||||
if tt.xForwardedUri != "" {
|
||||
req.Header.Set("X-Forwarded-Uri", tt.xForwardedUri)
|
||||
}
|
||||
|
||||
got, err := checker.Check(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Check() error: %v", err)
|
||||
}
|
||||
|
||||
if got != tt.want {
|
||||
t.Errorf("Check() = %v, want %v (subRequestMode=%v, urlPath=%q, X-Forwarded-Uri=%q)",
|
||||
got, tt.want, tt.subRequestMode, tt.urlPath, tt.xForwardedUri)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCELOriginalURIPathExcludesQuery(t *testing.T) {
|
||||
for _, key := range []string{"X-Original-Uri", "X-Forwarded-Uri"} {
|
||||
r, _ := http.NewRequest("GET", "http://example.com/api/check", nil)
|
||||
r.Header.Set(key, "/admin/secret?token=abc")
|
||||
cc, err := NewCELChecker(&config.ExpressionOrList{Expression: `path == "/admin/secret"`}, newTestDNS(t), true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := cc.Check(r); err != nil || !got {
|
||||
t.Errorf("%s path match=%v err=%v", key, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCELMalformedOriginalURI(t *testing.T) {
|
||||
cc, err := NewCELChecker(&config.ExpressionOrList{Expression: `path == "/admin"`}, newTestDNS(t), true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := http.NewRequest("GET", "http://example.com/api/check", nil)
|
||||
r.Header.Set("X-Original-Uri", "%invalid")
|
||||
if got, err := cc.Check(r); got || err == nil {
|
||||
t.Fatalf("malformed original URI match=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
+74
-14
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
@@ -41,9 +42,9 @@ func NewRemoteAddrChecker(cidrs []string) (checker.Impl, error) {
|
||||
}
|
||||
|
||||
func (rac *RemoteAddrChecker) Check(r *http.Request) (bool, error) {
|
||||
host := r.Header.Get("X-Real-Ip")
|
||||
host := r.Header.Get("X-Real-IP")
|
||||
if host == "" {
|
||||
return false, fmt.Errorf("%w: header X-Real-Ip is not set", ErrMisconfiguration)
|
||||
return false, fmt.Errorf("%w: header X-Real-IP is not set", ErrMisconfiguration)
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddr(host)
|
||||
@@ -82,7 +83,13 @@ func NewHeaderMatchesChecker(header, rexStr string) (checker.Impl, error) {
|
||||
}
|
||||
|
||||
func (hmc *HeaderMatchesChecker) Check(r *http.Request) (bool, error) {
|
||||
if hmc.regexp.MatchString(r.Header.Get(hmc.header)) {
|
||||
values := r.Header.Values(hmc.header)
|
||||
for _, value := range values {
|
||||
if hmc.regexp.MatchString(value) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
if hmc.regexp.MatchString(strings.Join(values, ",")) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -94,27 +101,36 @@ func (hmc *HeaderMatchesChecker) Hash() string {
|
||||
}
|
||||
|
||||
type PathChecker struct {
|
||||
regexp *regexp.Regexp
|
||||
hash string
|
||||
regexp *regexp.Regexp
|
||||
hash string
|
||||
subRequestMode bool
|
||||
}
|
||||
|
||||
func NewPathChecker(rexStr string) (checker.Impl, error) {
|
||||
func NewPathChecker(rexStr string, subrequestMode bool) (checker.Impl, error) {
|
||||
rex, err := regexp.Compile(strings.TrimSpace(rexStr))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: regex %s failed parse: %w", ErrMisconfiguration, rexStr, err)
|
||||
}
|
||||
return &PathChecker{rex, internal.FastHash(rexStr)}, nil
|
||||
return &PathChecker{rex, internal.FastHash(rexStr), subrequestMode}, nil
|
||||
}
|
||||
|
||||
func (pc *PathChecker) Check(r *http.Request) (bool, error) {
|
||||
originalUrl := r.Header.Get("X-Original-URI")
|
||||
if originalUrl != "" {
|
||||
if pc.regexp.MatchString(originalUrl) {
|
||||
return true, nil
|
||||
if pc.subRequestMode {
|
||||
originalUrl := r.Header.Get("X-Original-Uri")
|
||||
if originalUrl == "" {
|
||||
originalUrl = r.Header.Get("X-Forwarded-Uri")
|
||||
}
|
||||
if originalUrl != "" {
|
||||
if parsed, err := url.ParseRequestURI(originalUrl); err == nil {
|
||||
originalUrl = parsed.Path
|
||||
}
|
||||
if pc.regexp.MatchString(pathForPolicy(originalUrl)) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if pc.regexp.MatchString(r.URL.Path) {
|
||||
if pc.regexp.MatchString(pathForPolicy(r.URL.Path)) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -134,8 +150,10 @@ type headerExistsChecker struct {
|
||||
}
|
||||
|
||||
func (hec headerExistsChecker) Check(r *http.Request) (bool, error) {
|
||||
if r.Header.Get(hec.header) != "" {
|
||||
return true, nil
|
||||
for _, value := range r.Header.Values(hec.header) {
|
||||
if value != "" {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
@@ -170,3 +188,45 @@ func NewHeadersChecker(headermap map[string]string) (checker.Impl, error) {
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (pc *ParsedConfig) ValidateRequestPath(r *http.Request) error {
|
||||
paths := []string{r.URL.Path}
|
||||
if pc.SubrequestMode {
|
||||
original := r.Header.Get("X-Original-Uri")
|
||||
if original == "" {
|
||||
original = r.Header.Get("X-Forwarded-Uri")
|
||||
}
|
||||
if original != "" {
|
||||
u, err := url.ParseRequestURI(original)
|
||||
if err != nil {
|
||||
return ErrMisconfiguration
|
||||
}
|
||||
paths = append(paths, u.Path)
|
||||
}
|
||||
}
|
||||
for _, p := range paths {
|
||||
for segment := range strings.SplitSeq(p, "/") {
|
||||
if segment == "." || segment == ".." {
|
||||
return ErrMisconfiguration
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pathForPolicy collapses repeated slashes for rule evaluation without changing
|
||||
// the path forwarded to the origin. Dot segments are rejected separately.
|
||||
func pathForPolicy(p string) string {
|
||||
if !strings.Contains(p, "//") {
|
||||
return p
|
||||
}
|
||||
var result strings.Builder
|
||||
result.Grow(len(p))
|
||||
for i := range len(p) {
|
||||
if p[i] == '/' && i > 0 && p[i-1] == '/' {
|
||||
continue
|
||||
}
|
||||
result.WriteByte(p[i])
|
||||
}
|
||||
return result.String()
|
||||
}
|
||||
+224
-3
@@ -82,7 +82,7 @@ func TestRemoteAddrChecker(t *testing.T) {
|
||||
}
|
||||
|
||||
if tt.ip != "" {
|
||||
r.Header.Add("X-Real-Ip", tt.ip)
|
||||
r.Header.Add("X-Real-IP", tt.ip)
|
||||
}
|
||||
|
||||
ok, err := rac.Check(r)
|
||||
@@ -272,8 +272,8 @@ func TestPathChecker_XOriginalURI(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create the PathChecker
|
||||
pc, err := NewPathChecker(tt.regex)
|
||||
// Create the PathChecker in subrequest mode so X-Original-URI is honored.
|
||||
pc, err := NewPathChecker(tt.regex, true)
|
||||
if err != nil {
|
||||
if !tt.expectError {
|
||||
t.Fatalf("NewPathChecker() unexpected error: %v", err)
|
||||
@@ -305,3 +305,224 @@ func TestPathChecker_XOriginalURI(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPathChecker_GHSA_6wcg_mqvh_fcvg is a regression test for
|
||||
// https://github.com/TecharoHQ/anubis/security/advisories/GHSA-6wcg-mqvh-fcvg.
|
||||
//
|
||||
// PR https://github.com/TecharoHQ/anubis/pull/1015 added the ability for
|
||||
// reverse proxies using Anubis in subrequest auth mode to look at the path
|
||||
// of a request as there are many rules in the wild that rely on checking
|
||||
// the path. This is how access to things like robots.txt or anything in the
|
||||
// .well-known directory is unaffected by Anubis.
|
||||
//
|
||||
// However this logic was also enabled for non-subrequest deployments of Anubis,
|
||||
// meaning that a specially crafted request could include a /.well-known/
|
||||
// path in it and then get around Anubis with little effort.
|
||||
//
|
||||
// This fix gates the logic behind a new plumbed variable named subrequestMode
|
||||
// that only fires when Anubis is running in subrequest auth mode. This
|
||||
// properly contains that workaround so that the logic does not fire in
|
||||
// most deployments.
|
||||
func TestPathChecker_GHSA_6wcg_mqvh_fcvg(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
regex string
|
||||
urlPath string
|
||||
xOriginalURI string
|
||||
subRequestMode bool
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "default mode ignores spoofed X-Original-URI when real path matches",
|
||||
regex: "^/admin/.*",
|
||||
urlPath: "/admin/secret",
|
||||
xOriginalURI: "/public/index",
|
||||
subRequestMode: false,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "default mode ignores spoofed X-Original-URI when real path does not match",
|
||||
regex: "^/admin/.*",
|
||||
urlPath: "/public/index",
|
||||
xOriginalURI: "/admin/secret",
|
||||
subRequestMode: false,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "default mode without X-Original-URI matches real path",
|
||||
regex: "^/admin/.*",
|
||||
urlPath: "/admin/dashboard",
|
||||
xOriginalURI: "",
|
||||
subRequestMode: false,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "subrequest mode honors X-Original-URI",
|
||||
regex: "^/admin/.*",
|
||||
urlPath: "/auth",
|
||||
xOriginalURI: "/admin/secret",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "subrequest mode falls back to URL.Path when X-Original-URI does not match",
|
||||
regex: "^/admin/.*",
|
||||
urlPath: "/admin/dashboard",
|
||||
xOriginalURI: "/public/index",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "subrequest mode with empty X-Original-URI uses URL.Path",
|
||||
regex: "^/admin/.*",
|
||||
urlPath: "/admin/dashboard",
|
||||
xOriginalURI: "",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pc, err := NewPathChecker(tt.regex, tt.subRequestMode)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPathChecker(%q, %v) returned error: %v", tt.regex, tt.subRequestMode, err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://example.com"+tt.urlPath, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("http.NewRequest: %v", err)
|
||||
}
|
||||
|
||||
if tt.xOriginalURI != "" {
|
||||
req.Header.Set("X-Original-Uri", tt.xOriginalURI)
|
||||
}
|
||||
|
||||
got, err := pc.Check(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Check() unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if got != tt.want {
|
||||
t.Errorf("Check() = %v, want %v (subRequestMode=%v, urlPath=%q, X-Original-URI=%q)",
|
||||
got, tt.want, tt.subRequestMode, tt.urlPath, tt.xOriginalURI)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathChecker_XForwardedUri(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
regex string
|
||||
xForwardedUri string
|
||||
xOriginalURI string
|
||||
urlPath string
|
||||
subRequestMode bool
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "X-Forwarded-Uri matches regex in subrequest mode",
|
||||
regex: "^/admin/.*",
|
||||
xForwardedUri: "/admin/users",
|
||||
urlPath: "/.within.website/x/cmd/anubis/api/check",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Uri with query string",
|
||||
regex: "^/admin/.*",
|
||||
xForwardedUri: "/admin/users?page=1",
|
||||
urlPath: "/.within.website/x/cmd/anubis/api/check",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "X-Original-URI takes priority over X-Forwarded-Uri",
|
||||
regex: "^/admin/.*",
|
||||
xForwardedUri: "/public/page",
|
||||
xOriginalURI: "/admin/users",
|
||||
urlPath: "/.within.website/x/cmd/anubis/api/check",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "falls back to X-Forwarded-Uri when no X-Original-URI",
|
||||
regex: "^/admin/.*",
|
||||
xForwardedUri: "/admin/dashboard",
|
||||
urlPath: "/.within.website/x/cmd/anubis/api/check",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "neither header matches, url path matches",
|
||||
regex: "^/public/.*",
|
||||
xForwardedUri: "/admin/users",
|
||||
urlPath: "/public/page",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "nothing matches",
|
||||
regex: "^/admin/.*",
|
||||
xForwardedUri: "/public/page",
|
||||
urlPath: "/.within.website/x/cmd/anubis/api/check",
|
||||
subRequestMode: true,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "non-subrequest mode ignores X-Forwarded-Uri",
|
||||
regex: "^/admin/.*",
|
||||
xForwardedUri: "/admin/users",
|
||||
urlPath: "/public/page",
|
||||
subRequestMode: false,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "non-subrequest mode uses url path",
|
||||
regex: "^/admin/.*",
|
||||
xForwardedUri: "/public/page",
|
||||
urlPath: "/admin/secret",
|
||||
subRequestMode: false,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "empty X-Forwarded-Uri falls back to url path",
|
||||
regex: "^/check$",
|
||||
urlPath: "/check",
|
||||
subRequestMode: true,
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pc, err := NewPathChecker(tt.regex, tt.subRequestMode)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPathChecker(%q, %v) returned error: %v", tt.regex, tt.subRequestMode, err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://example.com"+tt.urlPath, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("http.NewRequest: %v", err)
|
||||
}
|
||||
|
||||
if tt.xForwardedUri != "" {
|
||||
req.Header.Set("X-Forwarded-Uri", tt.xForwardedUri)
|
||||
}
|
||||
if tt.xOriginalURI != "" {
|
||||
req.Header.Set("X-Original-Uri", tt.xOriginalURI)
|
||||
}
|
||||
|
||||
got, err := pc.Check(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Check() unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if got != tt.want {
|
||||
t.Errorf("Check() = %v, want %v (subRequestMode=%v, urlPath=%q, X-Forwarded-Uri=%q, X-Original-URI=%q)",
|
||||
got, tt.want, tt.subRequestMode, tt.urlPath, tt.xForwardedUri, tt.xOriginalURI)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"math/rand/v2"
|
||||
"strings"
|
||||
|
||||
"cel.dev/cel-go/cel"
|
||||
"cel.dev/cel-go/common/types"
|
||||
"cel.dev/cel-go/common/types/ref"
|
||||
"cel.dev/cel-go/common/types/traits"
|
||||
"cel.dev/cel-go/ext"
|
||||
"github.com/TecharoHQ/anubis/internal/dns"
|
||||
"github.com/google/cel-go/cel"
|
||||
"github.com/google/cel-go/common/types"
|
||||
"github.com/google/cel-go/common/types/ref"
|
||||
"github.com/google/cel-go/common/types/traits"
|
||||
"github.com/google/cel-go/ext"
|
||||
)
|
||||
|
||||
// BotEnvironment creates a new CEL environment, this is the set of
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
// Anubis can fail loudly and early when something is invalid instead
|
||||
// of blowing up at runtime.
|
||||
func BotEnvironment(dnsObj *dns.Dns) (*cel.Env, error) {
|
||||
return New(
|
||||
opts := []cel.EnvOption{
|
||||
// Variables exposed to CEL programs:
|
||||
cel.Variable("remoteAddress", cel.StringType),
|
||||
cel.Variable("contentLength", cel.IntType),
|
||||
@@ -191,7 +191,9 @@ func BotEnvironment(dnsObj *dns.Dns) (*cel.Env, error) {
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return New(append(opts, getBotVariables()...)...)
|
||||
}
|
||||
|
||||
// NewThreshold creates a new CEL environment for threshold checking.
|
||||
@@ -222,7 +224,16 @@ func New(opts ...cel.EnvOption) (*cel.Env, error) {
|
||||
return types.ValOrErr(val, "value is not an integer, but is %T", val)
|
||||
}
|
||||
|
||||
return types.Int(rand.IntN(int(n)))
|
||||
if n <= 0 {
|
||||
return types.NewErr("randInt bound must be positive, got %d", int64(n))
|
||||
}
|
||||
|
||||
bound := int(n)
|
||||
if types.Int(bound) != n {
|
||||
return types.NewErr("randInt bound %d overflows platform int", int64(n))
|
||||
}
|
||||
|
||||
return types.Int(rand.IntN(bound))
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -7,22 +7,24 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cel.dev/cel-go/cel"
|
||||
"cel.dev/cel-go/common/types"
|
||||
"cel.dev/cel-go/common/types/ref"
|
||||
"github.com/TecharoHQ/anubis/internal/dns"
|
||||
"github.com/TecharoHQ/anubis/lib/store/memory"
|
||||
"github.com/google/cel-go/common/types"
|
||||
"github.com/google/cel-go/common/types/ref"
|
||||
"github.com/neilotoole/slogt/v2"
|
||||
)
|
||||
|
||||
// newTestDNS is a helper function to create a new Dns object with an in-memory cache for testing.
|
||||
func newTestDNS(forwardTTL int, reverseTTL int) *dns.Dns {
|
||||
func newTestDNS(t *testing.T, forwardTTL int, reverseTTL int) *dns.Dns {
|
||||
ctx := context.Background()
|
||||
memStore := memory.New(ctx)
|
||||
cache := dns.NewDNSCache(forwardTTL, reverseTTL, memStore)
|
||||
return dns.New(ctx, cache)
|
||||
return dns.New(ctx, cache, slogt.New(t))
|
||||
}
|
||||
|
||||
func TestBotEnvironment(t *testing.T) {
|
||||
dnsObj := newTestDNS(300, 300)
|
||||
dnsObj := newTestDNS(t, 300, 300)
|
||||
env, err := BotEnvironment(dnsObj)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create bot environment: %v", err)
|
||||
@@ -103,7 +105,7 @@ func TestBotEnvironment(t *testing.T) {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(map[string]interface{}{
|
||||
result, _, err := prog.Eval(map[string]any{
|
||||
"headers": tt.headers,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -168,7 +170,7 @@ func TestBotEnvironment(t *testing.T) {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(map[string]interface{}{
|
||||
result, _, err := prog.Eval(map[string]any{
|
||||
"path": tt.path,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -280,7 +282,7 @@ func TestBotEnvironment(t *testing.T) {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(map[string]interface{}{})
|
||||
result, _, err := prog.Eval(map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to evaluate expression %q: %v", tt.expression, err)
|
||||
}
|
||||
@@ -359,7 +361,7 @@ func TestBotEnvironment(t *testing.T) {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(map[string]interface{}{})
|
||||
result, _, err := prog.Eval(map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to evaluate expression %q: %v", tt.expression, err)
|
||||
}
|
||||
@@ -421,7 +423,7 @@ func TestBotEnvironment(t *testing.T) {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(map[string]interface{}{})
|
||||
result, _, err := prog.Eval(map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to evaluate expression %q: %v", tt.expression, err)
|
||||
}
|
||||
@@ -514,7 +516,7 @@ func TestBotEnvironment(t *testing.T) {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(map[string]interface{}{})
|
||||
result, _, err := prog.Eval(map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to evaluate expression %q: %v", tt.expression, err)
|
||||
}
|
||||
@@ -572,7 +574,7 @@ func TestBotEnvironment(t *testing.T) {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(map[string]interface{}{})
|
||||
result, _, err := prog.Eval(map[string]any{})
|
||||
if tt.evalError {
|
||||
if err == nil {
|
||||
t.Errorf("%s: expected an evaluation error, but got none", tt.description)
|
||||
@@ -598,7 +600,7 @@ func TestThresholdEnvironment(t *testing.T) {
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
variables map[string]interface{}
|
||||
variables map[string]any
|
||||
name string
|
||||
expression string
|
||||
description string
|
||||
@@ -608,7 +610,7 @@ func TestThresholdEnvironment(t *testing.T) {
|
||||
{
|
||||
name: "weight-variable-available",
|
||||
expression: `weight > 100`,
|
||||
variables: map[string]interface{}{"weight": 150},
|
||||
variables: map[string]any{"weight": 150},
|
||||
expected: types.Bool(true),
|
||||
description: "should support weight variable in expressions",
|
||||
shouldCompile: true,
|
||||
@@ -616,7 +618,7 @@ func TestThresholdEnvironment(t *testing.T) {
|
||||
{
|
||||
name: "weight-variable-false-case",
|
||||
expression: `weight > 100`,
|
||||
variables: map[string]interface{}{"weight": 50},
|
||||
variables: map[string]any{"weight": 50},
|
||||
expected: types.Bool(false),
|
||||
description: "should correctly evaluate weight comparisons",
|
||||
shouldCompile: true,
|
||||
@@ -624,7 +626,7 @@ func TestThresholdEnvironment(t *testing.T) {
|
||||
{
|
||||
name: "missingHeader-not-available",
|
||||
expression: `missingHeader(headers, "Test")`,
|
||||
variables: map[string]interface{}{},
|
||||
variables: map[string]any{},
|
||||
expected: types.Bool(false), // not used
|
||||
description: "should not have missingHeader function available",
|
||||
shouldCompile: false,
|
||||
@@ -667,7 +669,7 @@ func TestNewEnvironment(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
expression string
|
||||
variables map[string]interface{}
|
||||
variables map[string]any
|
||||
expectBool *bool // nil if we just want to test compilation or non-bool result
|
||||
description string
|
||||
shouldCompile bool
|
||||
@@ -675,7 +677,7 @@ func TestNewEnvironment(t *testing.T) {
|
||||
{
|
||||
name: "randInt-function-compilation",
|
||||
expression: `randInt(10)`,
|
||||
variables: map[string]interface{}{},
|
||||
variables: map[string]any{},
|
||||
expectBool: nil, // Don't check result, just compilation
|
||||
description: "should compile randInt function",
|
||||
shouldCompile: true,
|
||||
@@ -683,15 +685,23 @@ func TestNewEnvironment(t *testing.T) {
|
||||
{
|
||||
name: "randInt-range-validation",
|
||||
expression: `randInt(10) >= 0 && randInt(10) < 10`,
|
||||
variables: map[string]interface{}{},
|
||||
variables: map[string]any{},
|
||||
expectBool: boolPtr(true),
|
||||
description: "should return values in correct range",
|
||||
shouldCompile: true,
|
||||
},
|
||||
{
|
||||
name: "randInt-large-bound",
|
||||
expression: `randInt(2147483647) >= 0`,
|
||||
variables: map[string]any{},
|
||||
expectBool: boolPtr(true),
|
||||
description: "should accept int32-max bounds without overflow",
|
||||
shouldCompile: true,
|
||||
},
|
||||
{
|
||||
name: "strings-extension-size",
|
||||
expression: `"hello".size() == 5`,
|
||||
variables: map[string]interface{}{},
|
||||
variables: map[string]any{},
|
||||
expectBool: boolPtr(true),
|
||||
description: "should support string extension functions",
|
||||
shouldCompile: true,
|
||||
@@ -699,7 +709,7 @@ func TestNewEnvironment(t *testing.T) {
|
||||
{
|
||||
name: "strings-extension-contains",
|
||||
expression: `"hello world".contains("world")`,
|
||||
variables: map[string]interface{}{},
|
||||
variables: map[string]any{},
|
||||
expectBool: boolPtr(true),
|
||||
description: "should support string contains function",
|
||||
shouldCompile: true,
|
||||
@@ -707,7 +717,7 @@ func TestNewEnvironment(t *testing.T) {
|
||||
{
|
||||
name: "strings-extension-startsWith",
|
||||
expression: `"hello world".startsWith("hello")`,
|
||||
variables: map[string]interface{}{},
|
||||
variables: map[string]any{},
|
||||
expectBool: boolPtr(true),
|
||||
description: "should support string startsWith function",
|
||||
shouldCompile: true,
|
||||
@@ -750,3 +760,65 @@ func TestNewEnvironment(t *testing.T) {
|
||||
func boolPtr(b bool) *bool {
|
||||
return &b
|
||||
}
|
||||
|
||||
func TestRandIntInvalidBounds(t *testing.T) {
|
||||
env, err := New(cel.Variable("contentLength", cel.IntType))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create environment: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
expression string
|
||||
variables map[string]any
|
||||
wantErrText string
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "zero-bound-literal",
|
||||
expression: `randInt(0)`,
|
||||
variables: map[string]any{},
|
||||
wantErrText: "randInt bound must be positive",
|
||||
description: "randInt(0) should return a CEL error, not panic",
|
||||
},
|
||||
{
|
||||
name: "negative-bound-literal",
|
||||
expression: `randInt(-5)`,
|
||||
variables: map[string]any{},
|
||||
wantErrText: "randInt bound must be positive",
|
||||
description: "randInt(-5) should return a CEL error, not panic",
|
||||
},
|
||||
{
|
||||
name: "zero-bound-from-variable",
|
||||
expression: `randInt(contentLength)`,
|
||||
variables: map[string]any{"contentLength": 0},
|
||||
wantErrText: "randInt bound must be positive",
|
||||
description: "attacker-controlled zero contentLength should error gracefully",
|
||||
},
|
||||
{
|
||||
name: "negative-bound-from-variable",
|
||||
expression: `randInt(contentLength)`,
|
||||
variables: map[string]any{"contentLength": -1},
|
||||
wantErrText: "randInt bound must be positive",
|
||||
description: "attacker-controlled negative contentLength should error gracefully",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
prog, err := Compile(env, tt.expression)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to compile expression %q: %v", tt.expression, err)
|
||||
}
|
||||
|
||||
result, _, err := prog.Eval(tt.variables)
|
||||
if err == nil {
|
||||
t.Fatalf("%s: expected an evaluation error, got result %v", tt.description, result)
|
||||
}
|
||||
|
||||
if !strings.Contains(err.Error(), tt.wantErrText) {
|
||||
t.Errorf("%s: expected error containing %q, got %q", tt.description, tt.wantErrText, err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/google/cel-go/common/types"
|
||||
"github.com/google/cel-go/common/types/ref"
|
||||
"github.com/google/cel-go/common/types/traits"
|
||||
"cel.dev/cel-go/common/types"
|
||||
"cel.dev/cel-go/common/types/ref"
|
||||
"cel.dev/cel-go/common/types/traits"
|
||||
)
|
||||
|
||||
// HTTPHeaders is a type wrapper to expose HTTP headers into CEL programs.
|
||||
@@ -46,11 +46,11 @@ func (h HTTPHeaders) Find(key ref.Val) (ref.Val, bool) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if _, ok := h.Header[string(k)]; !ok {
|
||||
if _, ok := h.Header[http.CanonicalHeaderKey(string(k))]; !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return types.String(strings.Join(h.Header.Values(string(k)), ",")), true
|
||||
return types.String(strings.Join(h.Values(string(k)), ",")), true
|
||||
}
|
||||
|
||||
func (h HTTPHeaders) Contains(key ref.Val) ref.Val {
|
||||
@@ -66,7 +66,9 @@ func (h HTTPHeaders) Get(key ref.Val) ref.Val {
|
||||
return result
|
||||
}
|
||||
|
||||
func (h HTTPHeaders) Iterator() traits.Iterator { panic("TODO(Xe): implement me") }
|
||||
func (h HTTPHeaders) Iterator() traits.Iterator {
|
||||
return newMapIterator(h.Header)
|
||||
}
|
||||
|
||||
func (h HTTPHeaders) IsZeroValue() bool {
|
||||
return len(h.Header) == 0
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/google/cel-go/common/types"
|
||||
"cel.dev/cel-go/common/types"
|
||||
)
|
||||
|
||||
func TestHTTPHeaders(t *testing.T) {
|
||||
|
||||
@@ -46,7 +46,7 @@ var (
|
||||
)
|
||||
|
||||
func init() {
|
||||
globalLoadAvg = &loadAvg{}
|
||||
globalLoadAvg = &loadAvg{data: &load.AvgStat{}}
|
||||
go globalLoadAvg.updateThread(context.Background())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package expressions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"maps"
|
||||
"reflect"
|
||||
"slices"
|
||||
|
||||
"cel.dev/cel-go/common/types"
|
||||
"cel.dev/cel-go/common/types/ref"
|
||||
"cel.dev/cel-go/common/types/traits"
|
||||
)
|
||||
|
||||
var ErrNotImplemented = errors.New("expressions: not implemented")
|
||||
|
||||
type stringSliceIterator struct {
|
||||
keys []string
|
||||
idx int
|
||||
}
|
||||
|
||||
func (s *stringSliceIterator) Value() any {
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *stringSliceIterator) ConvertToNative(typeDesc reflect.Type) (any, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
func (s *stringSliceIterator) ConvertToType(typeValue ref.Type) ref.Val {
|
||||
return types.NewErr("can't convert from %q to %q", types.IteratorType, typeValue)
|
||||
}
|
||||
|
||||
func (s *stringSliceIterator) Equal(other ref.Val) ref.Val {
|
||||
return types.NewErr("can't compare %q to %q", types.IteratorType, other.Type())
|
||||
}
|
||||
|
||||
func (s *stringSliceIterator) Type() ref.Type {
|
||||
return types.IteratorType
|
||||
}
|
||||
|
||||
func (s *stringSliceIterator) HasNext() ref.Val {
|
||||
return types.Bool(s.idx < len(s.keys))
|
||||
}
|
||||
|
||||
func (s *stringSliceIterator) Next() ref.Val {
|
||||
if s.HasNext() != types.True {
|
||||
return nil
|
||||
}
|
||||
|
||||
val := s.keys[s.idx]
|
||||
s.idx++
|
||||
return types.String(val)
|
||||
}
|
||||
|
||||
func newMapIterator(m map[string][]string) traits.Iterator {
|
||||
return &stringSliceIterator{
|
||||
keys: slices.Collect(maps.Keys(m)),
|
||||
idx: 0,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package expressions
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"cel.dev/cel-go/cel"
|
||||
)
|
||||
|
||||
// BotVariableResolver returns the value of a registered bot variable for
|
||||
// a request. This is how extensions can add additional variables to bot
|
||||
// contexts.
|
||||
type BotVariableResolver func(r *http.Request) (any, bool)
|
||||
|
||||
type botVariable struct {
|
||||
name string
|
||||
typ *cel.Type
|
||||
resolve BotVariableResolver
|
||||
}
|
||||
|
||||
var (
|
||||
botVariables = map[string]botVariable{}
|
||||
|
||||
// builtinBotVariables is the list of variables that the CEL environment
|
||||
// already defines. This is here so that extensions can't add a variable
|
||||
// that already exists.
|
||||
builtinBotVariables = map[string]struct{}{
|
||||
"remoteAddress": {},
|
||||
"contentLength": {},
|
||||
"host": {},
|
||||
"method": {},
|
||||
"userAgent": {},
|
||||
"path": {},
|
||||
"query": {},
|
||||
"headers": {},
|
||||
"load_1m": {},
|
||||
"load_5m": {},
|
||||
"load_15m": {},
|
||||
}
|
||||
)
|
||||
|
||||
// RegisterBotVariable adds a variable to the bot rule environment.
|
||||
//
|
||||
// This function assumes it's being called from an init() hook at the beginning
|
||||
// of program execution. Any attempt to call it after Anubis has started can
|
||||
// and will cause undefined behaviour up to and including a crash.
|
||||
//
|
||||
// If the bot variable being registered conflicts with a built-in bot variable,
|
||||
// this function will panic and take out the program early in its lifecycle. The
|
||||
// hope is that this will fire when tests are run, which should prevent errant
|
||||
// unfeatures from being shipped.
|
||||
func RegisterBotVariable(name string, typ *cel.Type, resolve BotVariableResolver) {
|
||||
if _, ok := builtinBotVariables[name]; ok {
|
||||
log.Panicf("cannot register bot variable %q, it's built in", name)
|
||||
}
|
||||
|
||||
if _, ok := botVariables[name]; ok {
|
||||
log.Panicf("cannot register bot variable %q, it's already registered", name)
|
||||
}
|
||||
|
||||
botVariables[name] = botVariable{name: name, typ: typ, resolve: resolve}
|
||||
}
|
||||
|
||||
// ResolveBotVariable resolves a bot variable that was registered with
|
||||
// [RegisterBotVariable], calling the arbitrary [BotVariableResolver] and
|
||||
// returning the values to the caller.
|
||||
func ResolveBotVariable(name string, r *http.Request) (any, bool) {
|
||||
v, ok := botVariables[name]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return v.resolve(r)
|
||||
}
|
||||
|
||||
// getBotVariables returns the bot variables as a []cel.EnvOption for building
|
||||
// CEL checkers.
|
||||
func getBotVariables() []cel.EnvOption {
|
||||
result := make([]cel.EnvOption, 0, len(botVariables))
|
||||
|
||||
for _, v := range botVariables {
|
||||
result = append(result, cel.Variable(v.name, v.typ))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package expressions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"cel.dev/cel-go/cel"
|
||||
"cel.dev/cel-go/common/types"
|
||||
)
|
||||
|
||||
type registryResolver struct{ r *http.Request }
|
||||
|
||||
func (rr registryResolver) ResolveName(name string) (any, bool) {
|
||||
return ResolveBotVariable(name, rr.r)
|
||||
}
|
||||
|
||||
func (ra registryResolver) Parent() cel.Activation { return nil }
|
||||
|
||||
func TestRegisterBotVariable(t *testing.T) {
|
||||
RegisterBotVariable("registryTestScore", cel.IntType, func(r *http.Request) (any, bool) {
|
||||
sc := r.Header.Get("X-Score")
|
||||
if sc == "" {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result, err := strconv.Atoi(sc)
|
||||
if err != nil {
|
||||
panic("score is not a number")
|
||||
}
|
||||
|
||||
return result, true
|
||||
})
|
||||
|
||||
env, err := BotEnvironment(newTestDNS(t, 300, 300))
|
||||
if err != nil {
|
||||
t.Fatalf("can't create bot environment: %v", err)
|
||||
}
|
||||
|
||||
t.Run("variable exists in compile", func(t *testing.T) {
|
||||
if _, err := Compile(env, `registryTestScore >= 3`); err != nil {
|
||||
t.Fatalf("cannot compile environment with added variable (is it not an int?): %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("variable is not a string", func(t *testing.T) {
|
||||
if _, err := Compile(env, `registryTestScore == "taco bell"`); err == nil {
|
||||
t.Fatalf("cannot compile program treating this as a string (is the type wrong?)")
|
||||
}
|
||||
})
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
score int
|
||||
want bool
|
||||
wantErr bool
|
||||
}{
|
||||
{"matches", 3, true, false},
|
||||
{"does not match", 2, false, false},
|
||||
{"no value", 0, false, true},
|
||||
} {
|
||||
t.Run("case/"+tt.name, func(t *testing.T) {
|
||||
const src = `registryTestScore >= 3`
|
||||
prog, err := Compile(env, src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
|
||||
if tt.score != 0 {
|
||||
r.Header.Set("X-Score", fmt.Sprint(tt.score))
|
||||
}
|
||||
|
||||
got, _, err := prog.ContextEval(t.Context(), registryResolver{r})
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("wanted error: %v, got error: %v", tt.wantErr, err)
|
||||
}
|
||||
if tt.wantErr {
|
||||
return
|
||||
}
|
||||
|
||||
if got != types.Bool(tt.want) {
|
||||
t.Errorf("wanted %v, got: %v", tt.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("duplicate reg panics", func(t *testing.T) {
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("second registration did not panic")
|
||||
}
|
||||
}()
|
||||
RegisterBotVariable("registryTestScore", cel.IntType, nil)
|
||||
})
|
||||
|
||||
t.Run("unknown variable does not resolve", func(t *testing.T) {
|
||||
if _, ok := ResolveBotVariable("registryTestMissing", httptest.NewRequest(http.MethodGet, "/", nil)); ok {
|
||||
t.Error("unregistered variable resolved")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,18 +1,15 @@
|
||||
package expressions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/google/cel-go/common/types"
|
||||
"github.com/google/cel-go/common/types/ref"
|
||||
"github.com/google/cel-go/common/types/traits"
|
||||
"cel.dev/cel-go/common/types"
|
||||
"cel.dev/cel-go/common/types/ref"
|
||||
"cel.dev/cel-go/common/types/traits"
|
||||
)
|
||||
|
||||
var ErrNotImplemented = errors.New("expressions: not implemented")
|
||||
|
||||
// URLValues is a type wrapper to expose url.Values into CEL programs.
|
||||
type URLValues struct {
|
||||
url.Values
|
||||
@@ -69,7 +66,9 @@ func (u URLValues) Get(key ref.Val) ref.Val {
|
||||
return result
|
||||
}
|
||||
|
||||
func (u URLValues) Iterator() traits.Iterator { panic("TODO(Xe): implement me") }
|
||||
func (u URLValues) Iterator() traits.Iterator {
|
||||
return newMapIterator(u.Values)
|
||||
}
|
||||
|
||||
func (u URLValues) IsZeroValue() bool {
|
||||
return len(u.Values) == 0
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/google/cel-go/common/types"
|
||||
"cel.dev/cel-go/common/types"
|
||||
)
|
||||
|
||||
func TestURLValues(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
)
|
||||
|
||||
func TestHeaderRulesReadAllValues(t *testing.T) {
|
||||
r := httptest.NewRequest("GET", "http://example.com/", nil)
|
||||
r.Header.Add("X-Test", "benign")
|
||||
r.Header.Add("X-Test", "evil")
|
||||
c, err := NewHeaderMatchesChecker("x-test", "evil")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := c.Check(r); err != nil || !got {
|
||||
t.Fatalf("regex match=%v err=%v", got, err)
|
||||
}
|
||||
cel, err := NewCELChecker(&config.ExpressionOrList{Expression: `"x-test" in headers && headers["x-test"] == "benign,evil"`}, newTestDNS(t), false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := cel.Check(r); err != nil || !got {
|
||||
t.Fatalf("CEL match=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnchoredHeaderRulesReadEachValue(t *testing.T) {
|
||||
for _, values := range [][]string{{"benign", "evil"}, {"evil", "benign"}} {
|
||||
r := httptest.NewRequest("GET", "http://example.com/", nil)
|
||||
r.Header["X-Test"] = values
|
||||
c, err := NewHeaderMatchesChecker("X-Test", "^evil$")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := c.Check(r); err != nil || !got {
|
||||
t.Errorf("values=%q match=%v err=%v", values, got, err)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest("GET", "http://example.com/", nil)
|
||||
r.Header["X-Test"] = []string{"", ""}
|
||||
if got, _ := NewHeaderExistsChecker("X-Test").Check(r); got {
|
||||
t.Fatal("empty values treated as present")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
)
|
||||
|
||||
func TestPolicyRejectsAmbiguousPaths(t *testing.T) {
|
||||
for _, p := range []string{"/foo/%2e%2e/admin/secret", "/admin/./secret", "/public//../admin", "/admin//./secret"} {
|
||||
r := httptest.NewRequest("GET", "http://example.com"+p, nil)
|
||||
cfg := &ParsedConfig{}
|
||||
if cfg.ValidateRequestPath(r) == nil {
|
||||
t.Errorf("accepted %q", p)
|
||||
}
|
||||
}
|
||||
for _, p := range []string{"/", "/admin/", "/admin/secret", "/wiki//bin", "//admin/secret", "/wiki///", "/admin%2F%2F/secret"} {
|
||||
if err := (&ParsedConfig{}).ValidateRequestPath(httptest.NewRequest("GET", "http://example.com"+p, nil)); err != nil {
|
||||
t.Errorf("rejected %q: %v", p, err)
|
||||
}
|
||||
}
|
||||
for _, header := range []string{"X-Original-Uri", "X-Forwarded-Uri"} {
|
||||
for _, p := range []string{"/public/../admin", "/public//%2e%2e/admin", "/admin//%2e/secret", "%invalid"} {
|
||||
r := httptest.NewRequest("GET", "http://example.com/api/check", nil)
|
||||
r.Header.Set(header, p)
|
||||
if (&ParsedConfig{SubrequestMode: true}).ValidateRequestPath(r) == nil {
|
||||
t.Errorf("accepted %s URI %q", header, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepeatedSlashesInPathRules(t *testing.T) {
|
||||
for _, target := range []string{"//admin/secret", "/admin//secret", "/admin%2F%2F/secret"} {
|
||||
for _, header := range []string{"", "X-Original-Uri", "X-Forwarded-Uri"} {
|
||||
t.Run(target+header, func(t *testing.T) {
|
||||
r := httptest.NewRequest("GET", "http://example.com"+target, nil)
|
||||
if header != "" {
|
||||
r = httptest.NewRequest("GET", "http://example.com/api/check", nil)
|
||||
r.Header.Set(header, target+"?next=/public")
|
||||
}
|
||||
if err := (&ParsedConfig{SubrequestMode: header != ""}).ValidateRequestPath(r); err != nil {
|
||||
t.Fatalf("rejected repeated slashes: %v", err)
|
||||
}
|
||||
pathBefore, escapedBefore, uriBefore := r.URL.Path, r.URL.EscapedPath(), r.RequestURI
|
||||
checker, err := NewPathChecker(`^/admin/secret$`, header != "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if matched, err := checker.Check(r); err != nil || !matched {
|
||||
t.Errorf("regex match=%v err=%v", matched, err)
|
||||
}
|
||||
celChecker, err := NewCELChecker(&config.ExpressionOrList{Expression: `path == "/admin/secret"`}, newTestDNS(t), header != "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if matched, err := celChecker.Check(r); err != nil || !matched {
|
||||
t.Errorf("CEL match=%v err=%v", matched, err)
|
||||
}
|
||||
if r.URL.Path != pathBefore || r.URL.EscapedPath() != escapedBefore || r.RequestURI != uriBefore {
|
||||
t.Fatal("path evaluation changed the request")
|
||||
}
|
||||
if header != "" && r.Header.Get(header) != target+"?next=/public" {
|
||||
t.Fatal("path evaluation changed the forwarded URI")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
-20
@@ -7,15 +7,15 @@ import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis/internal"
|
||||
"github.com/TecharoHQ/anubis/internal/dns"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/TecharoHQ/anubis/lib/geoip"
|
||||
"github.com/TecharoHQ/anubis/lib/policy/checker"
|
||||
"github.com/TecharoHQ/anubis/lib/store"
|
||||
"github.com/TecharoHQ/anubis/lib/thoth"
|
||||
"github.com/fahedouch/go-logrotate"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
@@ -23,20 +23,36 @@ import (
|
||||
_ "github.com/TecharoHQ/anubis/lib/store/all"
|
||||
)
|
||||
|
||||
// LogRotateTimeFormat is the timestamp a rotated log file is named after.
|
||||
//
|
||||
// It is RFC 3339 with the colons taken out. Windows reads a colon in a path
|
||||
// as the separator before an alternate data stream, so a name containing one
|
||||
// cannot be created: rotation would fail with ERROR_INVALID_NAME every time,
|
||||
// and because the rotating logger has already closed the file by then, every
|
||||
// subsequent line would cost another close, open and doomed rename while the
|
||||
// log grew past its limit without bound.
|
||||
//
|
||||
// The other characters Windows forbids in a name are < > " / \ | ? *, none of
|
||||
// which a time format produces. A rotated log file is a backup rather than an
|
||||
// interchange format, so nothing parses this.
|
||||
const LogRotateTimeFormat = "2006-01-02T15-04-05Z0700"
|
||||
|
||||
var (
|
||||
Applications = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "anubis_policy_results",
|
||||
Help: "The results of each policy rule",
|
||||
}, []string{"rule", "action"})
|
||||
}, []string{"rule", "action", "asn", "asn_description"})
|
||||
|
||||
ErrChallengeRuleHasWrongAlgorithm = errors.New("config.Bot.ChallengeRules: algorithm is invalid")
|
||||
warnedAboutThresholds = &atomic.Bool{}
|
||||
)
|
||||
|
||||
type ParsedConfig struct {
|
||||
SubrequestMode bool
|
||||
Store store.Interface
|
||||
orig *config.Config
|
||||
Impressum *config.Impressum
|
||||
Honeypot *config.Honeypot
|
||||
OpenGraph config.OpenGraph
|
||||
Bots []Bot
|
||||
Thresholds []*Threshold
|
||||
@@ -46,6 +62,10 @@ type ParsedConfig struct {
|
||||
DnsCache *dns.DnsCache
|
||||
Dns *dns.Dns
|
||||
Logger *slog.Logger
|
||||
Metrics *config.Metrics
|
||||
GeoIP *geoip.DB
|
||||
LogASN bool
|
||||
NeedJA4H bool
|
||||
}
|
||||
|
||||
func newParsedConfig(orig *config.Config) *ParsedConfig {
|
||||
@@ -53,10 +73,11 @@ func newParsedConfig(orig *config.Config) *ParsedConfig {
|
||||
orig: orig,
|
||||
OpenGraph: orig.OpenGraph,
|
||||
StatusCodes: orig.StatusCodes,
|
||||
Metrics: orig.Metrics,
|
||||
}
|
||||
}
|
||||
|
||||
func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDifficulty int, logLevel string) (*ParsedConfig, error) {
|
||||
func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDifficulty int, logLevel string, subrequestMode bool) (*ParsedConfig, error) {
|
||||
c, err := config.Load(fin, fname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -64,10 +85,10 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
|
||||
var validationErrs []error
|
||||
|
||||
tc, hasThothClient := thoth.FromContext(ctx)
|
||||
|
||||
result := newParsedConfig(c)
|
||||
result.SubrequestMode = subrequestMode
|
||||
result.DefaultDifficulty = defaultDifficulty
|
||||
result.LogASN = c.Logging.LogASN
|
||||
|
||||
if c.Logging.Level != nil {
|
||||
logLevel = c.Logging.Level.String()
|
||||
@@ -79,7 +100,7 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
case config.LogSinkFile:
|
||||
out := &logrotate.Logger{
|
||||
Filename: c.Logging.Parameters.Filename,
|
||||
FilenameTimeFormat: time.RFC3339,
|
||||
FilenameTimeFormat: LogRotateTimeFormat,
|
||||
MaxBytes: c.Logging.Parameters.MaxBytes,
|
||||
MaxAge: c.Logging.Parameters.MaxAge,
|
||||
MaxBackups: c.Logging.Parameters.MaxBackups,
|
||||
@@ -92,6 +113,24 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
|
||||
lg := result.Logger.With("at", "config-validate")
|
||||
|
||||
switch {
|
||||
case c.GeoIP != nil:
|
||||
db, err := geoip.New(ctx, result.Logger, c.GeoIP)
|
||||
if err != nil {
|
||||
validationErrs = append(validationErrs, fmt.Errorf("can't load geoip databases: %w", err))
|
||||
} else {
|
||||
result.GeoIP = db
|
||||
}
|
||||
default:
|
||||
if db, ok := geoip.FromContext(ctx); ok {
|
||||
result.GeoIP = db
|
||||
}
|
||||
}
|
||||
|
||||
if result.LogASN && !result.GeoIP.HasASN() {
|
||||
lg.WarnContext(ctx, "logging.asn is enabled but no geoip ASN database is configured; ASN logging and metrics will be skipped. Please configure geoip.asn in your policy file")
|
||||
}
|
||||
|
||||
stFac, ok := store.Get(c.Store.Backend)
|
||||
switch ok {
|
||||
case true:
|
||||
@@ -106,7 +145,7 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
|
||||
result.DnsCache = dns.NewDNSCache(result.orig.DNSTTL.Forward, result.orig.DNSTTL.Reverse, result.Store)
|
||||
result.Dns = dns.New(ctx, result.DnsCache)
|
||||
result.Dns = dns.New(ctx, result.DnsCache, lg.With("component", "dns"))
|
||||
|
||||
for _, b := range c.Bots {
|
||||
if berr := b.Valid(); berr != nil {
|
||||
@@ -130,6 +169,15 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
}
|
||||
|
||||
if b.RemoteAddressesURL != nil {
|
||||
c, err := NewRemoteAddressesURLChecker(ctx, *b.RemoteAddressesURL, result.Logger.With("rule", b.Name))
|
||||
if err != nil {
|
||||
validationErrs = append(validationErrs, fmt.Errorf("while processing rule %s remote addresses url: %w", b.Name, err))
|
||||
} else {
|
||||
cl = append(cl, c)
|
||||
}
|
||||
}
|
||||
|
||||
if b.UserAgentRegex != nil {
|
||||
c, err := NewUserAgentChecker(*b.UserAgentRegex)
|
||||
if err != nil {
|
||||
@@ -140,7 +188,7 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
|
||||
if b.PathRegex != nil {
|
||||
c, err := NewPathChecker(*b.PathRegex)
|
||||
c, err := NewPathChecker(*b.PathRegex, subrequestMode)
|
||||
if err != nil {
|
||||
validationErrs = append(validationErrs, fmt.Errorf("while processing rule %s path regex: %w", b.Name, err))
|
||||
} else {
|
||||
@@ -158,7 +206,7 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
|
||||
if b.Expression != nil {
|
||||
c, err := NewCELChecker(b.Expression, result.Dns)
|
||||
c, err := NewCELChecker(b.Expression, result.Dns, subrequestMode)
|
||||
if err != nil {
|
||||
validationErrs = append(validationErrs, fmt.Errorf("while processing rule %s expressions: %w", b.Name, err))
|
||||
} else {
|
||||
@@ -167,21 +215,21 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
|
||||
if b.ASNs != nil {
|
||||
if !hasThothClient {
|
||||
lg.Warn("You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information", "check", "asn", "settings", b.ASNs)
|
||||
if !result.GeoIP.HasASN() {
|
||||
lg.WarnContext(ctx, "You have specified an asns check but you have no geoip ASN database configured. Please configure geoip.asn in your policy file", "check", "asn", "settings", b.ASNs)
|
||||
continue
|
||||
}
|
||||
|
||||
cl = append(cl, tc.ASNCheckerFor(b.ASNs.Match))
|
||||
cl = append(cl, result.GeoIP.ASNCheckerFor(b.ASNs.Match))
|
||||
}
|
||||
|
||||
if b.GeoIP != nil {
|
||||
if !hasThothClient {
|
||||
lg.Warn("You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information", "check", "geoip", "settings", b.GeoIP)
|
||||
if !result.GeoIP.HasCountry() {
|
||||
lg.WarnContext(ctx, "You have specified a geoip check but you have no geoip country database configured. Please configure geoip.country in your policy file", "check", "geoip", "settings", b.GeoIP)
|
||||
continue
|
||||
}
|
||||
|
||||
cl = append(cl, tc.GeoIPCheckerFor(b.GeoIP.Countries))
|
||||
cl = append(cl, result.GeoIP.GeoIPCheckerFor(b.GeoIP.Countries))
|
||||
}
|
||||
|
||||
if b.Challenge == nil {
|
||||
@@ -196,7 +244,7 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
|
||||
if parsedBot.Challenge.Algorithm == "slow" {
|
||||
lg.Warn("use of deprecated algorithm \"slow\" detected, please update this to \"fast\" when possible", "name", parsedBot.Name)
|
||||
lg.WarnContext(ctx, "use of deprecated algorithm \"slow\" detected, please update this to \"fast\" when possible", "name", parsedBot.Name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,24 +253,26 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
|
||||
result.Impressum = c.Impressum
|
||||
result.Honeypot = c.Honeypot
|
||||
|
||||
parsedBot.Rules = cl
|
||||
parsedBot.hash = parsedBot.Hash()
|
||||
|
||||
result.Bots = append(result.Bots, parsedBot)
|
||||
}
|
||||
|
||||
for _, t := range c.Thresholds {
|
||||
if t.Challenge != nil && t.Challenge.Algorithm == "slow" {
|
||||
lg.Warn("use of deprecated algorithm \"slow\" detected, please update this to \"fast\" when possible", "name", t.Name)
|
||||
lg.WarnContext(ctx, "use of deprecated algorithm \"slow\" detected, please update this to \"fast\" when possible", "name", t.Name)
|
||||
}
|
||||
|
||||
if t.Challenge != nil && t.Challenge.ReportAs != 0 {
|
||||
lg.Warn("use of deprecated report_as setting detected, please remove this from your policy file when possible", "name", t.Name)
|
||||
lg.WarnContext(ctx, "use of deprecated report_as setting detected, please remove this from your policy file when possible", "name", t.Name)
|
||||
}
|
||||
|
||||
if t.Name == "legacy-anubis-behaviour" && t.Expression.String() == "true" {
|
||||
if !warnedAboutThresholds.Load() {
|
||||
lg.Warn("configuration file does not contain thresholds, see docs for details on how to upgrade", "fname", fname, "docs_url", "https://anubis.techaro.lol/docs/admin/configuration/thresholds/")
|
||||
lg.WarnContext(ctx, "configuration file does not contain thresholds, see docs for details on how to upgrade", "fname", fname, "docs_url", "https://anubis.techaro.lol/docs/admin/configuration/thresholds/")
|
||||
warnedAboutThresholds.Store(true)
|
||||
}
|
||||
|
||||
@@ -243,6 +293,31 @@ func ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDiffic
|
||||
}
|
||||
|
||||
result.DNSBL = c.DNSBL
|
||||
result.NeedJA4H = configReferencesJA4H(c.Bots)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// configReferencesJA4H reports whether any bot rule references the JA4H
|
||||
// fingerprint header, either through a headers_regex key or a CEL expression.
|
||||
// Computing the JA4H fingerprint for every request is relatively expensive, so
|
||||
// when no rule needs it the middleware that adds the header can be skipped
|
||||
// entirely. Threshold expressions can't access request headers, so only bot
|
||||
// rules are considered.
|
||||
func configReferencesJA4H(bots []config.BotConfig) bool {
|
||||
needle := strings.ToLower(internal.JA4HHeaderName)
|
||||
|
||||
for _, b := range bots {
|
||||
for key := range b.HeadersRegex {
|
||||
if strings.EqualFold(key, internal.JA4HHeaderName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if b.Expression != nil && strings.Contains(strings.ToLower(b.Expression.String()), needle) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
+320
-16
@@ -1,25 +1,34 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis"
|
||||
"github.com/TecharoHQ/anubis/data"
|
||||
"github.com/TecharoHQ/anubis/lib/thoth/thothmock"
|
||||
"github.com/TecharoHQ/anubis/internal"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/TecharoHQ/anubis/lib/geoip/geoiptest"
|
||||
)
|
||||
|
||||
func TestDefaultPolicyMustParse(t *testing.T) {
|
||||
ctx := thothmock.WithMockThoth(t)
|
||||
ctx := geoiptest.WithMockGeoIP(t)
|
||||
|
||||
fin, err := data.BotPolicies.Open("botPolicies.yaml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fin.Close()
|
||||
defer fin.Close() //nolint:errcheck
|
||||
|
||||
if _, err := ParseConfig(ctx, fin, "botPolicies.yaml", anubis.DefaultDifficulty, "info"); err != nil {
|
||||
if _, err := ParseConfig(ctx, fin, "botPolicies.yaml", anubis.DefaultDifficulty, "info", false); err != nil {
|
||||
t.Fatalf("can't parse config: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -32,29 +41,28 @@ func TestGoodConfigs(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, st := range finfos {
|
||||
st := st
|
||||
t.Run(st.Name(), func(t *testing.T) {
|
||||
t.Run("with-thoth", func(t *testing.T) {
|
||||
t.Run("with-geoip", func(t *testing.T) {
|
||||
fin, err := os.Open(filepath.Join("..", "config", "testdata", "good", st.Name()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fin.Close()
|
||||
defer fin.Close() //nolint:errcheck
|
||||
|
||||
ctx := thothmock.WithMockThoth(t)
|
||||
if _, err := ParseConfig(ctx, fin, fin.Name(), anubis.DefaultDifficulty, "info"); err != nil {
|
||||
ctx := geoiptest.WithMockGeoIP(t)
|
||||
if _, err := ParseConfig(ctx, fin, fin.Name(), anubis.DefaultDifficulty, "info", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("without-thoth", func(t *testing.T) {
|
||||
t.Run("without-geoip", func(t *testing.T) {
|
||||
fin, err := os.Open(filepath.Join("..", "config", "testdata", "good", st.Name()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fin.Close()
|
||||
defer fin.Close() //nolint:errcheck
|
||||
|
||||
if _, err := ParseConfig(t.Context(), fin, fin.Name(), anubis.DefaultDifficulty, "info"); err != nil {
|
||||
if _, err := ParseConfig(t.Context(), fin, fin.Name(), anubis.DefaultDifficulty, "info", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
@@ -63,7 +71,7 @@ func TestGoodConfigs(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBadConfigs(t *testing.T) {
|
||||
ctx := thothmock.WithMockThoth(t)
|
||||
ctx := geoiptest.WithMockGeoIP(t)
|
||||
|
||||
finfos, err := os.ReadDir("../config/testdata/bad")
|
||||
if err != nil {
|
||||
@@ -71,15 +79,14 @@ func TestBadConfigs(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, st := range finfos {
|
||||
st := st
|
||||
t.Run(st.Name(), func(t *testing.T) {
|
||||
fin, err := os.Open(filepath.Join("..", "config", "testdata", "bad", st.Name()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fin.Close()
|
||||
defer fin.Close() //nolint:errcheck
|
||||
|
||||
if _, err := ParseConfig(ctx, fin, fin.Name(), anubis.DefaultDifficulty, "info"); err == nil {
|
||||
if _, err := ParseConfig(ctx, fin, fin.Name(), anubis.DefaultDifficulty, "info", false); err == nil {
|
||||
t.Fatal(err)
|
||||
} else {
|
||||
t.Log(err)
|
||||
@@ -87,3 +94,300 @@ func TestBadConfigs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathCheckerStripsForwardedURIQuery(t *testing.T) {
|
||||
checker, err := NewPathChecker("^/admin$", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "https://anubis.local/.within.website/x/cmd/anubis/api/check", nil)
|
||||
req.Header.Set("X-Forwarded-Uri", "/admin?x=1")
|
||||
matched, err := checker.Check(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !matched {
|
||||
t.Fatalf("expected exact path checker to match forwarded URI when query string is appended")
|
||||
}
|
||||
req.Header.Set("X-Forwarded-Uri", "/admin")
|
||||
matched, err = checker.Check(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !matched {
|
||||
t.Fatalf("expected exact path checker to match forwarded URI without query string")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigReferencesJA4H(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
bots []config.BotConfig
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "no bots",
|
||||
bots: nil,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "unrelated rules",
|
||||
bots: []config.BotConfig{
|
||||
{Name: "ua", HeadersRegex: map[string]string{"User-Agent": "curl"}},
|
||||
{Name: "expr", Expression: &config.ExpressionOrList{Expression: `userAgent.contains("bot")`}},
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "headers_regex exact match",
|
||||
bots: []config.BotConfig{
|
||||
{Name: "ja4h", HeadersRegex: map[string]string{internal.JA4HHeaderName: "t13d.*"}},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "headers_regex case-insensitive match",
|
||||
bots: []config.BotConfig{
|
||||
{Name: "ja4h", HeadersRegex: map[string]string{"x-http-fingerprint-ja4h": ".*"}},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "expression references header",
|
||||
bots: []config.BotConfig{
|
||||
{Name: "ja4h", Expression: &config.ExpressionOrList{Expression: `headers["X-Http-Fingerprint-Ja4h"] == "t13d"`}},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "expression list references header",
|
||||
bots: []config.BotConfig{
|
||||
{Name: "ja4h", Expression: &config.ExpressionOrList{Any: []string{
|
||||
`userAgent.contains("bot")`,
|
||||
`headers["X-Http-Fingerprint-Ja4h"] == "t13d"`,
|
||||
}}},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "expression missingHeader references header",
|
||||
bots: []config.BotConfig{
|
||||
{Name: "ja4h", Expression: &config.ExpressionOrList{Expression: `!missingHeader(headers, "X-Http-Fingerprint-Ja4h")`}},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := configReferencesJA4H(tt.bots); got != tt.want {
|
||||
t.Errorf("configReferencesJA4H() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeoIPDatabasesBlock(t *testing.T) {
|
||||
asnPath, countryPath := geoiptest.WriteFixtures(t)
|
||||
|
||||
const rules = `
|
||||
bots:
|
||||
- name: cloudflare
|
||||
action: DENY
|
||||
asns:
|
||||
match:
|
||||
- 13335
|
||||
- name: canada
|
||||
action: DENY
|
||||
geoip:
|
||||
countries:
|
||||
- CA
|
||||
- name: everything
|
||||
action: CHALLENGE
|
||||
path_regex: .*
|
||||
`
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
geoipBlock string
|
||||
withCtx bool
|
||||
wantBots []string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "both databases",
|
||||
geoipBlock: `
|
||||
geoip:
|
||||
asn:
|
||||
path: ` + asnPath + `
|
||||
country:
|
||||
path: ` + countryPath,
|
||||
wantBots: []string{"cloudflare", "canada", "everything"},
|
||||
},
|
||||
{
|
||||
name: "asn only skips geoip rules",
|
||||
geoipBlock: `
|
||||
geoip:
|
||||
asn:
|
||||
path: ` + asnPath,
|
||||
wantBots: []string{"cloudflare", "everything"},
|
||||
},
|
||||
{
|
||||
name: "policy block wins over context",
|
||||
geoipBlock: `
|
||||
geoip:
|
||||
country:
|
||||
path: ` + countryPath,
|
||||
withCtx: true,
|
||||
wantBots: []string{"canada", "everything"},
|
||||
},
|
||||
{
|
||||
name: "context only",
|
||||
withCtx: true,
|
||||
wantBots: []string{"cloudflare", "canada", "everything"},
|
||||
},
|
||||
{
|
||||
name: "nothing configured skips both",
|
||||
wantBots: []string{"everything"},
|
||||
},
|
||||
{
|
||||
name: "missing database file",
|
||||
geoipBlock: `
|
||||
geoip:
|
||||
asn:
|
||||
path: ` + filepath.Join(t.TempDir(), "nope.mmdb"),
|
||||
wantErr: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
if tt.withCtx {
|
||||
ctx = geoiptest.WithMockGeoIP(t)
|
||||
}
|
||||
|
||||
pc, err := ParseConfig(ctx, strings.NewReader(rules+tt.geoipBlock), "test.yaml", anubis.DefaultDifficulty, "info", false)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("wanted an error, got nil")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var got []string
|
||||
for _, b := range pc.Bots {
|
||||
got = append(got, b.Name)
|
||||
}
|
||||
|
||||
if !slices.Equal(got, tt.wantBots) {
|
||||
t.Fatalf("bots: want %v, got %v", tt.wantBots, got)
|
||||
}
|
||||
|
||||
for _, b := range pc.Bots {
|
||||
var ip string
|
||||
switch b.Name {
|
||||
case "cloudflare":
|
||||
ip = "1.1.1.1"
|
||||
case "canada":
|
||||
ip = "2.2.2.2"
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.Header.Set("X-Real-IP", ip)
|
||||
ok, err := b.Rules.Check(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !ok {
|
||||
t.Errorf("%s rule did not match %s", b.Name, ip)
|
||||
}
|
||||
|
||||
req.Header.Set("X-Real-IP", "8.8.8.8")
|
||||
if ok, _ := b.Rules.Check(req); ok {
|
||||
t.Errorf("%s rule matched 8.8.8.8", b.Name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfigRemoteAddressesURL(t *testing.T) {
|
||||
body := `{
|
||||
"creationTime": "2025-01-02T03:04:05.000000",
|
||||
"prefixes": [{"ipv4Prefix": "20.42.10.176/28"}]
|
||||
}`
|
||||
|
||||
release := make(chan struct{})
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
select {
|
||||
case <-release:
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, body)
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
yaml := fmt.Sprintf(`
|
||||
bots:
|
||||
- name: openai-searchbot
|
||||
action: ALLOW
|
||||
remote_addresses_url: %q
|
||||
`, ts.URL)
|
||||
|
||||
type parseResult struct {
|
||||
cfg *ParsedConfig
|
||||
err error
|
||||
}
|
||||
ch := make(chan parseResult, 1)
|
||||
go func() {
|
||||
cfg, err := ParseConfig(t.Context(), strings.NewReader(yaml), "dynamic.yaml", anubis.DefaultDifficulty, "error", false)
|
||||
ch <- parseResult{cfg, err}
|
||||
}()
|
||||
|
||||
var parsed *ParsedConfig
|
||||
select {
|
||||
case res := <-ch:
|
||||
if res.err != nil {
|
||||
t.Fatalf("ParseConfig: %v", res.err)
|
||||
}
|
||||
parsed = res.cfg
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("ParseConfig blocked on remote fetch")
|
||||
}
|
||||
|
||||
if len(parsed.Bots) != 1 {
|
||||
t.Fatalf("got %d bots, want 1", len(parsed.Bots))
|
||||
}
|
||||
|
||||
close(release)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.Header.Set("X-Real-IP", "20.42.10.176")
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
ok, err := parsed.Bots[0].Rules.Check(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Check: %v", err)
|
||||
}
|
||||
if ok {
|
||||
miss := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
miss.Header.Set("X-Real-IP", "1.1.1.1")
|
||||
matched, err := parsed.Bots[0].Rules.Check(miss)
|
||||
if err != nil {
|
||||
t.Fatalf("Check unrelated IP: %v", err)
|
||||
}
|
||||
if matched {
|
||||
t.Fatal("unrelated IP should not match")
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
t.Fatal("remote addresses url list was not loaded in time")
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis"
|
||||
"github.com/TecharoHQ/anubis/internal"
|
||||
"github.com/TecharoHQ/anubis/internal/iplist"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/TecharoHQ/anubis/lib/policy/checker"
|
||||
"github.com/gaissmai/bart"
|
||||
)
|
||||
|
||||
const (
|
||||
remoteAddressesURLRefreshInterval = 24 * time.Hour
|
||||
remoteAddressesURLRetryInterval = 15 * time.Minute
|
||||
remoteAddressesURLMaxRetries = 5
|
||||
remoteAddressesURLHTTPTimeout = 30 * time.Second
|
||||
remoteAddressesURLMaxBodyBytes = 8 << 20
|
||||
)
|
||||
|
||||
// RemoteAddressesURLChecker matches client IPs against a prefix list fetched
|
||||
// from a remote JSON document. The list starts empty and is replaced on each
|
||||
// successful refresh. Failed fetches never clobber a previously loaded list.
|
||||
type RemoteAddressesURLChecker struct {
|
||||
url string
|
||||
logger *slog.Logger
|
||||
client *http.Client
|
||||
|
||||
mu sync.RWMutex
|
||||
prefixTable *bart.Lite
|
||||
hash string
|
||||
creationTime string
|
||||
rebuildCount int
|
||||
|
||||
cycleStart time.Time
|
||||
consecutiveFail int
|
||||
|
||||
refreshInterval time.Duration
|
||||
retryInterval time.Duration
|
||||
maxRetries int
|
||||
|
||||
stopped chan struct{}
|
||||
}
|
||||
|
||||
func NewRemoteAddressesURLChecker(ctx context.Context, rawURL string, logger *slog.Logger) (checker.Impl, error) {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
|
||||
if err := parseRemoteAddressesURL(rawURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c := &RemoteAddressesURLChecker{
|
||||
url: rawURL,
|
||||
logger: logger,
|
||||
client: &http.Client{Timeout: remoteAddressesURLHTTPTimeout, CheckRedirect: remoteAddressesRedirect},
|
||||
prefixTable: new(bart.Lite),
|
||||
hash: internal.FastHash(""),
|
||||
refreshInterval: remoteAddressesURLRefreshInterval,
|
||||
retryInterval: remoteAddressesURLRetryInterval,
|
||||
maxRetries: remoteAddressesURLMaxRetries,
|
||||
stopped: make(chan struct{}),
|
||||
}
|
||||
|
||||
go c.run(ctx)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func parseRemoteAddressesURL(rawURL string) error {
|
||||
rawURL = strings.TrimSpace(rawURL)
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
return fmt.Errorf("%w: %q", config.ErrInvalidRemoteAddressesURL, rawURL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RemoteAddressesURLChecker) Check(r *http.Request) (bool, error) {
|
||||
host := r.Header.Get("X-Real-IP")
|
||||
if host == "" {
|
||||
return false, fmt.Errorf("%w: header X-Real-IP is not set", ErrMisconfiguration)
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddr(host)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%w: %s is not an IP address: %w", ErrMisconfiguration, host, err)
|
||||
}
|
||||
|
||||
if addr.Is6() && addr.Is4In6() {
|
||||
addr = addr.Unmap()
|
||||
}
|
||||
|
||||
c.mu.RLock()
|
||||
table := c.prefixTable
|
||||
c.mu.RUnlock()
|
||||
|
||||
if table == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return table.Contains(addr), nil
|
||||
}
|
||||
|
||||
func (c *RemoteAddressesURLChecker) Hash() string {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
return c.hash
|
||||
}
|
||||
|
||||
func (c *RemoteAddressesURLChecker) run(ctx context.Context) {
|
||||
defer close(c.stopped)
|
||||
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
delay := c.refreshOnce(ctx)
|
||||
timer := time.NewTimer(delay)
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *RemoteAddressesURLChecker) refreshOnce(ctx context.Context) time.Duration {
|
||||
if c.cycleStart.IsZero() {
|
||||
c.cycleStart = time.Now()
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
|
||||
if err != nil {
|
||||
return c.handleRetryable(ctx, "can't build remote_addresses_url request", err)
|
||||
}
|
||||
req.Header.Set("User-Agent", "TecharoHQ-Anubis/"+anubis.Version)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return 0
|
||||
}
|
||||
return c.handleRetryable(ctx, "can't fetch remote_addresses_url", err)
|
||||
}
|
||||
defer resp.Body.Close() //nolint:errcheck
|
||||
|
||||
switch {
|
||||
case resp.StatusCode >= 500:
|
||||
return c.handleRetryable(ctx, "remote_addresses_url fetch returned server error", fmt.Errorf("http status %d", resp.StatusCode))
|
||||
case resp.StatusCode >= 400:
|
||||
c.logger.WarnContext(ctx, "remote_addresses_url fetch returned client error", "url", c.url, "status", resp.StatusCode)
|
||||
return c.delayUntilNextCycle()
|
||||
case resp.StatusCode < 200 || resp.StatusCode > 299:
|
||||
return c.handleRetryable(ctx, "remote_addresses_url fetch returned unexpected status", fmt.Errorf("http status %d", resp.StatusCode))
|
||||
}
|
||||
|
||||
pl, err := iplist.Parse(io.LimitReader(resp.Body, remoteAddressesURLMaxBodyBytes))
|
||||
if err != nil {
|
||||
c.logger.WarnContext(ctx, "failed to parse remote_addresses_url", "url", c.url, "err", err)
|
||||
return c.delayUntilNextCycle()
|
||||
}
|
||||
|
||||
if err := c.applyList(pl); err != nil {
|
||||
c.logger.WarnContext(ctx, "failed to apply remote_addresses_url", "url", c.url, "err", err)
|
||||
return c.delayUntilNextCycle()
|
||||
}
|
||||
|
||||
c.cycleStart = time.Now()
|
||||
c.consecutiveFail = 0
|
||||
return c.refreshInterval
|
||||
}
|
||||
|
||||
func (c *RemoteAddressesURLChecker) applyList(pl *iplist.PrefixList) error {
|
||||
if pl.CreationTime != "" && pl.CreationTime == c.creationTime {
|
||||
c.logger.Debug("remote_addresses_url unchanged, skip rebuild", "url", c.url, "creationTime", pl.CreationTime)
|
||||
return nil
|
||||
}
|
||||
|
||||
cidrs := pl.CIDRs()
|
||||
if len(cidrs) == 0 {
|
||||
return config.ErrInvalidRemoteAddressesURL
|
||||
}
|
||||
table := new(bart.Lite)
|
||||
for _, cidr := range cidrs {
|
||||
prefix, err := netip.ParsePrefix(cidr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid CIDR %q: %w", cidr, err)
|
||||
}
|
||||
table.Insert(prefix)
|
||||
}
|
||||
|
||||
hash := internal.FastHash(strings.Join(cidrs, ","))
|
||||
|
||||
c.mu.Lock()
|
||||
c.prefixTable = table
|
||||
c.hash = hash
|
||||
c.creationTime = pl.CreationTime
|
||||
c.rebuildCount++
|
||||
c.mu.Unlock()
|
||||
|
||||
c.logger.Info("updated remote_addresses_url", "url", c.url, "prefixes", len(cidrs), "creationTime", pl.CreationTime)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RemoteAddressesURLChecker) handleRetryable(ctx context.Context, msg string, err error) time.Duration {
|
||||
c.consecutiveFail++
|
||||
if c.consecutiveFail < c.maxRetries {
|
||||
c.logger.WarnContext(ctx, msg, "url", c.url, "attempt", c.consecutiveFail, "err", err)
|
||||
return c.retryInterval
|
||||
}
|
||||
|
||||
c.logger.WarnContext(ctx, "remote_addresses_url fetch failed, giving up until next refresh window", "url", c.url, "attempts", c.consecutiveFail, "err", err)
|
||||
return c.delayUntilNextCycle()
|
||||
}
|
||||
|
||||
func (c *RemoteAddressesURLChecker) delayUntilNextCycle() time.Duration {
|
||||
c.consecutiveFail = 0
|
||||
remaining := time.Until(c.cycleStart.Add(c.refreshInterval))
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
c.cycleStart = time.Time{}
|
||||
return remaining
|
||||
}
|
||||
|
||||
func remoteAddressesRedirect(req *http.Request, via []*http.Request) error {
|
||||
if len(via) == 0 || len(via) >= 10 {
|
||||
return config.ErrInvalidRemoteAddressesURL
|
||||
}
|
||||
if req.URL.Scheme != via[0].URL.Scheme || req.URL.Host != via[0].URL.Host {
|
||||
return config.ErrInvalidRemoteAddressesURL
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis/internal/iplist"
|
||||
|
||||
"github.com/TecharoHQ/anubis"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/gaissmai/bart"
|
||||
)
|
||||
|
||||
func discardLogger() *slog.Logger {
|
||||
return slog.New(slog.DiscardHandler)
|
||||
}
|
||||
|
||||
func newTestRemoteAddressesURLChecker(url string) *RemoteAddressesURLChecker {
|
||||
return &RemoteAddressesURLChecker{
|
||||
url: url,
|
||||
logger: discardLogger(),
|
||||
client: &http.Client{Timeout: 5 * time.Second},
|
||||
prefixTable: new(bart.Lite),
|
||||
refreshInterval: 24 * time.Hour,
|
||||
retryInterval: 15 * time.Minute,
|
||||
maxRetries: 5,
|
||||
stopped: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func checkIP(t *testing.T, c *RemoteAddressesURLChecker, ip string) bool {
|
||||
t.Helper()
|
||||
r, err := http.NewRequest(http.MethodGet, "/", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("can't make request: %v", err)
|
||||
}
|
||||
r.Header.Set("X-Real-IP", ip)
|
||||
ok, err := c.Check(r)
|
||||
if err != nil {
|
||||
t.Fatalf("Check: %v", err)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
func jsonHandler(status int, body string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_, _ = io.WriteString(w, body)
|
||||
})
|
||||
}
|
||||
|
||||
const samplePrefixList = `{
|
||||
"creationTime": "2025-01-02T03:04:05.000000",
|
||||
"prefixes": [
|
||||
{"ipv4Prefix": "20.42.10.176/28"},
|
||||
{"ipv6Prefix": "2001:db8::/32"}
|
||||
]
|
||||
}`
|
||||
|
||||
func TestRemoteAddressesURLChecker_emptyBeforeFetch(t *testing.T) {
|
||||
c := newTestRemoteAddressesURLChecker("http://127.0.0.1:1/missing.json")
|
||||
if checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("empty list should not match any IP")
|
||||
}
|
||||
if checkIP(t, c, "1.1.1.1") {
|
||||
t.Fatal("empty list should not match any IP")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_successfulFetch(t *testing.T) {
|
||||
var gotUA string
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotUA = r.Header.Get("User-Agent")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, samplePrefixList)
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
delay := c.refreshOnce(t.Context())
|
||||
if delay != c.refreshInterval {
|
||||
t.Fatalf("delay = %v, want %v", delay, c.refreshInterval)
|
||||
}
|
||||
wantUA := "TecharoHQ-Anubis/" + anubis.Version
|
||||
if gotUA != wantUA {
|
||||
t.Fatalf("User-Agent = %q, want %q", gotUA, wantUA)
|
||||
}
|
||||
if c.consecutiveFail != 0 {
|
||||
t.Fatalf("consecutiveFail = %d, want 0", c.consecutiveFail)
|
||||
}
|
||||
if c.rebuildCount != 1 {
|
||||
t.Fatalf("rebuildCount = %d, want 1", c.rebuildCount)
|
||||
}
|
||||
if c.Hash() == "" {
|
||||
t.Fatal("hash should be non-empty after a successful fetch")
|
||||
}
|
||||
|
||||
if !checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("expected 20.42.10.176 to match")
|
||||
}
|
||||
if !checkIP(t, c, "20.42.10.191") {
|
||||
t.Fatal("expected 20.42.10.191 (end of /28) to match")
|
||||
}
|
||||
if checkIP(t, c, "20.42.10.192") {
|
||||
t.Fatal("expected 20.42.10.192 to be outside the prefix")
|
||||
}
|
||||
if !checkIP(t, c, "2001:db8::1") {
|
||||
t.Fatal("expected IPv6 prefix to match")
|
||||
}
|
||||
if checkIP(t, c, "1.1.1.1") {
|
||||
t.Fatal("expected unrelated IPv4 not to match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_http5xx(t *testing.T) {
|
||||
ts := httptest.NewServer(jsonHandler(http.StatusInternalServerError, "nope"))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
c.cycleStart = time.Now()
|
||||
|
||||
delay := c.refreshOnce(t.Context())
|
||||
if delay != c.retryInterval {
|
||||
t.Fatalf("delay = %v, want retry interval %v", delay, c.retryInterval)
|
||||
}
|
||||
if c.consecutiveFail != 1 {
|
||||
t.Fatalf("consecutiveFail = %d, want 1", c.consecutiveFail)
|
||||
}
|
||||
if checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("failed fetch must not populate the list")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_http5xxGivesUpAfterMaxRetries(t *testing.T) {
|
||||
ts := httptest.NewServer(jsonHandler(http.StatusBadGateway, "nope"))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
c.cycleStart = time.Now()
|
||||
c.consecutiveFail = 4
|
||||
|
||||
delay := c.refreshOnce(t.Context())
|
||||
if delay < 23*time.Hour || delay > 24*time.Hour {
|
||||
t.Fatalf("delay = %v, want remainder of 24h window", delay)
|
||||
}
|
||||
if c.consecutiveFail != 0 {
|
||||
t.Fatalf("consecutiveFail = %d, want 0 after giving up", c.consecutiveFail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_http5xxKeepsExistingList(t *testing.T) {
|
||||
var status atomic.Int32
|
||||
status.Store(http.StatusOK)
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(int(status.Load()))
|
||||
if status.Load() == http.StatusOK {
|
||||
_, _ = io.WriteString(w, samplePrefixList)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
if delay := c.refreshOnce(t.Context()); delay != c.refreshInterval {
|
||||
t.Fatalf("initial fetch delay = %v, want %v", delay, c.refreshInterval)
|
||||
}
|
||||
if !checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("expected initial fetch to populate the list")
|
||||
}
|
||||
|
||||
status.Store(http.StatusInternalServerError)
|
||||
c.cycleStart = time.Now()
|
||||
if delay := c.refreshOnce(t.Context()); delay != c.retryInterval {
|
||||
t.Fatalf("5xx delay = %v, want %v", delay, c.retryInterval)
|
||||
}
|
||||
if !checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("existing list must be kept after a 5xx response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_http4xx(t *testing.T) {
|
||||
ts := httptest.NewServer(jsonHandler(http.StatusNotFound, "missing"))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
c.cycleStart = time.Now()
|
||||
|
||||
delay := c.refreshOnce(t.Context())
|
||||
if delay < 23*time.Hour || delay > 24*time.Hour {
|
||||
t.Fatalf("delay = %v, want remainder of 24h window", delay)
|
||||
}
|
||||
if c.consecutiveFail != 0 {
|
||||
t.Fatalf("consecutiveFail = %d, want 0 (4xx does not retry)", c.consecutiveFail)
|
||||
}
|
||||
if checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("4xx fetch must not populate the list")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_invalidJSON(t *testing.T) {
|
||||
ts := httptest.NewServer(jsonHandler(http.StatusOK, `{not json`))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
c.cycleStart = time.Now()
|
||||
|
||||
delay := c.refreshOnce(t.Context())
|
||||
if delay < 23*time.Hour || delay > 24*time.Hour {
|
||||
t.Fatalf("delay = %v, want remainder of 24h window", delay)
|
||||
}
|
||||
if c.rebuildCount != 0 {
|
||||
t.Fatalf("rebuildCount = %d, want 0", c.rebuildCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_invalidCIDR(t *testing.T) {
|
||||
body := `{"creationTime": "t", "prefixes": [{"ipv4Prefix": "not-a-cidr"}]}`
|
||||
ts := httptest.NewServer(jsonHandler(http.StatusOK, body))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
c.cycleStart = time.Now()
|
||||
|
||||
delay := c.refreshOnce(t.Context())
|
||||
if delay < 23*time.Hour || delay > 24*time.Hour {
|
||||
t.Fatalf("delay = %v, want remainder of 24h window", delay)
|
||||
}
|
||||
if c.rebuildCount != 0 {
|
||||
t.Fatalf("rebuildCount = %d, want 0", c.rebuildCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_unchangedCreationTime(t *testing.T) {
|
||||
ts := httptest.NewServer(jsonHandler(http.StatusOK, samplePrefixList))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
if delay := c.refreshOnce(t.Context()); delay != c.refreshInterval {
|
||||
t.Fatalf("first fetch delay = %v, want %v", delay, c.refreshInterval)
|
||||
}
|
||||
hash := c.Hash()
|
||||
if c.rebuildCount != 1 {
|
||||
t.Fatalf("rebuildCount = %d, want 1", c.rebuildCount)
|
||||
}
|
||||
|
||||
if delay := c.refreshOnce(t.Context()); delay != c.refreshInterval {
|
||||
t.Fatalf("second fetch delay = %v, want %v", delay, c.refreshInterval)
|
||||
}
|
||||
if c.rebuildCount != 1 {
|
||||
t.Fatalf("rebuildCount = %d, want 1 (creationTime unchanged)", c.rebuildCount)
|
||||
}
|
||||
if c.Hash() != hash {
|
||||
t.Fatal("hash should be unchanged when creationTime matches")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLChecker_creationTimeChangeRebuilds(t *testing.T) {
|
||||
var body atomic.Value
|
||||
body.Store(samplePrefixList)
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, body.Load().(string))
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
c := newTestRemoteAddressesURLChecker(ts.URL)
|
||||
c.refreshOnce(t.Context())
|
||||
|
||||
body.Store(`{
|
||||
"creationTime": "2026-09-18T00:00:00.000000",
|
||||
"prefixes": [{"ipv4Prefix": "1.1.1.1/32"}]
|
||||
}`)
|
||||
c.refreshOnce(t.Context())
|
||||
|
||||
if c.rebuildCount != 2 {
|
||||
t.Fatalf("rebuildCount = %d, want 2", c.rebuildCount)
|
||||
}
|
||||
if !checkIP(t, c, "1.1.1.1") {
|
||||
t.Fatal("expected rebuilt list to contain 1.1.1.1")
|
||||
}
|
||||
if checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("expected old prefixes to be replaced, not merged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRemoteAddressesURLChecker_invalidURL(t *testing.T) {
|
||||
_, err := NewRemoteAddressesURLChecker(t.Context(), "not a url", discardLogger())
|
||||
if !errors.Is(err, config.ErrInvalidRemoteAddressesURL) {
|
||||
t.Fatalf("err = %v, want %v", err, config.ErrInvalidRemoteAddressesURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRemoteAddressesURLChecker_runStopsOnCancel(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
select {
|
||||
case <-started:
|
||||
default:
|
||||
close(started)
|
||||
}
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
impl, err := NewRemoteAddressesURLChecker(ctx, ts.URL, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := impl.(*RemoteAddressesURLChecker)
|
||||
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("fetch did not start")
|
||||
}
|
||||
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-c.stopped:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("refresh goroutine did not stop after context cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLRejectsEmptyReplacement(t *testing.T) {
|
||||
c := newTestRemoteAddressesURLChecker("")
|
||||
for _, doc := range []string{samplePrefixList, `{}`, `{"prefixes":[]}`} {
|
||||
pl, err := iplist.Parse(strings.NewReader(doc))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = c.applyList(pl)
|
||||
if doc != samplePrefixList && err == nil {
|
||||
t.Errorf("accepted empty feed %s", doc)
|
||||
}
|
||||
if !checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("loaded prefix lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteAddressesURLRedirectOrigin(t *testing.T) {
|
||||
var reached atomic.Bool
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reached.Store(true)
|
||||
if _, err := io.WriteString(w, samplePrefixList); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}))
|
||||
defer other.Close()
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/external":
|
||||
http.Redirect(w, r, other.URL, http.StatusFound)
|
||||
case "/local":
|
||||
http.Redirect(w, r, "/feed", http.StatusFound)
|
||||
default:
|
||||
if _, err := io.WriteString(w, samplePrefixList); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}))
|
||||
defer origin.Close()
|
||||
for _, p := range []string{"/external", "/local"} {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
impl, err := NewRemoteAddressesURLChecker(ctx, origin.URL+p, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := impl.(*RemoteAddressesURLChecker)
|
||||
cancel()
|
||||
<-c.stopped
|
||||
c.refreshOnce(t.Context())
|
||||
if p == "/external" && reached.Load() {
|
||||
t.Fatal("followed external redirect")
|
||||
}
|
||||
if p == "/local" && !checkIP(t, c, "20.42.10.176") {
|
||||
t.Fatal("same origin redirect failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"cel.dev/cel-go/cel"
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
"github.com/TecharoHQ/anubis/lib/policy/expressions"
|
||||
"github.com/google/cel-go/cel"
|
||||
)
|
||||
|
||||
type Threshold struct {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWeighDefaultSurvivesParsing(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, weight string
|
||||
want int
|
||||
}{
|
||||
{"default", "", 5}, {"explicit", " weight:\n adjust: 17\n", 17},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
input := "bots:\n - name: weigh\n user_agent_regex: .*\n action: WEIGH\n" + tc.weight
|
||||
p, err := ParseConfig(t.Context(), strings.NewReader(input), "test.yaml", 4, "info", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range p.Bots {
|
||||
if b.Name == "weigh" {
|
||||
if b.Weight == nil {
|
||||
t.Fatal("missing default weight")
|
||||
}
|
||||
if b.Weight.Adjust != tc.want {
|
||||
t.Fatalf("weight=%d", b.Weight.Adjust)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("missing rule")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportedWeighDefaultSurvivesParsing(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "bots.yaml")
|
||||
if err := os.WriteFile(path, []byte("- name: imported-weigh\n user_agent_regex: .*\n action: WEIGH\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := ParseConfig(t.Context(), strings.NewReader("bots:\n - import: "+path+"\n"), "test.yaml", 4, "info", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range p.Bots {
|
||||
if b.Name == "imported-weigh" {
|
||||
if b.Weight == nil || b.Weight.Adjust != 5 {
|
||||
t.Fatalf("weight=%v", b.Weight)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("missing imported rule")
|
||||
}
|
||||
Reference in new issue
Block a user