Import Anubis v1.28.2

Replace the tree with upstream TecharoHQ/anubis v1.28.2 (a1384fbf42e3).
Masyunis customizations are re-applied in the following commits.
This commit is contained in:
sol_bot Bot committed 2026-11-28 14:52:26 +03:00
1 parent eb3e46d8d0
commit e07de898cd
573 files changed
+35846 -6807

No files matched your search

+19 -8
View File
@@ -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))
}),
),
),
+94 -22
View File
@@ -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())
}
})
}
}
+8 -6
View File
@@ -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
+1 -1
View File
@@ -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) {
+1 -1
View File
@@ -46,7 +46,7 @@ var (
)
func init() {
globalLoadAvg = &loadAvg{}
globalLoadAvg = &loadAvg{data: &load.AvgStat{}}
go globalLoadAvg.updateThread(context.Background())
}
+60
View File
@@ -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,
}
}
+86
View File
@@ -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
}
+104
View File
@@ -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")
}
})
}
+6 -7
View File
@@ -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
+1 -1
View File
@@ -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) {