Fix challenge validation panic when follow-up hits ALLOW (#1278)

* fix(localization): correct formatting of Swedish loading message

* fix(main): correct formatting and improve readability in main.go

* fix(challenge): add difficulty and policy rule hash to challenge metadata

* docs(challenge): fix panic when validating challenges in privacy-mode browsers
This commit is contained in:
Jason Cameron 2025-11-14 16:51:48 -08:00 committed by GitHub
parent 68fcc0c44f
commit 97ba84e26d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 126 additions and 23 deletions

View file

@ -145,7 +145,7 @@ func parseBindNetFromAddr(address string) (string, string) {
return "", address
}
func parseSameSite(s string) (http.SameSite) {
func parseSameSite(s string) http.SameSite {
switch strings.ToLower(s) {
case "none":
return http.SameSiteNoneMode

View file

@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<!-- This changes the project to: -->
- Fix panic when validating challenges after privacy-mode browsers strip headers and the follow-up request matches an `ALLOW` threshold.
- Expose WEIGHT rule matches as Prometheus metrics.
- Allow more OCI registry clients [based on feedback](https://github.com/TecharoHQ/anubis/pull/1253#issuecomment-3506744184).
- Expose services directory in the embedded `(data)` filesystem.

View file

@ -121,6 +121,8 @@ func (s *Server) issueChallenge(ctx context.Context, r *http.Request, lg *slog.L
Method: rule.Challenge.Algorithm,
RandomData: fmt.Sprintf("%x", randomData),
IssuedAt: time.Now(),
Difficulty: rule.Challenge.Difficulty,
PolicyRuleHash: rule.Hash(),
Metadata: map[string]string{
"User-Agent": r.Header.Get("User-Agent"),
"X-Real-Ip": r.Header.Get("X-Real-Ip"),
@ -137,6 +139,44 @@ func (s *Server) issueChallenge(ctx context.Context, r *http.Request, lg *slog.L
return &chall, err
}
func (s *Server) hydrateChallengeRule(rule *policy.Bot, chall *challenge.Challenge, lg *slog.Logger) *policy.Bot {
if chall == nil {
return rule
}
if rule == nil {
rule = &policy.Bot{
Rules: &checker.List{},
}
}
if chall.Difficulty == 0 {
// fall back to whatever the policy currently says or the global default
if rule.Challenge != nil && rule.Challenge.Difficulty != 0 {
chall.Difficulty = rule.Challenge.Difficulty
} else {
chall.Difficulty = s.policy.DefaultDifficulty
}
}
if rule.Challenge == nil {
lg.Warn("rule missing challenge configuration; using stored challenge metadata", "rule", rule.Name)
rule.Challenge = &config.ChallengeRules{}
}
if rule.Challenge.Difficulty == 0 {
rule.Challenge.Difficulty = chall.Difficulty
}
if rule.Challenge.ReportAs == 0 {
rule.Challenge.ReportAs = chall.Difficulty
}
if rule.Challenge.Algorithm == "" {
rule.Challenge.Algorithm = chall.Method
}
return rule
}
func (s *Server) maybeReverseProxyHttpStatusOnly(w http.ResponseWriter, r *http.Request) {
s.maybeReverseProxy(w, r, true)
}
@ -461,6 +501,8 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
return
}
rule = s.hydrateChallengeRule(rule, chall, lg)
impl, ok := challenge.Get(chall.Method)
if !ok {
lg.Error("check failed", "err", err)

View file

@ -2,6 +2,7 @@ package lib
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
@ -18,8 +19,10 @@ import (
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/data"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/policy"
"github.com/TecharoHQ/anubis/lib/policy/config"
"github.com/TecharoHQ/anubis/lib/store"
"github.com/TecharoHQ/anubis/lib/thoth/thothmock"
)
@ -1027,6 +1030,59 @@ func TestPassChallengeXSS(t *testing.T) {
})
}
func TestPassChallengeNilRuleChallengeFallback(t *testing.T) {
pol := loadPolicies(t, "testdata/zero_difficulty.yaml", 0)
srv := spawnAnubis(t, Options{
Next: http.NewServeMux(),
Policy: pol,
})
allowThreshold, err := policy.ParsedThresholdFromConfig(config.Threshold{
Name: "allow-all",
Expression: &config.ExpressionOrList{
Expression: "true",
},
Action: config.RuleAllow,
})
if err != nil {
t.Fatalf("can't compile test threshold: %v", err)
}
srv.policy.Thresholds = []*policy.Threshold{allowThreshold}
srv.policy.Bots = nil
chall := challenge.Challenge{
ID: "test-challenge",
Method: "metarefresh",
RandomData: "apple cider",
IssuedAt: time.Now().Add(-5 * time.Second),
Difficulty: 1,
}
j := store.JSON[challenge.Challenge]{Underlying: srv.store}
if err := j.Set(context.Background(), "challenge:"+chall.ID, chall, time.Minute); err != nil {
t.Fatalf("can't insert challenge into store: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "https://example.com"+anubis.APIPrefix+"pass-challenge", nil)
q := req.URL.Query()
q.Set("redir", "/")
q.Set("id", chall.ID)
q.Set("challenge", chall.RandomData)
req.URL.RawQuery = q.Encode()
req.Header.Set("X-Real-Ip", "203.0.113.4")
req.Header.Set("User-Agent", "NilChallengeTester/1.0")
req.AddCookie(&http.Cookie{Name: anubis.TestCookieName, Value: chall.ID})
rr := httptest.NewRecorder()
srv.PassChallenge(rr, req)
if rr.Code != http.StatusFound {
t.Fatalf("expected redirect when validating challenge, got %d", rr.Code)
}
}
func TestXForwardedForNoDoubleComma(t *testing.T) {
var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Forwarded-For", r.Header.Get("X-Forwarded-For"))

View file

@ -10,4 +10,6 @@ type Challenge struct {
IssuedAt time.Time `json:"issuedAt"` // When the challenge was issued
Metadata map[string]string `json:"metadata"` // Challenge metadata such as IP address and user agent
Spent bool `json:"spent"` // Has the challenge already been solved?
Difficulty int `json:"difficulty,omitempty"` // Difficulty that was in effect when issued
PolicyRuleHash string `json:"policyRuleHash,omitempty"` // Hash of the policy rule that issued this challenge
}

View file

@ -4,6 +4,7 @@ import (
"testing"
"time"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/google/uuid"
@ -19,5 +20,6 @@ func New(t *testing.T) *challenge.Challenge {
ID: id.String(),
RandomData: randomData,
IssuedAt: time.Now(),
Difficulty: anubis.DefaultDifficulty,
}
}

View file

@ -31,7 +31,7 @@ func TestLocalizationService(t *testing.T) {
"vi": "Đang nạp...",
"zh-CN": "加载中...",
"zh-TW": "載入中...",
"sv" : "Laddar...",
"sv": "Laddar...",
}
var keys []string