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

+412 -120
View File
@@ -4,18 +4,24 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"net/netip"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"time"
"cel.dev/cel-go/common/types"
"github.com/golang-jwt/jwt/v5"
"github.com/google/cel-go/common/types"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
@@ -27,6 +33,7 @@ import (
"github.com/TecharoHQ/anubis/internal/dnsbl"
"github.com/TecharoHQ/anubis/internal/ogtags"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/challenge/extension"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/localization"
"github.com/TecharoHQ/anubis/lib/policy"
@@ -37,55 +44,101 @@ import (
_ "github.com/TecharoHQ/anubis/lib/challenge/metarefresh"
_ "github.com/TecharoHQ/anubis/lib/challenge/preact"
_ "github.com/TecharoHQ/anubis/lib/challenge/proofofwork"
_ "github.com/TecharoHQ/anubis/lib/challenge/wasm"
// extension implementations
_ "github.com/TecharoHQ/anubis/lib/challenge/extension/css-load"
)
type contextKey int
const asnContextKey contextKey = iota
type asnInfo struct {
ASN string
Description string
}
func asnFromContext(ctx context.Context) (string, string) {
if v, ok := ctx.Value(asnContextKey).(asnInfo); ok {
return v.ASN, v.Description
}
return "", ""
}
var (
challengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_challenges_issued",
Help: "The total number of challenges issued",
}, []string{"method"})
}, []string{"method", "asn", "asn_description"})
challengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_challenges_validated",
Help: "The total number of challenges validated",
}, []string{"method"})
}, []string{"method", "asn", "asn_description"})
droneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_dronebl_hits",
Help: "The total number of hits from DroneBL",
}, []string{"status"})
}, []string{"status", "asn", "asn_description"})
failedValidations = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_failed_validations",
Help: "The total number of failed validations",
}, []string{"method"})
}, []string{"method", "asn", "asn_description"})
requestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_proxied_requests_total",
Help: "Number of requests proxied through Anubis to upstream targets",
}, []string{"host"})
}, []string{"host", "asn", "asn_description"})
requestsByASN = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_requests_by_asn_total",
Help: "Number of requests by ASN",
}, []string{"asn", "asn_description"})
)
type Server struct {
next http.Handler
store store.Interface
mux *http.ServeMux
policy *policy.ParsedConfig
OGTags *ogtags.OGTagCache
logger *slog.Logger
opts Options
ed25519Priv ed25519.PrivateKey
hs512Secret []byte
challengeLocks [256]sync.Mutex
next http.Handler
store store.Interface
mux *http.ServeMux
policy *policy.ParsedConfig
OGTags *ogtags.OGTagCache
logger *slog.Logger
opts Options
ed25519Priv ed25519.PrivateKey
hs512Secret []byte
}
func (s *Server) getRequestLogger(r *http.Request) (*slog.Logger, *http.Request) {
lg := internal.GetRequestLogger(s.logger, r)
if s.policy.LogASN && s.policy.GeoIP.HasASN() {
if addr, err := netip.ParseAddr(r.Header.Get("X-Real-IP")); err == nil {
if asNumber, description, ok := s.policy.GeoIP.LookupASN(addr); ok {
asn := strconv.FormatUint(uint64(asNumber), 10)
lg = lg.With("asn", asNumber, "asn_description", description)
requestsByASN.WithLabelValues(asn, description).Inc()
r = r.WithContext(context.WithValue(r.Context(), asnContextKey, asnInfo{
ASN: asn,
Description: description,
}))
}
}
}
return lg, r
}
func (s *Server) getTokenKeyfunc() jwt.Keyfunc {
// return ED25519 key if HS512 is not set
if len(s.hs512Secret) == 0 {
return func(token *jwt.Token) (interface{}, error) {
return func(token *jwt.Token) (any, error) {
return s.ed25519Priv.Public().(ed25519.PublicKey), nil
}
} else {
return func(token *jwt.Token) (interface{}, error) {
return func(token *jwt.Token) (any, error) {
return s.hs512Secret, nil
}
}
@@ -100,16 +153,50 @@ func (s *Server) getChallenge(r *http.Request) (*challenge.Challenge, error) {
return &chall, err
}
// shouldRetryMissingTestCookie reports whether a client that reached
// PassChallenge without the verification cookie should be sent through a fresh
// challenge instead of being shown the cookies disabled error. Some browsers
// drop the verification cookie in edge cases such as an HTTP to HTTPS upgrade
// on the first navigation, and a fresh challenge then succeeds. See
// https://github.com/TecharoHQ/anubis/issues/1916
//
// A retry is only granted for a live, unspent challenge and at most once per
// client (IP address and User-Agent) per challenge lifetime, so clients that
// never send cookies get the error after one extra challenge instead of
// looping.
func (s *Server) shouldRetryMissingTestCookie(r *http.Request) bool {
chall, err := s.getChallenge(r)
if err != nil || chall.Spent {
return false
}
key := "cookie-retry:" + internal.SHA256sum(r.Header.Get("X-Real-IP")+":"+r.Header.Get("User-Agent"))
if _, err := s.store.Get(r.Context(), key); err == nil {
return false
}
// Same lifetime as an issued challenge.
return s.store.Set(r.Context(), key, []byte("1"), 30*time.Minute) == nil
}
func (s *Server) issueChallenge(ctx context.Context, r *http.Request, lg *slog.Logger, cr policy.CheckResult, rule *policy.Bot) (*challenge.Challenge, error) {
if cr.Rule != config.RuleChallenge {
slog.Error("this should be impossible, asked to issue a challenge but the rule is not a challenge rule", "cr", cr, "rule", rule)
slog.ErrorContext(ctx, "this should be impossible, asked to issue a challenge but the rule is not a challenge rule", "cr", cr, "rule", rule)
//return nil, errors.New("[unexpected] this codepath should be impossible, asked to issue a challenge for a non-challenge rule")
}
if rule.Challenge == nil {
rule.Challenge = &config.ChallengeRules{
Difficulty: s.policy.DefaultDifficulty,
Algorithm: config.DefaultAlgorithm,
}
}
id, err := uuid.NewV7()
if err != nil {
return nil, err
}
idStr := id.String()
var randomData = make([]byte, 64)
if _, err := rand.Read(randomData); err != nil {
@@ -117,24 +204,26 @@ func (s *Server) issueChallenge(ctx context.Context, r *http.Request, lg *slog.L
}
chall := challenge.Challenge{
ID: id.String(),
ID: idStr,
Method: rule.Challenge.Algorithm,
RandomData: fmt.Sprintf("%x", randomData),
RandomData: hex.EncodeToString(randomData),
IssuedAt: time.Now(),
Difficulty: rule.Challenge.Difficulty,
PolicyRuleHash: rule.Hash(),
Extensions: slices.Clone(rule.Challenge.Extensions),
Metadata: map[string]string{
"User-Agent": r.Header.Get("User-Agent"),
"X-Real-Ip": r.Header.Get("X-Real-Ip"),
"X-Real-IP": r.Header.Get("X-Real-IP"),
"Referer": r.Header.Get("Referer"),
},
}
j := store.JSON[challenge.Challenge]{Underlying: s.store}
if err := j.Set(ctx, "challenge:"+id.String(), chall, 30*time.Minute); err != nil {
if err := j.Set(ctx, "challenge:"+idStr, chall, 30*time.Minute); err != nil {
return nil, err
}
lg.Info("new challenge issued", "challenge", id.String())
lg.InfoContext(ctx, "new challenge issued", "challenge", idStr, "weight", cr.Weight)
return &chall, err
}
@@ -148,6 +237,14 @@ func (s *Server) hydrateChallengeRule(rule *policy.Bot, chall *challenge.Challen
rule = &policy.Bot{
Rules: &checker.List{},
}
} else {
copiedRule := *rule
if rule.Challenge != nil {
copiedChallenge := *rule.Challenge
copiedChallenge.Extensions = slices.Clone(rule.Challenge.Extensions)
copiedRule.Challenge = &copiedChallenge
}
rule = &copiedRule
}
if chall.Difficulty == 0 {
@@ -185,14 +282,51 @@ func (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request)
s.maybeReverseProxy(w, r, false)
}
func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {
lg := internal.GetRequestLogger(s.logger, r)
const (
downstreamRiskRuleHeader = "X-Anubis-Rule"
downstreamRiskActionHeader = "X-Anubis-Action"
downstreamRiskStatusHeader = "X-Anubis-Status"
)
if val, _ := s.store.Get(r.Context(), fmt.Sprintf("ogtags:allow:%s%s", r.Host, r.URL.String())); val != nil {
lg.Debug("serving opengraph tag asset")
s.ServeHTTPNext(w, r)
func isDownstreamRiskHeader(name string) bool {
switch http.CanonicalHeaderKey(name) {
case downstreamRiskRuleHeader, downstreamRiskActionHeader, downstreamRiskStatusHeader:
return true
}
return false
}
func removeDownstreamRiskConnectionTokens(header http.Header) {
connectionValues := header.Values("Connection")
header.Del("Connection")
for _, value := range connectionValues {
var remaining []string
for token := range strings.SplitSeq(value, ",") {
token = strings.TrimSpace(token)
if token == "" || isDownstreamRiskHeader(token) {
continue
}
remaining = append(remaining, token)
}
if len(remaining) != 0 {
header.Add("Connection", strings.Join(remaining, ", "))
}
}
}
func setDownstreamRiskHeaders(header http.Header, cr policy.CheckResult, status string) {
removeDownstreamRiskConnectionTokens(header)
header.Set(downstreamRiskRuleHeader, cr.Name)
header.Set(downstreamRiskActionHeader, string(cr.Rule))
if status == "" {
header.Del(downstreamRiskStatusHeader)
return
}
header.Set(downstreamRiskStatusHeader, status)
}
func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {
lg, r := s.getRequestLogger(r)
// Adjust cookie path if base prefix is not empty
cookiePath := "/"
@@ -202,18 +336,19 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
cr, rule, err := s.check(r, lg)
if err != nil {
lg.Error("check failed", "err", err)
lg.ErrorContext(r.Context(), "check failed", "err", err)
localizer := localization.GetLocalizer(r)
s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy\"", localizer.T("internal_server_error")), makeCode(err))
return
}
r.Header.Add("X-Anubis-Rule", cr.Name)
r.Header.Add("X-Anubis-Action", string(cr.Rule))
lg = lg.With("check_result", cr)
policy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)
{
asn, asnDesc := asnFromContext(r.Context())
policy.Applications.WithLabelValues(cr.Name, string(cr.Rule), asn, asnDesc).Add(1)
}
ip := r.Header.Get("X-Real-Ip")
ip := r.Header.Get("X-Real-IP")
if s.handleDNSBL(w, r, ip, lg) {
return
@@ -223,23 +358,25 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
return
}
ckie, err := r.Cookie(anubis.CookieName)
ckie, err := s.getCookie(r, anubis.CookieName)
if err != nil {
lg.Debug("cookie not found", "path", r.URL.Path)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
// Don't clear the cookie, there is none to clear. This response can land
// after a concurrent pass-challenge issued a valid one and would delete
// it. See https://github.com/TecharoHQ/anubis/issues/1314
lg.DebugContext(r.Context(), "cookie not found", "path", r.URL.Path)
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if err := ckie.Valid(); err != nil {
lg.Debug("cookie is invalid", "err", err)
lg.DebugContext(r.Context(), "cookie is invalid", "err", err)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {
lg.Debug("cookie expired", "path", r.URL.Path)
lg.DebugContext(r.Context(), "cookie expired", "path", r.URL.Path)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
@@ -248,7 +385,7 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
token, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())
if err != nil || !token.Valid {
lg.Debug("invalid token", "path", r.URL.Path, "err", err)
lg.DebugContext(r.Context(), "invalid token", "path", r.URL.Path, "err", err)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
@@ -256,7 +393,7 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
lg.Debug("invalid token claims type", "path", r.URL.Path)
lg.DebugContext(r.Context(), "invalid token claims type", "path", r.URL.Path)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
@@ -264,30 +401,49 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
policyRule, ok := claims["policyRule"].(string)
if !ok {
lg.Debug("policyRule claim is not a string")
lg.DebugContext(r.Context(), "policyRule claim is not a string")
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if policyRule != rule.Hash() {
lg.Debug("user originally passed with a different rule, issuing new challenge", "old", policyRule, "new", rule.Name)
lg.DebugContext(r.Context(), "user originally passed with a different rule, issuing new challenge", "old", policyRule, "new", rule.Name)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if s.opts.JWTRestrictionHeader != "" && claims["restriction"] != internal.SHA256sum(r.Header.Get(s.opts.JWTRestrictionHeader)) {
lg.Debug("JWT restriction header is invalid")
lg.DebugContext(r.Context(), "JWT restriction header is invalid")
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
r.Header.Add("X-Anubis-Status", "PASS")
s.restoreOriginalReferer(w, r, cookiePath)
setDownstreamRiskHeaders(r.Header, cr, "PASS")
s.ServeHTTPNext(w, r)
}
// restoreOriginalReferer looks for the one-shot cookie set by PassChallenge and, if
// present, overwrites the request's Referer header with the value it carries before
// the request is proxied upstream. The cookie only survives the single redirect from
// PassChallenge back to the original URL, so this only ever fires for that one request.
func (s *Server) restoreOriginalReferer(w http.ResponseWriter, r *http.Request, cookiePath string) {
ckie, err := s.getCookie(r, anubis.OriginalRefererCookieName)
if err != nil || ckie.Value == "" {
return
}
s.ClearCookie(w, CookieOpts{Name: anubis.OriginalRefererCookieName, Path: cookiePath, Host: r.Host})
if referer, err := url.QueryUnescape(ckie.Value); err == nil {
r.Header.Set("Referer", referer)
}
}
func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {
// Adjust cookie path if base prefix is not empty
cookiePath := "/"
@@ -299,31 +455,32 @@ func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.Ch
switch cr.Rule {
case config.RuleAllow:
lg.Debug("allowing traffic to origin (explicit)")
lg.DebugContext(r.Context(), "allowing traffic to origin (explicit)")
setDownstreamRiskHeaders(r.Header, cr, "")
s.ServeHTTPNext(w, r)
return true
case config.RuleDeny:
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
lg.Info("explicit deny")
lg.InfoContext(r.Context(), "explicit deny")
if rule == nil {
lg.Error("rule is nil, cannot calculate checksum")
lg.ErrorContext(r.Context(), "rule is nil, cannot calculate checksum")
s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy.RuleDeny\"", localizer.T("internal_server_error")), makeCode(ErrActualAnubisBug))
return true
}
hash := rule.Hash()
lg.Debug("rule hash", "hash", hash)
lg.DebugContext(r.Context(), "rule hash", "hash", hash)
s.respondWithStatus(w, r, fmt.Sprintf("%s %s", localizer.T("access_denied"), hash), "", s.policy.StatusCodes.Deny)
return true
case config.RuleChallenge:
lg.Debug("challenge requested")
lg.DebugContext(r.Context(), "challenge requested")
case config.RuleBenchmark:
lg.Debug("serving benchmark page")
lg.DebugContext(r.Context(), "serving benchmark page")
s.RenderBench(w, r)
return true
default:
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
lg.Error("CONFIG ERROR: unknown rule", "rule", cr.Rule)
lg.ErrorContext(r.Context(), "CONFIG ERROR: unknown rule", "rule", cr.Rule)
s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy.Rules\"", localizer.T("internal_server_error")), makeCode(ErrActualAnubisBug))
return true
}
@@ -331,21 +488,28 @@ func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.Ch
}
func (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {
return s.handleDNSBLWithLookup(w, r, ip, lg, dnsbl.Lookup)
}
func (s *Server) handleDNSBLWithLookup(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger, lookup func(string) (dnsbl.DroneBLResponse, error)) bool {
db := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: "dronebl:"}
if s.policy.DNSBL && ip != "" {
resp, err := db.Get(r.Context(), ip)
if err != nil {
lg.Debug("looking up ip in dnsbl")
resp, err := dnsbl.Lookup(ip)
lg.DebugContext(r.Context(), "looking up ip in dnsbl")
resp, err = lookup(ip)
if err != nil {
lg.Error("can't look up ip in dnsbl", "err", err)
lg.ErrorContext(r.Context(), "can't look up ip in dnsbl", "err", err)
s.respondWithStatus(w, r, localization.GetLocalizer(r).T("internal_server_error"), "", http.StatusServiceUnavailable)
return true
}
db.Set(r.Context(), ip, resp, 24*time.Hour)
droneBLHits.WithLabelValues(resp.String()).Inc()
_ = db.Set(r.Context(), ip, resp, 24*time.Hour) // worst case we do the dns lookup again
asn, asnDesc := asnFromContext(r.Context())
droneBLHits.WithLabelValues(resp.String(), asn, asnDesc).Inc()
}
if resp != dnsbl.AllGood {
lg.Info("DNSBL hit", "status", resp.String())
lg.InfoContext(r.Context(), "DNSBL hit", "status", resp.String())
localizer := localization.GetLocalizer(r)
s.respondWithStatus(w, r, fmt.Sprintf("%s: %s, %s https://dronebl.org/lookup?ip=%s",
localizer.T("dronebl_entry"),
@@ -359,19 +523,25 @@ func (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string,
}
func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
lg := internal.GetRequestLogger(s.logger, r)
if !prepareChallengeForm(w, r) {
return
}
defer cleanupChallengeForm(r)
lg, r := s.getRequestLogger(r)
localizer := localization.GetLocalizer(r)
redir := r.FormValue("redir")
if redir == "" {
w.WriteHeader(http.StatusBadRequest)
encoder := json.NewEncoder(w)
lg.Error("invalid invocation of MakeChallenge", "redir", redir)
encoder.Encode(struct {
lg.ErrorContext(r.Context(), "invalid invocation of MakeChallenge", "redir", redir)
if err := encoder.Encode(struct {
Error string `json:"error"`
}{
Error: localizer.T("invalid_invocation"),
})
}); err != nil {
s.logger.DebugContext(r.Context(), "can't write invalid invocation error to client, did they disconnect?", "err", err)
}
return
}
@@ -380,7 +550,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(w)
cr, rule, err := s.check(r, lg)
if err != nil {
lg.Error("check failed", "err", err)
lg.ErrorContext(r.Context(), "check failed", "err", err)
w.WriteHeader(http.StatusInternalServerError)
err := encoder.Encode(struct {
Error string `json:"error"`
@@ -388,7 +558,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
Error: fmt.Sprintf("%s \"makeChallenge\"", localizer.T("internal_server_error")),
})
if err != nil {
lg.Error("failed to encode error response", "err", err)
lg.ErrorContext(r.Context(), "failed to encode error response", "err", err)
w.WriteHeader(http.StatusInternalServerError)
}
return
@@ -397,7 +567,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
chall, err := s.issueChallenge(r.Context(), r, lg, cr, rule)
if err != nil {
lg.Error("failed to fetch or issue challenge", "err", err)
lg.ErrorContext(r.Context(), "failed to fetch or issue challenge", "err", err)
w.WriteHeader(http.StatusInternalServerError)
err := encoder.Encode(struct {
Error string `json:"error"`
@@ -405,7 +575,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
Error: fmt.Sprintf("%s \"makeChallenge\"", localizer.T("internal_server_error")),
})
if err != nil {
lg.Error("failed to encode error response", "err", err)
lg.ErrorContext(r.Context(), "failed to encode error response", "err", err)
w.WriteHeader(http.StatusInternalServerError)
}
return
@@ -423,32 +593,40 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
ID: chall.ID,
})
if err != nil {
lg.Error("failed to encode challenge", "err", err)
lg.ErrorContext(r.Context(), "failed to encode challenge", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
lg.Debug("made challenge", "challenge", chall, "rules", rule.Challenge, "cr", cr)
challengesIssued.WithLabelValues("api").Inc()
lg.DebugContext(r.Context(), "made challenge", "challenge", chall, "rules", rule.Challenge, "cr", cr)
{
asn, asnDesc := asnFromContext(r.Context())
challengesIssued.WithLabelValues("api", asn, asnDesc).Inc()
}
}
func (s *Server) validateExtension(name string, r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {
ext, ok := extension.Get(name)
if !ok {
return fmt.Errorf("%w: %q", ErrUnknownChallengeExtension, name)
}
return ext.Validate(r, lg, in)
}
func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
lg := internal.GetRequestLogger(s.logger, r)
if !prepareChallengeForm(w, r) {
return
}
defer cleanupChallengeForm(r)
lg, r := s.getRequestLogger(r)
localizer := localization.GetLocalizer(r)
redir := r.FormValue("redir")
redirURL, err := url.ParseRequestURI(redir)
if err != nil {
lg.Error("invalid redirect", "err", err)
s.respondWithStatus(w, r, localizer.T("invalid_redirect"), makeCode(err), http.StatusBadRequest)
return
redirURL, err := s.validateRedirect(redir)
if err == nil && (redir == "" || (redirURL.Scheme == "" && !strings.HasPrefix(redir, "/"))) {
err = ErrInvalidRedirect
}
switch redirURL.Scheme {
case "", "http", "https":
// allowed
default:
lg.Error("XSS attempt blocked, invalid redirect scheme", "scheme", redirURL.Scheme)
s.respondWithStatus(w, r, localizer.T("invalid_redirect"), "", http.StatusBadRequest)
if err != nil {
s.rejectRedirect(w, r, err)
return
}
@@ -458,10 +636,15 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
}
if _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {
if _, err := s.getCookie(r, anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})
lg.Warn("user has cookies disabled, this is not an anubis bug")
if s.shouldRetryMissingTestCookie(r) {
lg.DebugContext(r.Context(), "verification cookie missing, retrying with a fresh challenge")
http.Redirect(w, r, redir, http.StatusFound)
return
}
lg.WarnContext(r.Context(), "user has cookies disabled, this is not an anubis bug")
s.respondWithError(w, r, localizer.T("cookies_disabled"), "")
return
}
@@ -469,43 +652,44 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
// used by the path checker rule
r.URL = redirURL
urlParsed, err := r.URL.Parse(redir)
if err != nil {
s.respondWithError(w, r, localizer.T("redirect_not_parseable"), makeCode(err))
return
}
if (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !matchRedirectDomain(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {
lg.Debug("domain not allowed", "domain", urlParsed.Host)
s.respondWithError(w, r, localizer.T("redirect_domain_not_allowed"), "")
return
}
cr, rule, err := s.check(r, lg)
if err != nil {
lg.Error("check failed", "err", err)
lg.ErrorContext(r.Context(), "check failed", "err", err)
s.respondWithError(w, r, fmt.Sprintf("%s \"passChallenge\"", localizer.T("internal_server_error")), makeCode(err))
return
}
lg = lg.With("check_result", cr)
lockIndex := sha256.Sum256([]byte(r.FormValue("id")))
lock := &s.challengeLocks[lockIndex[0]]
lock.Lock()
defer lock.Unlock()
chall, err := s.getChallenge(r)
if err != nil {
lg.Error("getChallenge failed", "err", err)
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), rule.Challenge.Algorithm), makeCode(err))
lg.ErrorContext(r.Context(), "getChallenge failed", "err", err)
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), "getChallenge failed"), makeCode(err))
return
}
if chall.Spent {
lg.Error("double spend prevented", "reason", "double_spend")
lg.ErrorContext(r.Context(), "double spend prevented", "reason", "double_spend")
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), "double_spend"), "")
return
}
if cr.Rule != config.RuleChallenge || rule == nil || rule.Challenge == nil ||
chall.PolicyRuleHash != rule.Hash() || chall.Method != rule.Challenge.Algorithm ||
chall.Difficulty != rule.Challenge.Difficulty || !slices.Equal(chall.Extensions, rule.Challenge.Extensions) {
s.respondWithStatus(w, r, localizer.T("internal_server_error"), makeCode(challenge.ErrFailed), http.StatusForbidden)
return
}
rule = s.hydrateChallengeRule(rule, chall, lg)
impl, ok := challenge.Get(chall.Method)
if !ok {
lg.Error("check failed", "err", err)
lg.ErrorContext(r.Context(), "check failed", "err", err)
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), rule.Challenge.Algorithm), makeCode(ErrActualAnubisBug))
return
}
@@ -519,26 +703,56 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
}
if err := impl.Validate(r, lg, in); err != nil {
failedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()
asn, asnDesc := asnFromContext(r.Context())
failedValidations.WithLabelValues(rule.Challenge.Algorithm, asn, asnDesc).Inc()
var cerr *challenge.Error
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
lg.Debug("challenge validate call failed", "err", err)
lg.DebugContext(r.Context(), "challenge validate call failed", "err", err)
switch {
case errors.As(err, &cerr):
switch {
case errors.Is(err, challenge.ErrFailed):
lg.Error("challenge failed", "err", err)
lg.ErrorContext(r.Context(), "challenge failed", "err", err)
s.respondWithStatus(w, r, cerr.PublicReason, makeCode(err), cerr.StatusCode)
return
case errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):
lg.Error("invalid challenge format", "err", err)
lg.ErrorContext(r.Context(), "invalid challenge format", "err", err)
s.respondWithError(w, r, cerr.PublicReason, makeCode(err))
return
}
}
s.respondWithError(w, r, localizer.T("internal_server_error"), makeCode(err))
return
}
for _, name := range chall.Extensions {
if err := s.validateExtension(name, r, lg, in); err != nil {
asn, asnDesc := asnFromContext(r.Context())
failedValidations.WithLabelValues("extension/"+name, asn, asnDesc).Inc()
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
lg.ErrorContext(r.Context(), "challenge extension failed", "extension", name, "err", err)
var cerr *challenge.Error
if errors.As(err, &cerr) {
s.respondWithStatus(w, r, cerr.PublicReason, makeCode(err), cerr.StatusCode)
} else {
s.respondWithError(w, r, localizer.T("internal_server_error"), makeCode(err))
}
return
}
}
chall.Spent = true
j := store.JSON[challenge.Challenge]{Underlying: s.store}
if err := j.Set(r.Context(), "challenge:"+chall.ID, *chall, 30*time.Minute); err != nil {
lg.DebugContext(r.Context(), "can't update information about challenge", "err", err)
s.respondWithError(w, r, localizer.T("internal_server_error"), makeCode(err))
return
}
lg.InfoContext(r.Context(), "challenge accepted")
// generate JWT cookie
var tokenString string
@@ -551,7 +765,7 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
}
if s.opts.JWTRestrictionHeader != "" {
if r.Header.Get(s.opts.JWTRestrictionHeader) == "" {
lg.Error("JWTRestrictionHeader is set in config but not found in request, please check your reverse proxy config.")
lg.ErrorContext(r.Context(), "JWTRestrictionHeader is set in config but not found in request, please check your reverse proxy config.")
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.respondWithError(w, r, "failed to sign JWT", makeCode(err))
return
@@ -565,7 +779,7 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
tokenString, err = s.signJWT(claims)
if err != nil {
lg.Error("failed to sign JWT", "err", err)
lg.ErrorContext(r.Context(), "failed to sign JWT", "err", err)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.respondWithError(w, r, localizer.T("failed_to_sign_jwt"), makeCode(err))
return
@@ -573,15 +787,69 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
s.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})
chall.Spent = true
j := store.JSON[challenge.Challenge]{Underlying: s.store}
if err := j.Set(r.Context(), "challenge:"+chall.ID, *chall, 30*time.Minute); err != nil {
lg.Debug("can't update information about challenge", "err", err)
if origReferer := chall.Metadata["Referer"]; origReferer != "" {
s.SetCookie(w, CookieOpts{
Path: cookiePath,
Host: r.Host,
Name: anubis.OriginalRefererCookieName,
Value: url.QueryEscape(origReferer),
Expiry: 1 * time.Minute,
})
}
challengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()
lg.Debug("challenge passed, redirecting to app")
http.Redirect(w, r, redir, http.StatusFound)
{
asn, asnDesc := asnFromContext(r.Context())
challengesValidated.WithLabelValues(rule.Challenge.Algorithm, asn, asnDesc).Inc()
}
lg.DebugContext(r.Context(), "challenge passed, redirecting to app")
http.Redirect(w, r, s.withRefererAttributionQuery(redir, chall.Metadata["Referer"], r.Host), http.StatusFound)
}
// refererAttributionQueryParams lists query parameters that already carry
// campaign or referrer attribution. When the redirect target has any of these,
// withRefererAttributionQuery leaves it alone rather than overwrite genuine
// campaign data.
var refererAttributionQueryParams = []string{
"ref", "source",
"utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term",
"gclid", "msclkid",
}
// withRefererAttributionQuery appends utm_source/utm_medium query parameters
// derived from the original external Referer to redir, so client-side analytics
// tools that fall back to query parameters when document.referrer is unusable
// (e.g. Plausible, GA4) can still attribute the visit. This exists because
// document.referrer itself cannot be fixed here: it reflects the browser's
// actual navigation history -- the challenge page -- and neither Anubis nor any
// page script can override it. Opt-in via PreserveRefererQueryParam since it
// changes the URL the visitor lands on. See
// https://github.com/TecharoHQ/anubis/issues/1596
func (s *Server) withRefererAttributionQuery(redir, origReferer, host string) string {
if !s.opts.PreserveRefererQueryParam || origReferer == "" {
return redir
}
refURL, err := url.Parse(origReferer)
if err != nil || refURL.Host == "" || refURL.Host == host {
return redir
}
u, err := url.Parse(redir)
if err != nil {
return redir
}
q := u.Query()
for _, name := range refererAttributionQueryParams {
if q.Has(name) {
return redir
}
}
q.Set("utm_source", refURL.Host)
q.Set("utm_medium", "referral")
u.RawQuery = q.Encode()
return u.String()
}
func cr(name string, rule config.Rule, weight int) policy.CheckResult {
@@ -594,9 +862,12 @@ func cr(name string, rule config.Rule, weight int) policy.CheckResult {
// Check evaluates the list of rules, and returns the result
func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *policy.Bot, error) {
host := r.Header.Get("X-Real-Ip")
if err := s.policy.ValidateRequestPath(r); err != nil {
return policy.CheckResult{}, nil, err
}
host := r.Header.Get("X-Real-IP")
if host == "" {
return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("[misconfiguration] X-Real-Ip header is not set")
return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("[misconfiguration] X-Real-IP header is not set")
}
addr := net.ParseIP(host)
@@ -606,7 +877,9 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
weight := 0
for _, b := range s.policy.Bots {
// Ranging by index keeps b from escaping to the heap on every iteration.
for i := range s.policy.Bots {
b := &s.policy.Bots[i]
match, err := b.Rules.Check(r)
if err != nil {
return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("can't run check %s: %w", b.Name, err)
@@ -615,10 +888,13 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
if match {
switch b.Action {
case config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:
return cr("bot/"+b.Name, b.Action, weight), &b, nil
// Return a copy of the rule, as the shared policy must not be modified.
bot := *b
return cr("bot/"+b.Name, b.Action, weight), &bot, nil
case config.RuleWeigh:
lg.Debug("adjusting weight", "name", b.Name, "delta", b.Weight.Adjust)
policy.Applications.WithLabelValues("bot/"+b.Name, "WEIGH").Add(1)
lg.DebugContext(r.Context(), "adjusting weight", "name", b.Name, "delta", b.Weight.Adjust)
asn, asnDesc := asnFromContext(r.Context())
policy.Applications.WithLabelValues("bot/"+b.Name, "WEIGH", asn, asnDesc).Add(1)
weight += b.Weight.Adjust
}
}
@@ -627,7 +903,7 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
for _, t := range s.policy.Thresholds {
result, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})
if err != nil {
lg.Error("error when evaluating threshold expression", "expression", t.Expression.String(), "err", err)
lg.ErrorContext(r.Context(), "error when evaluating threshold expression", "expression", t.Expression.String(), "err", err)
continue
}
@@ -638,14 +914,30 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
}
if matches {
challRules := t.Challenge
if challRules == nil {
// Non-CHALLENGE thresholds (ALLOW/DENY) don't have challenge config.
// Use an empty struct so hydrateChallengeRule can fill from stored
// challenge data during validation, rather than baking in defaults
// that could mismatch the difficulty the client actually solved for.
challRules = &config.ChallengeRules{}
}
identity, err := json.Marshal(t.Threshold)
if err != nil {
return policy.CheckResult{}, nil, err
}
return cr("threshold/"+t.Name, t.Action, weight), &policy.Bot{
Challenge: t.Challenge,
Name: "threshold/" + t.Name + ":" + internal.FastHash(string(identity)),
Action: t.Action,
Challenge: challRules,
Rules: &checker.List{},
}, nil
}
}
return cr("default/allow", config.RuleAllow, weight), &policy.Bot{
Name: "default/allow",
Action: config.RuleAllow,
Challenge: &config.ChallengeRules{
Difficulty: s.policy.DefaultDifficulty,
Algorithm: config.DefaultAlgorithm,
+705 -156
View File
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
package lib
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/TecharoHQ/anubis/lib/geoip/geoiptest"
)
func TestGetRequestLoggerASN(t *testing.T) {
for _, tt := range []struct {
name string
logASN bool
withDB bool
ip string
wantASN string
wantDesc string
}{
{name: "announced", logASN: true, withDB: true, ip: "1.1.1.1", wantASN: "13335", wantDesc: "Cloudflare, Inc."},
{name: "private", logASN: true, withDB: true, ip: "10.0.0.1"},
{name: "not an IP", logASN: true, withDB: true, ip: "taco"},
{name: "logging disabled", withDB: true, ip: "1.1.1.1"},
{name: "no database", logASN: true, ip: "1.1.1.1"},
} {
t.Run(tt.name, func(t *testing.T) {
pol := loadPolicies(t, "", 4)
pol.LogASN = tt.logASN
pol.GeoIP = nil
if tt.withDB {
pol.GeoIP = geoiptest.DB(t)
}
srv := spawnAnubis(t, Options{Policy: pol})
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Real-IP", tt.ip)
_, req = srv.getRequestLogger(req)
asn, desc := asnFromContext(req.Context())
if asn != tt.wantASN || desc != tt.wantDesc {
t.Errorf("want (%q, %q), got (%q, %q)", tt.wantASN, tt.wantDesc, asn, desc)
}
})
}
}
+1
View File
@@ -12,4 +12,5 @@ type Challenge struct {
PolicyRuleHash string `json:"policyRuleHash,omitempty"` // Hash of the policy rule that issued this challenge
Difficulty int `json:"difficulty,omitempty"` // Difficulty that was in effect when issued
Spent bool `json:"spent"` // Has the challenge already been solved?
Extensions []string `json:"extensions"` // Challenge extensions that must validate before a JWT is issued
}
+28
View File
@@ -0,0 +1,28 @@
// Package challengepage holds the parts of the challenge page that every
// JavaScript-driven challenge method needs.
package challengepage
import (
"context"
_ "embed"
"io"
"github.com/a-h/templ"
)
//go:generate ./build.sh
//go:embed static/js/bootstrap.mjs
var scriptBytes string
// Bootstrap renders the inline watchdog script that re-injects main.mjs when
// it fails to load. It must be rendered after the script tag it watches so
// that the tag exists by the time this runs during page parse.
func Bootstrap() templ.Component {
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
if _, err := io.WriteString(w, "<script>"+scriptBytes+"</script>"); err != nil {
return err
}
return nil
})
}
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
LICENSE='/*
@licstart The following is the entire license notice for the
JavaScript code in this page.
Copyright (c) 2026 Xe Iaso <xe.iaso@techaro.lol>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@licend The above is the entire license notice
for the JavaScript code in this page.
## Rationale
This script catches `main.mjs` failing to load and re-injects it with
jittered exponential backoff.
Without this any failures loading `main.mjs` leaves the challenge page
sitting on the "Loading..." message forever with no error messaging
outside of the browser console, which is unavailable on mobile browsers.
Disable loading this script at your peril. You have been warned.
*/'
mkdir -p static/js
shopt -s nullglob globstar
for file in js/**/*.ts js/**/*.mjs; do
# Mirrors web/build.sh: js/lib/ is for shared modules, not entry points.
if [[ "$file" == js/lib/* ]]; then
continue
fi
out="static/${file}"
if [[ "$file" == *.ts ]]; then
out="static/${file%.ts}.mjs"
fi
mkdir -p "$(dirname "$out")"
esbuild "$file" --bundle --minify --target=chrome66 --outfile="$out" --banner:js="$LICENSE"
done
@@ -0,0 +1,20 @@
package challengepage
import (
"html"
"regexp"
)
//go:generate go tool github.com/a-h/templ/cmd/templ generate
// wikipediaLink matches an escaped Wikipedia anchor tag in translated text.
// The URL character set is restricted so that nothing in it can break out of
// the href attribute.
var wikipediaLink = regexp.MustCompile(`&lt;a href=&#34;(https://[a-z-]{2,12}\.wikipedia\.org/wiki/[A-Za-z0-9_-]+)&#34;&gt;(.*?)&lt;/a&gt;`)
// explanationHTML escapes translated text and then restores only anchor tags
// pointing at Wikipedia. Translations are community-contributed, so they must
// never be rendered as raw HTML.
func explanationHTML(text string) string {
return wikipediaLink.ReplaceAllString(html.EscapeString(text), `<a href="$1">$2</a>`)
}
@@ -0,0 +1,15 @@
package challengepage
import "github.com/TecharoHQ/anubis/lib/localization"
// Explanation renders the "Why am I seeing this?" details block.
templ Explanation(localizer *localization.SimpleLocalizer) {
<details>
<p>
@templ.Raw(explanationHTML(localizer.T("simplified_explanation")))
</p>
<p>
{ localizer.T("jshelter_note") }
</p>
</details>
}
+64
View File
@@ -0,0 +1,64 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1070
package challengepage
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import "github.com/TecharoHQ/anubis/lib/localization"
// Explanation renders the "Why am I seeing this?" details block.
func Explanation(localizer *localization.SimpleLocalizer) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<details><p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.Raw(explanationHTML(localizer.T("simplified_explanation"))).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "</p><p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("jshelter_note"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `explanation.templ`, Line: 12, Col: 33}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "</p></details>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
var _ = templruntime.GeneratedTemplate
@@ -0,0 +1,103 @@
package challengepage
import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/TecharoHQ/anubis/lib/localization"
)
func TestExplanationHTML(t *testing.T) {
for _, tt := range []struct {
name string
in string
want string
}{
{
name: "plain text",
in: "hello & goodbye",
want: "hello &amp; goodbye",
},
{
name: "wikipedia link",
in: `called <a href="https://en.wikipedia.org/wiki/Proof_of_work">Proof of Work</a>.`,
want: `called <a href="https://en.wikipedia.org/wiki/Proof_of_work">Proof of Work</a>.`,
},
{
name: "localized wikipedia link",
in: `<a href="https://de.wikipedia.org/wiki/Proof_of_Work">Proof of Work</a>`,
want: `<a href="https://de.wikipedia.org/wiki/Proof_of_Work">Proof of Work</a>`,
},
{
name: "script tag",
in: `<script>alert(1)</script>`,
want: `&lt;script&gt;alert(1)&lt;/script&gt;`,
},
{
name: "javascript href",
in: `<a href="javascript:alert(1)">x</a>`,
want: `&lt;a href=&#34;javascript:alert(1)&#34;&gt;x&lt;/a&gt;`,
},
{
name: "attribute breakout",
in: `<a href="https://en.wikipedia.org/wiki/X" onclick="alert(1)">x</a>`,
want: `&lt;a href=&#34;https://en.wikipedia.org/wiki/X&#34; onclick=&#34;alert(1)&#34;&gt;x&lt;/a&gt;`,
},
{
name: "markup inside link text",
in: `<a href="https://en.wikipedia.org/wiki/X"><img src=x onerror=alert(1)></a>`,
want: `<a href="https://en.wikipedia.org/wiki/X">&lt;img src=x onerror=alert(1)&gt;</a>`,
},
} {
t.Run(tt.name, func(t *testing.T) {
if got := explanationHTML(tt.in); got != tt.want {
t.Errorf("explanationHTML(%q)\n got: %s\nwant: %s", tt.in, got, tt.want)
}
})
}
}
// TestExplanationRendersLink makes sure no shipped translation of
// simplified_explanation renders its Proof of Work link as escaped text.
func TestExplanationRendersLink(t *testing.T) {
files, err := filepath.Glob("../../localization/locales/*.json")
if err != nil {
t.Fatal(err)
}
for _, fname := range files {
lang := strings.TrimSuffix(filepath.Base(fname), ".json")
if lang == "manifest" {
continue
}
t.Run(lang, func(t *testing.T) {
data, err := os.ReadFile(fname)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "wikipedia.org") {
t.Skip("translation has no link")
}
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("Accept-Language", lang)
var sb strings.Builder
if err := Explanation(localization.GetLocalizer(req)).Render(t.Context(), &sb); err != nil {
t.Fatal(err)
}
out := sb.String()
if strings.Contains(out, "&lt;a") || strings.Contains(out, "&lt;/a") {
t.Errorf("rendered explanation contains escaped anchor markup: %s", out)
}
if !strings.Contains(out, `<a href="https://`) {
t.Errorf("rendered explanation has no link: %s", out)
}
})
}
}
+117
View File
@@ -0,0 +1,117 @@
// Watch for `main.mjs` failing to load and re-injects it with jittered
// exponential backoff.
//
// Without this any failures loading `main.mjs` leaves the challenge page
// sitting on the "Loading..." message forever with no error messaging
// outside of the browser console, which is unavailable on mobile browsers.
//
// This is the worst way for Anubis to fail because it requires the user
// to manually reload the webpage, which fails the main design goal of
// the proof of work challenges: no user interaction is required to pass
// challenges. Paradoxically, this would increase the level of load to
// an already overwhelmed server, making the problem much worse.
//
// This is injected into the page as a raw constant embedded from this
// file instead of loaded dynamically so that things are more reliable.
//
// A few notes on the implementation of this and why it makes some weird
// assumptions about the browser environment:
//
// - Loading a module script uses a slightly different internal fetch path
// than loading it as a normal javascript script. As such, if you try to
// re-load _the exact same_ URL you end up getting a cached fetch
// failure, which then amplifies the problem and makes the logic _never_
// load. This is bad, so we have to inject extra URL parameters to the
// Anubis server.
// - The canonical way to solve this in a `<script>` tag is the
// `script.onerror` property, which sadly does not fire for every kind of
// failure that is relevant to Anubis. As a result we have to use a
// watchdog timer to ensure the `main.mjs` file actually booted.
import { backoffDelay } from "@lib/backoff";
import { g, h } from "@lib/xeact.mjs";
const getMany = (ids: string[]): (HTMLElement | null)[] => ids.map(g);
(() => {
const tag = g("anubis-main");
if (!tag) {
console.debug(
"can't find anubis main.mjs element via ID `anubis-main`, bailing",
);
return;
}
const src = tag.getAttribute("src");
if (!src) {
console.debug(
"can't find src attribute of script element `anubis-main`, bailing",
);
return;
}
const joiner = src.indexOf("?") === -1 ? "?" : "&";
const MAX_ATTEMPTS = 4;
const BASE_DELAY_MS = 750;
const MAX_DELAY_MS = 10000;
// XXX(Xe): this timer is overly generous to account for mobile connections
// and/or German train Wi-Fi.
const WATCHDOG_MS = 10000;
let attempt = 0;
let generation = 0;
const booted = () =>
// @ts-ignore: global variable set by main.mjs
(window as any).__anubisBooted === true;
const fail = () => {
const els = getMany(["anubis-script-error", "status", "progress"]);
if (els.filter((x) => x == null).length !== 0) {
console.debug(
"missing one of the following elements: anubis-script-error, status, progress. cannot proceed, bailing.",
);
return;
}
const [el, status, progress] = els as HTMLElement[];
el.style.display = "block";
status.style.display = "none";
progress.style.display = "none";
};
const settleFor = (gen: number) => () => {
if (booted() || gen !== generation) {
return;
}
generation++;
attempt++;
if (attempt > MAX_ATTEMPTS) {
fail();
return;
}
const delay = backoffDelay(attempt, BASE_DELAY_MS, MAX_DELAY_MS);
setTimeout(inject, delay);
};
const inject = () => {
if (booted()) {
return;
}
const settle = settleFor(generation);
const s = h("script", {
async: true,
type: "module",
src: src + joiner + "anubisRetry=" + attempt,
onerror: settle,
});
document.head.appendChild(s);
setTimeout(settle, WATCHDOG_MS);
};
const initial = settleFor(0);
tag.onerror = initial;
setTimeout(initial, WATCHDOG_MS);
})();
@@ -0,0 +1,2 @@
*
!.gitignore
@@ -0,0 +1,39 @@
/*
@licstart The following is the entire license notice for the
JavaScript code in this page.
Copyright (c) 2026 Xe Iaso <xe.iaso@techaro.lol>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@licend The above is the entire license notice
for the JavaScript code in this page.
## Rationale
This script catches `main.mjs` failing to load and re-injects it with
jittered exponential backoff.
Without this any failures loading `main.mjs` leaves the challenge page
sitting on the "Loading..." message forever with no error messaging
outside of the browser console, which is unavailable on mobile browsers.
Disable loading this script at your peril. You have been warned.
*/
(()=>{var f=(e,t=750,n=1e4)=>Math.random()*Math.min(n,t*Math.pow(e,2));var d=(e,t={},n=[])=>{let s=typeof e=="function"?e(t):Object.assign(document.createElement(e),t);return Array.isArray(n)||(n=[n]),s.append(...n),s};var i=e=>document.getElementById(e);var _=e=>e.map(i);(()=>{let e=i("anubis-main");if(!e){console.debug("can't find anubis main.mjs element via ID `anubis-main`, bailing");return}let t=e.getAttribute("src");if(!t){console.debug("can't find src attribute of script element `anubis-main`, bailing");return}let n=t.indexOf("?")===-1?"?":"&",s=4,E=750,A=1e4,c=1e4,a=0,l=0,u=()=>window.__anubisBooted===!0,p=()=>{let r=_(["anubis-script-error","status","progress"]);if(r.filter(D=>D==null).length!==0){console.debug("missing one of the following elements: anubis-script-error, status, progress. cannot proceed, bailing.");return}let[o,M,T]=r;o.style.display="block",M.style.display="none",T.style.display="none"},m=r=>()=>{if(u()||r!==l)return;if(l++,a++,a>s){p();return}let o=f(a,E,A);setTimeout(y,o)},y=()=>{if(u())return;let r=m(l),o=d("script",{async:!0,type:"module",src:t+n+"anubisRetry="+a,onerror:r});document.head.appendChild(o),setTimeout(r,c)},b=m(0);e.onerror=b,setTimeout(b,c)})();})();
+1
View File
@@ -10,6 +10,7 @@ var (
ErrFailed = errors.New("challenge: user failed challenge")
ErrMissingField = errors.New("challenge: missing field")
ErrInvalidFormat = errors.New("challenge: field has invalid format")
ErrInvalidInput = errors.New("challenge: input is nil or missing required fields")
)
func NewError(verb, publicReason string, privateReason error) *Error {
@@ -0,0 +1,96 @@
package cssload
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"time"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/challenge/extension"
"github.com/TecharoHQ/anubis/lib/store"
"github.com/a-h/templ"
"github.com/google/uuid"
)
const (
validPrefix = "ext:css-load:valid:"
storePrefix = "ext:css-load:seen:"
)
func init() {
extension.Register("css-load", &Impl{})
}
type Impl struct {
st store.Interface
}
func (i *Impl) cssFolder() string {
return anubis.BasePrefix + "/.within.website/x/cmd/anubis/ext/css-load"
}
func (i *Impl) Setup(mux *http.ServeMux, st store.Interface) error {
i.st = st
mux.HandleFunc(fmt.Sprintf("GET %s/{challengeID}", i.cssFolder()), i.renderCSS)
return nil
}
func (i *Impl) Head(r *http.Request, chall *challenge.Challenge) templ.Component {
key := chall.ID
validCh := store.JSON[struct{}]{Underlying: i.st, Prefix: validPrefix}
if _, err := validCh.Get(r.Context(), key); errors.Is(err, store.ErrNotFound) {
validCh.Set(context.WithoutCancel(r.Context()), key, struct{}{}, 30*time.Minute) //nolint:errcheck
}
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
_, err := fmt.Fprintf(w, `<style>@import url("%s");</style>`, (&url.URL{Path: i.cssFolder() + "/" + key}).EscapedPath())
return err
})
}
func (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {
seen := store.JSON[struct{}]{Underlying: i.st, Prefix: storePrefix}
_, err := seen.Get(r.Context(), in.Challenge.ID)
switch {
case errors.Is(err, store.ErrNotFound):
return challenge.NewError("css-load", "Please ensure your browser has modern web standards enabled", fmt.Errorf("%w: CSS was not fetched", challenge.ErrFailed))
case err != nil:
lg.DebugContext(r.Context(), "store unavailable", "err", err)
return err
}
return nil
}
func (i *Impl) renderCSS(w http.ResponseWriter, r *http.Request) {
validCh := store.JSON[struct{}]{Underlying: i.st, Prefix: validPrefix}
seen := store.JSON[struct{}]{Underlying: i.st, Prefix: storePrefix}
chID := r.PathValue("challengeID")
chIDo, err := uuid.Parse(chID)
if err != nil {
http.NotFound(w, r)
return
}
if _, err := validCh.Get(r.Context(), chIDo.String()); err != nil {
http.NotFound(w, r)
return
}
seen.Set(r.Context(), chIDo.String(), struct{}{}, 30*time.Minute) //nolint:errcheck
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.Header().Set("Cache-Control", "no-store, max-age=0")
w.Header().Set("Content-Length", "0")
w.WriteHeader(http.StatusOK)
}
@@ -0,0 +1,108 @@
package cssload
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/store/memory"
"github.com/google/uuid"
"github.com/neilotoole/slogt/v2"
)
func TestCSSLoad(t *testing.T) {
st := memory.New(t.Context())
mux := http.NewServeMux()
i := &Impl{}
if err := i.Setup(mux, st); err != nil {
t.Fatalf("can't setup css-load extension: %v", err)
}
chID := uuid.Must(uuid.NewV7())
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
comp := i.Head(r, &challenge.Challenge{ID: chID.String()})
if err := comp.Render(t.Context(), io.Discard); err != nil {
t.Fatal(err)
}
lg := slogt.New(t)
t.Run("load-css", func(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, i.cssFolder()+"/"+chID.String(), nil)
rw := httptest.NewRecorder()
mux.ServeHTTP(rw, req)
resp := rw.Result()
if resp.StatusCode != http.StatusOK {
t.Errorf("wanted status code %d, got: %s", http.StatusOK, resp.Status)
}
})
t.Run("validate", func(t *testing.T) {
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
if err := i.Validate(r, lg, &challenge.ValidateInput{
Rule: nil,
Challenge: &challenge.Challenge{ID: chID.String()},
Store: st,
}); err != nil {
t.Fatal(err)
}
})
t.Run("validate-invalid", func(t *testing.T) {
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
if err := i.Validate(r, lg, &challenge.ValidateInput{
Rule: nil,
Challenge: &challenge.Challenge{ID: "hunter2"},
Store: st,
}); err == nil {
t.Fatal("validation passed when it should have failed")
}
})
}
func FuzzRenderCSS(f *testing.F) {
st := memory.New(f.Context())
mux := http.NewServeMux()
i := &Impl{}
if err := i.Setup(mux, st); err != nil {
f.Fatalf("can't setup css-load extension: %v", err)
}
f.Add(uuid.Must(uuid.NewV7()).String())
f.Fuzz(func(t *testing.T, a string) {
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, i.cssFolder()+"/"+a, nil)
if err != nil {
return
}
rw := httptest.NewRecorder()
mux.ServeHTTP(rw, req)
})
}
func TestHeadEscapesCSSURL(t *testing.T) {
previous := anubis.BasePrefix
t.Cleanup(func() { anubis.BasePrefix = previous })
anubis.BasePrefix = `/x");</style><script>bad</script>`
i := &Impl{st: memory.New(t.Context())}
r := httptest.NewRequest("GET", "http://example.com/", nil)
var out strings.Builder
if err := i.Head(r, &challenge.Challenge{ID: "test"}).Render(t.Context(), &out); err != nil {
t.Fatal(err)
}
if strings.Contains(out.String(), "<script>") || strings.Contains(out.String(), `/x");`) {
t.Fatalf("unsafe output: %s", out.String())
}
}
@@ -0,0 +1,24 @@
package cssload
import (
"context"
"errors"
"log/slog"
"net/http/httptest"
"testing"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/store"
)
type unavailableStore struct{ store.Interface }
func (unavailableStore) Get(context.Context, string) ([]byte, error) { return nil, store.ErrCantDecode }
func TestValidateRejectsUnavailableStore(t *testing.T) {
impl := &Impl{st: unavailableStore{}}
err := impl.Validate(httptest.NewRequest("GET", "/", nil), slog.Default(), &challenge.ValidateInput{Challenge: &challenge.Challenge{ID: "test"}})
if !errors.Is(err, store.ErrCantDecode) {
t.Fatalf("store failure accepted or hidden: %v", err)
}
}
@@ -0,0 +1,2 @@
go test fuzz v1
string(" ")
+65
View File
@@ -0,0 +1,65 @@
package extension
import (
"log/slog"
"net/http"
"sort"
"sync"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/store"
"github.com/a-h/templ"
)
var (
registry = map[string]Impl{}
regLock sync.RWMutex
)
// Register adds an extension to the global extension registry.
func Register(name string, impl Impl) {
regLock.Lock()
defer regLock.Unlock()
registry[name] = impl
}
// Get returns the extension by name. If no extension is found, ok is false.
func Get(name string) (impl Impl, ok bool) {
regLock.RLock()
defer regLock.RUnlock()
result, ok := registry[name]
return result, ok
}
// Names returns the names of all loaded challenge extensions.
func Names() []string {
regLock.RLock()
defer regLock.RUnlock()
result := make([]string, 0, len(registry))
for name := range registry {
result = append(result, name)
}
sort.Strings(result)
return result
}
// Impl is the implementation of a given challenge extension.
type Impl interface {
// Setup registers any relevant extension routes. Routes MUST include
// anubis.BasePrefix.
Setup(mux *http.ServeMux, st store.Interface) error
// Head returns additional data that is put into the HTML <head> block
// on the challenge page.
//
// Scripts rendered here run before challenge scripts (if any).
Head(r *http.Request, chall *challenge.Challenge) templ.Component
// Validate ensures that this challenge method's side effects have been
// fulfilled. Returning a non-nil error refuses to mint a JWT.
//
// If you return *challenge.Error via challenge.NewError, the client
// gets a more useful message.
Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error
}
+35 -1
View File
@@ -1,6 +1,7 @@
package challenge
import (
"fmt"
"log/slog"
"net/http"
"sort"
@@ -50,15 +51,48 @@ type IssueInput struct {
Store store.Interface
}
func (in *IssueInput) Valid() error {
if in == nil {
return fmt.Errorf("%w: IssueInput is nil", ErrInvalidInput)
}
if in.Rule == nil {
return fmt.Errorf("%w: Rule is nil", ErrInvalidInput)
}
if in.Rule.Challenge == nil {
return fmt.Errorf("%w: Rule.Challenge is nil", ErrInvalidInput)
}
if in.Challenge == nil {
return fmt.Errorf("%w: Challenge is nil", ErrInvalidInput)
}
return nil
}
type ValidateInput struct {
Rule *policy.Bot
Challenge *Challenge
Store store.Interface
}
func (in *ValidateInput) Valid() error {
if in == nil {
return fmt.Errorf("%w: ValidateInput is nil", ErrInvalidInput)
}
if in.Rule == nil {
return fmt.Errorf("%w: Rule is nil", ErrInvalidInput)
}
if in.Rule.Challenge == nil {
return fmt.Errorf("%w: Rule.Challenge is nil", ErrInvalidInput)
}
if in.Challenge == nil {
return fmt.Errorf("%w: Challenge is nil", ErrInvalidInput)
}
return nil
}
type Impl interface {
// Setup registers any additional routes with the Impl for assets or API routes.
Setup(mux *http.ServeMux)
// Any routes passed to this mux MUST include anubis.BasePrefix.
Setup(mux *http.ServeMux) error
// Issue a new challenge to the user, called by the Anubis.
Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)
+9 -1
View File
@@ -21,9 +21,13 @@ func init() {
type Impl struct{}
func (i *Impl) Setup(mux *http.ServeMux) {}
func (i *Impl) Setup(mux *http.ServeMux) error { return nil }
func (i *Impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {
if err := in.Valid(); err != nil {
return nil, err
}
u, err := r.URL.Parse(anubis.BasePrefix + "/.within.website/x/cmd/anubis/api/pass-challenge")
if err != nil {
return nil, fmt.Errorf("can't render page: %w", err)
@@ -49,6 +53,10 @@ func (i *Impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in
}
func (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {
if err := in.Valid(); err != nil {
return challenge.NewError("validate", "invalid input", err)
}
wantTime := in.Challenge.IssuedAt.Add(time.Duration(in.Rule.Challenge.Difficulty) * 800 * time.Millisecond)
if time.Now().Before(wantTime) {
+7 -7
View File
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.960
// templ: version: v0.3.1070
package metarefresh
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -41,11 +41,11 @@ func page(redir string, difficulty int, showMeta bool, loc *localization.SimpleL
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version)
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 12, Col: 165}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -54,11 +54,11 @@ func page(redir string, difficulty int, showMeta bool, loc *localization.SimpleL
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version)
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 13, Col: 174}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -98,11 +98,11 @@ func page(redir string, difficulty int, showMeta bool, loc *localization.SimpleL
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d; url=%s", difficulty+1, redir))
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d; url=%s", difficulty+1, redir))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 17, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+1 -1
View File
@@ -45,5 +45,5 @@ for file in js/*.tsx; do
output="${filename%.tsx}.js" # Changes "app.jsx" to "app.js"
echo $output
esbuild "${file}" --minify --bundle --outfile=static/"${output}" --banner:js="${LICENSE}"
esbuild "${file}" --minify --bundle --target=chrome66 --outfile=static/"${output}" --banner:js="${LICENSE}"
done
+18 -4
View File
@@ -24,9 +24,15 @@ import (
var appJS []byte
func renderAppJS(ctx context.Context, out io.Writer) error {
fmt.Fprint(out, `<script type="module">`)
out.Write(appJS)
fmt.Fprint(out, "</script>")
if _, err := fmt.Fprint(out, `<script type="module">`); err != nil {
return err
}
if _, err := out.Write(appJS); err != nil {
return err
}
if _, err := fmt.Fprint(out, "</script>"); err != nil {
return err
}
return nil
}
@@ -36,9 +42,13 @@ func init() {
type impl struct{}
func (i *impl) Setup(mux *http.ServeMux) {}
func (i *impl) Setup(mux *http.ServeMux) error { return nil }
func (i *impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {
if err := in.Valid(); err != nil {
return nil, err
}
u, err := r.URL.Parse(anubis.BasePrefix + "/.within.website/x/cmd/anubis/api/pass-challenge")
if err != nil {
return nil, fmt.Errorf("can't render page: %w", err)
@@ -57,6 +67,10 @@ func (i *impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in
}
func (i *impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {
if err := in.Valid(); err != nil {
return challenge.NewError("validate", "invalid input", err)
}
wantTime := in.Challenge.IssuedAt.Add(time.Duration(in.Rule.Challenge.Difficulty) * 80 * time.Millisecond)
if time.Now().Before(wantTime) {
+3 -3
View File
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.960
// templ: version: v0.3.1070
package preact
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -39,11 +39,11 @@ func page(redir, challenge string, difficulty int, loc *localization.SimpleLocal
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version)
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `preact.templ`, Line: 11, Col: 166}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+28
View File
@@ -0,0 +1,28 @@
package proofofwork
import (
"log/slog"
"strings"
"testing"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/policy"
)
func TestInvalidProofDoesNotRevealExpectedDigest(t *testing.T) {
for _, algorithm := range []string{"fast", "slow"} {
t.Run(algorithm, func(t *testing.T) {
data := "oracle-regression"
expected := internal.SHA256sum(data + "0")
err := (&Impl{Algorithm: algorithm}).Validate(mkRequest(t, map[string]string{"nonce": "0", "elapsedTime": "1", "response": strings.Repeat("f", 64)}), slog.Default(), &challenge.ValidateInput{Challenge: &challenge.Challenge{RandomData: data}, Rule: &policy.Bot{Challenge: &config.ChallengeRules{Difficulty: 1}}})
if err == nil {
t.Fatal("invalid proof accepted")
}
if strings.Contains(err.Error(), expected) {
t.Error("error reveals expected digest")
}
})
}
}
+22 -8
View File
@@ -1,14 +1,15 @@
package proofofwork
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
"github.com/TecharoHQ/anubis/internal"
chall "github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/localization"
"github.com/a-h/templ"
@@ -25,7 +26,7 @@ type Impl struct {
Algorithm string
}
func (i *Impl) Setup(mux *http.ServeMux) {}
func (i *Impl) Setup(mux *http.ServeMux) error { return nil }
func (i *Impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {
loc := localization.GetLocalizer(r)
@@ -33,6 +34,10 @@ func (i *Impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in
}
func (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInput) error {
if err := in.Valid(); err != nil {
return chall.NewError("validate", "invalid input", err)
}
rule := in.Rule
challenge := in.Challenge.RandomData
@@ -41,7 +46,7 @@ func (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInpu
return chall.NewError("validate", "invalid response", fmt.Errorf("%w nonce", chall.ErrMissingField))
}
nonce, err := strconv.Atoi(nonceStr)
_, err := strconv.Atoi(nonceStr)
if err != nil {
return chall.NewError("validate", "invalid response", fmt.Errorf("%w: nonce: %w", chall.ErrInvalidFormat, err))
@@ -62,11 +67,20 @@ func (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInpu
return chall.NewError("validate", "invalid response", fmt.Errorf("%w response", chall.ErrMissingField))
}
calcString := fmt.Sprintf("%s%d", challenge, nonce)
calculated := internal.SHA256sum(calcString)
// Stream the challenge and nonce into a single sha256 hasher to avoid
// the intermediate "challenge + nonceStr" concatenation. Hex-encode
// the digest into a stack buffer so the comparison runs without
// allocating a heap string.
h := sha256.New()
h.Write([]byte(challenge))
h.Write([]byte(nonceStr))
var sumBuf [sha256.Size]byte
sum := h.Sum(sumBuf[:0])
var hexBuf [sha256.Size * 2]byte
hex.Encode(hexBuf[:], sum)
if subtle.ConstantTimeCompare([]byte(response), []byte(calculated)) != 1 {
return chall.NewError("validate", "invalid response", fmt.Errorf("%w: wanted response %s but got %s", chall.ErrFailed, calculated, response))
if subtle.ConstantTimeCompare([]byte(response), hexBuf[:]) != 1 {
return chall.NewError("validate", "invalid response", chall.ErrFailed)
}
// compare the leading zeroes
@@ -74,7 +88,7 @@ func (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInpu
return chall.NewError("validate", "invalid response", fmt.Errorf("%w: wanted %d leading zeros but got %s", chall.ErrFailed, rule.Challenge.Difficulty, response))
}
lg.Debug("challenge took", "elapsedTime", elapsedTime)
lg.DebugContext(r.Context(), "challenge took", "elapsedTime", elapsedTime)
chall.TimeTaken.WithLabelValues(i.Algorithm).Observe(elapsedTime)
return nil
+5 -21
View File
@@ -2,6 +2,7 @@ package proofofwork
import (
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/challenge/challengepage"
"github.com/TecharoHQ/anubis/lib/localization"
)
@@ -10,30 +11,13 @@ templ page(localizer *localization.SimpleLocalizer) {
<img id="image" style="width:100%;max-width:256px;" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version }/>
<img style="display:none;" style="width:100%;max-width:256px;" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version }/>
<p id="status">{ localizer.T("loading") }</p>
<script async type="module" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/js/main.mjs?cacheBuster=" + anubis.Version }></script>
<p id="anubis-script-error" style="display:none;">{ localizer.T("script_load_error") }</p>
<script id="anubis-main" defer type="module" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/js/main.mjs?cacheBuster=" + anubis.Version }></script>
@challengepage.Bootstrap()
<div id="progress" role="progressbar" aria-labelledby="status">
<div class="bar-inner"></div>
</div>
<details>
if anubis.UseSimplifiedExplanation {
<p>
{ localizer.T("simplified_explanation") }
</p>
} else {
<p>
{ localizer.T("ai_companies_explanation") }
</p>
<p>
{ localizer.T("anubis_compromise") }
</p>
<p>
{ localizer.T("hack_purpose") }
</p>
<p>
{ localizer.T("jshelter_note") }
</p>
}
</details>
@challengepage.Explanation(localizer)
<noscript>
<p>
{ localizer.T("javascript_required") }
+45 -95
View File
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.960
// templ: version: v0.3.1070
package proofofwork
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -10,6 +10,7 @@ import templruntime "github.com/a-h/templ/runtime"
import (
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/challenge/challengepage"
"github.com/TecharoHQ/anubis/lib/localization"
)
@@ -39,11 +40,11 @@ func page(localizer *localization.SimpleLocalizer) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version)
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 10, Col: 165}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 11, Col: 165}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -52,11 +53,11 @@ func page(localizer *localization.SimpleLocalizer) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version)
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 11, Col: 174}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 12, Col: 174}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -67,119 +68,68 @@ func page(localizer *localization.SimpleLocalizer) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("loading"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 12, Col: 41}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 13, Col: 41}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</p><script async type=\"module\" src=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</p><p id=\"anubis-script-error\" style=\"display:none;\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/js/main.mjs?cacheBuster=" + anubis.Version)
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("script_load_error"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 13, Col: 136}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 14, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "\"></script><div id=\"progress\" role=\"progressbar\" aria-labelledby=\"status\"><div class=\"bar-inner\"></div></div><details>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</p><script id=\"anubis-main\" defer type=\"module\" src=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if anubis.UseSimplifiedExplanation {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("simplified_explanation"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 20, Col: 44}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("ai_companies_explanation"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 24, Col: 46}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</p><p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("anubis_compromise"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 27, Col: 39}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</p><p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("hack_purpose"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 30, Col: 34}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</p><p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("jshelter_note"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 33, Col: 35}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/js/main.mjs?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 15, Col: 153}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</details><noscript><p>")
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("javascript_required"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 39, Col: 40}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\"></script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</p></noscript><div id=\"testarea\"></div></div>")
templ_7745c5c3_Err = challengepage.Bootstrap().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div id=\"progress\" role=\"progressbar\" aria-labelledby=\"status\"><div class=\"bar-inner\"></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = challengepage.Explanation(localizer).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<noscript><p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("javascript_required"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 23, Col: 40}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</p></noscript><div id=\"testarea\"></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+59 -1
View File
@@ -30,6 +30,62 @@ func mkRequest(t *testing.T, values map[string]string) *http.Request {
return req
}
// TestValidateNilRuleChallenge reproduces the panic from
// https://github.com/TecharoHQ/anubis/issues/1463
//
// When a threshold rule matches during PassChallenge, check() can return
// a policy.Bot with Challenge == nil. After hydrateChallengeRule fails to
// run (or the error path hits before it), Validate dereferences
// rule.Challenge.Difficulty and panics.
func TestValidateNilRuleChallenge(t *testing.T) {
i := &Impl{Algorithm: "fast"}
lg := slog.With()
// This is the exact response for SHA256("hunter" + "0") with 0 leading zeros required.
const challengeStr = "hunter"
const response = "2652bdba8fb4d2ab39ef28d8534d7694c557a4ae146c1e9237bd8d950280500e"
req := mkRequest(t, map[string]string{
"nonce": "0",
"elapsedTime": "69",
"response": response,
})
for _, tc := range []struct {
name string
input *challenge.ValidateInput
}{
{
name: "nil-rule-challenge",
input: &challenge.ValidateInput{
Rule: &policy.Bot{},
Challenge: &challenge.Challenge{RandomData: challengeStr},
},
},
{
name: "nil-rule",
input: &challenge.ValidateInput{
Challenge: &challenge.Challenge{RandomData: challengeStr},
},
},
{
name: "nil-challenge",
input: &challenge.ValidateInput{Rule: &policy.Bot{Challenge: &config.ChallengeRules{Algorithm: "fast"}}},
},
{
name: "nil-input",
input: nil,
},
} {
t.Run(tc.name, func(t *testing.T) {
err := i.Validate(req, lg, tc.input)
if !errors.Is(err, challenge.ErrInvalidInput) {
t.Fatalf("expected ErrInvalidInput, got: %v", err)
}
})
}
}
func TestBasic(t *testing.T) {
i := &Impl{Algorithm: "fast"}
bot := &policy.Bot{
@@ -124,7 +180,9 @@ func TestBasic(t *testing.T) {
t.Run(cs.name, func(t *testing.T) {
lg := slog.With()
i.Setup(http.NewServeMux())
if err := i.Setup(http.NewServeMux()); err != nil {
t.Fatalf("can't set up server %v", err)
}
inp := &challenge.IssueInput{
Rule: bot,
@@ -0,0 +1,2 @@
*
!.gitignore
+107
View File
@@ -0,0 +1,107 @@
package wasm
import (
"context"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"strconv"
chall "github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/localization"
"github.com/TecharoHQ/anubis/wasm"
"github.com/TecharoHQ/anubis/web"
"github.com/a-h/templ"
)
//go:generate go tool github.com/a-h/templ/cmd/templ generate --log-level=error
func init() {
chall.Register("argon2id", &Impl{algorithm: "argon2id"})
chall.Register("hashx", &Impl{algorithm: "hashx"})
chall.Register("sha256", &Impl{algorithm: "sha256"})
}
type Impl struct {
algorithm string
runner *wasm.Runner
}
func (i *Impl) Setup(mux *http.ServeMux) error {
fname := fmt.Sprintf("static/wasm/simd128/%s.wasm", i.algorithm)
fin, err := web.Static.Open(fname)
if err != nil {
return err
}
defer fin.Close() //nolint:errcheck
i.runner, err = wasm.NewRunner(context.Background(), fname, fin)
if err != nil {
return err
}
return nil
}
func (i *Impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {
loc := localization.GetLocalizer(r)
return page(loc), nil
}
func (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInput) error {
if err := in.Valid(); err != nil {
return err
}
nonceStr := r.FormValue("nonce")
if nonceStr == "" {
return chall.NewError("validate", "invalid response", fmt.Errorf("%w nonce", chall.ErrMissingField))
}
nonce, err := strconv.Atoi(nonceStr)
if err != nil {
return chall.NewError("validate", "invalid response", fmt.Errorf("%w: nonce: %w", chall.ErrInvalidFormat, err))
}
elapsedTimeStr := r.FormValue("elapsedTime")
if elapsedTimeStr == "" {
return chall.NewError("validate", "invalid response", fmt.Errorf("%w elapsedTime", chall.ErrMissingField))
}
elapsedTime, err := strconv.ParseFloat(elapsedTimeStr, 64)
if err != nil {
return chall.NewError("validate", "invalid response", fmt.Errorf("%w: elapsedTime: %w", chall.ErrInvalidFormat, err))
}
response := r.FormValue("response")
if response == "" {
return chall.NewError("validate", "invalid response", fmt.Errorf("%w response", chall.ErrMissingField))
}
challengeBytes, err := hex.DecodeString(in.Challenge.RandomData)
if err != nil {
return chall.NewError("validate", "invalid random data", fmt.Errorf("can't decode random data: %w", err))
}
gotBytes, err := hex.DecodeString(response)
if err != nil {
return chall.NewError("validate", "invalid client data format", fmt.Errorf("%w response", chall.ErrInvalidFormat))
}
ok, err := i.runner.Verify(r.Context(), challengeBytes, gotBytes, uint32(nonce), uint32(in.Rule.Challenge.Difficulty))
if err != nil {
return chall.NewError("validate", "internal WASM error", fmt.Errorf("can't run wasm validation logic: %w", err))
}
if !ok {
return chall.NewError("verify", "client calculated wrong data", fmt.Errorf("%w: response invalid: %s", chall.ErrFailed, response))
}
lg.DebugContext(r.Context(), "challenge took", "elapsedTime", elapsedTime)
chall.TimeTaken.WithLabelValues(i.algorithm).Observe(elapsedTime)
return nil
}
+28
View File
@@ -0,0 +1,28 @@
package wasm
import (
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/challenge/challengepage"
"github.com/TecharoHQ/anubis/lib/localization"
)
templ page(localizer *localization.SimpleLocalizer) {
<div class="centered-div">
<img id="image" style="width:100%;max-width:256px;" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version }/>
<img style="display:none;" style="width:100%;max-width:256px;" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version }/>
<p id="status">{ localizer.T("loading") }</p>
<p id="anubis-script-error" style="display:none;">{ localizer.T("script_load_error") }</p>
<script id="anubis-main" defer type="module" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/js/main.mjs?cacheBuster=" + anubis.Version }></script>
@challengepage.Bootstrap()
<div id="progress" role="progressbar" aria-labelledby="status">
<div class="bar-inner"></div>
</div>
@challengepage.Explanation(localizer)
<noscript>
<p>
{ localizer.T("javascript_required") }
</p>
</noscript>
<div id="testarea"></div>
</div>
}
+140
View File
@@ -0,0 +1,140 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1070
package wasm
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import (
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/challenge/challengepage"
"github.com/TecharoHQ/anubis/lib/localization"
)
func page(localizer *localization.SimpleLocalizer) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"centered-div\"><img id=\"image\" style=\"width:100%;max-width:256px;\" src=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `wasm.templ`, Line: 11, Col: 165}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\"> <img style=\"display:none;\" style=\"width:100%;max-width:256px;\" src=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `wasm.templ`, Line: 12, Col: 174}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\"><p id=\"status\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("loading"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `wasm.templ`, Line: 13, Col: 41}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</p><p id=\"anubis-script-error\" style=\"display:none;\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("script_load_error"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `wasm.templ`, Line: 14, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</p><script id=\"anubis-main\" defer type=\"module\" src=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.ResolveAttributeValue(anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/js/main.mjs?cacheBuster=" + anubis.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `wasm.templ`, Line: 15, Col: 153}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\"></script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = challengepage.Bootstrap().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div id=\"progress\" role=\"progressbar\" aria-labelledby=\"status\"><div class=\"bar-inner\"></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = challengepage.Explanation(localizer).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<noscript><p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("javascript_required"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `wasm.templ`, Line: 23, Col: 40}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</p></noscript><div id=\"testarea\"></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
var _ = templruntime.GeneratedTemplate
+377
View File
@@ -0,0 +1,377 @@
package wasm
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"net/http"
"runtime"
"strconv"
"testing"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/policy"
"github.com/TecharoHQ/anubis/wasm"
"github.com/TecharoHQ/anubis/web"
)
// difficulty is intentionally tiny so that solving the proof of work in tests
// is effectively instant.
const difficulty = 4
// mkRequest builds a GET request whose query parameters become the form values
// read by Validate via r.FormValue.
func mkRequest(t *testing.T, values map[string]string) *http.Request {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
if err != nil {
t.Fatal(err)
}
q := req.URL.Query()
for k, v := range values {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
return req
}
// skipSlowArgon2id skips argon2id anywhere it is too slow to finish inside the
// go test timeout. wazero only ships a compiler for amd64 and arm64, every other
// architecture falls back to its interpreter. arm64 has been skipped since
// before that mattered and stays skipped.
func skipSlowArgon2id(t *testing.T, algorithm string) {
t.Helper()
if algorithm != "argon2id" {
return
}
if runtime.GOARCH != "amd64" {
t.Skipf("skipping argon2id on %s because validation is slow in the interpreter", runtime.GOARCH)
}
}
// solve runs the same WASM module the server uses to compute a genuinely valid
// (nonce, response) pair for the given challenge data, so the happy-path case
// exercises the full verification flow rather than a hand-rolled constant.
func solve(t *testing.T, algorithm string, data []byte) (nonce string, response string) {
t.Helper()
fname := fmt.Sprintf("static/wasm/baseline/%s.wasm", algorithm)
fin, err := web.Static.Open(fname)
if err != nil {
t.Fatalf("can't open %s: %v", fname, err)
}
defer fin.Close() //nolint:errcheck
runner, err := wasm.NewRunner(t.Context(), fname, fin)
if err != nil {
t.Fatalf("can't create runner for %s: %v", algorithm, err)
}
n, hash, err := runner.Run(t.Context(), data, difficulty, 0, 1)
if err != nil {
t.Fatalf("can't compute valid solution: %v", err)
}
return strconv.Itoa(int(n)), hex.EncodeToString(hash)
}
// TestValidateAdversarial feeds Validate a matrix of malformed and hostile
// inputs. Several of these cases are regression guards:
//
// - the "nil-*" cases reproduce the #1463-class nil-pointer panic that occurs
// when Validate dereferences in.Challenge / in.Rule.Challenge without first
// calling in.Valid().
// - "response-wrong-length" reproduces the nil api.Module panic in
// Runner.Verify when writeVerification rejects a correctly-encoded but
// wrong-sized response.
//
// None of these inputs may panic, and each must surface a clean error. The matrix is run
// against every WASM algorithm so an algorithm-specific validation path can't regress.
func TestValidateAdversarial(t *testing.T) {
for _, algorithm := range []string{"sha256", "hashx", "argon2id"} {
t.Run(algorithm, func(t *testing.T) {
skipSlowArgon2id(t, algorithm)
testValidateAdversarial(t, algorithm)
})
}
}
func testValidateAdversarial(t *testing.T, algorithm string) {
t.Helper()
i := &Impl{algorithm: algorithm}
if err := i.Setup(http.NewServeMux()); err != nil {
t.Fatalf("can't set up %s challenge: %v", algorithm, err)
}
lg := slog.New(slog.DiscardHandler)
// A challenge whose RandomData is valid hex-encoded bytes.
challengeBytes := sha256.Sum256([]byte(t.Name()))
randomData := hex.EncodeToString(challengeBytes[:])
validNonce, validResponse := solve(t, algorithm, challengeBytes[:])
bot := &policy.Bot{
Challenge: &config.ChallengeRules{
Algorithm: algorithm,
Difficulty: difficulty,
},
}
// goodInput returns a fresh, fully-populated ValidateInput so individual
// cases can override only what they want to break.
goodInput := func() *challenge.ValidateInput {
return &challenge.ValidateInput{
Rule: bot,
Challenge: &challenge.Challenge{RandomData: randomData},
}
}
// goodValues returns a fresh set of form values for a valid solution.
goodValues := func() map[string]string {
return map[string]string{
"nonce": validNonce,
"elapsedTime": "42",
"response": validResponse,
}
}
// errNotNil asserts only that an error was returned (used where the failure
// path does not wrap a package sentinel).
errNotNil := func(err error) bool { return err != nil }
tests := []struct {
name string
values map[string]string
input *challenge.ValidateInput
wantErr error // matched with errors.Is; nil means expect success
errCheck func(err error) bool // optional override; when set, wantErr is ignored
}{
{
name: "valid-solution-passes",
values: goodValues(),
input: goodInput(),
wantErr: nil,
},
{
name: "no-fields",
values: map[string]string{},
input: goodInput(),
wantErr: challenge.ErrMissingField,
},
{
name: "missing-nonce",
values: map[string]string{
"elapsedTime": "42",
"response": validResponse,
},
input: goodInput(),
wantErr: challenge.ErrMissingField,
},
{
name: "missing-elapsedTime",
values: map[string]string{
"nonce": validNonce,
"response": validResponse,
},
input: goodInput(),
wantErr: challenge.ErrMissingField,
},
{
name: "missing-response",
values: map[string]string{
"nonce": validNonce,
"elapsedTime": "42",
},
input: goodInput(),
wantErr: challenge.ErrMissingField,
},
{
name: "nonce-not-an-integer",
values: map[string]string{
"nonce": "taco",
"elapsedTime": "42",
"response": validResponse,
},
input: goodInput(),
wantErr: challenge.ErrInvalidFormat,
},
{
name: "nonce-overflows-int",
values: map[string]string{
"nonce": "999999999999999999999999999999",
"elapsedTime": "42",
"response": validResponse,
},
input: goodInput(),
wantErr: challenge.ErrInvalidFormat,
},
{
name: "elapsedTime-not-a-number",
values: map[string]string{
"nonce": validNonce,
"elapsedTime": "taco",
"response": validResponse,
},
input: goodInput(),
wantErr: challenge.ErrInvalidFormat,
},
{
name: "response-not-hex",
values: map[string]string{
"nonce": validNonce,
"elapsedTime": "42",
"response": "zz",
},
input: goodInput(),
wantErr: challenge.ErrInvalidFormat,
},
{
// Correctly hex-encoded but the wrong number of bytes. This drove a
// nil api.Module dereference panic in Runner.Verify.
name: "response-wrong-length",
values: map[string]string{
"nonce": validNonce,
"elapsedTime": "42",
"response": "abcd",
},
input: goodInput(),
errCheck: errNotNil,
},
{
// Correct length, valid hex, but not the hash we asked for.
name: "response-wrong-hash",
values: map[string]string{
"nonce": "0",
"elapsedTime": "42",
"response": hex.EncodeToString(make([]byte, sha256.Size)),
},
input: goodInput(),
wantErr: challenge.ErrFailed,
},
{
name: "nil-input",
values: goodValues(),
input: nil,
wantErr: challenge.ErrInvalidInput,
},
{
name: "nil-rule",
values: goodValues(),
input: &challenge.ValidateInput{Challenge: &challenge.Challenge{RandomData: randomData}},
wantErr: challenge.ErrInvalidInput,
},
{
name: "nil-rule-challenge",
values: goodValues(),
input: &challenge.ValidateInput{Rule: &policy.Bot{}, Challenge: &challenge.Challenge{RandomData: randomData}},
wantErr: challenge.ErrInvalidInput,
},
{
name: "nil-challenge",
values: goodValues(),
input: &challenge.ValidateInput{Rule: bot},
wantErr: challenge.ErrInvalidInput,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := mkRequest(t, tt.values)
err := i.Validate(req, lg, tt.input)
if tt.errCheck != nil {
if !tt.errCheck(err) {
t.Fatalf("error check failed, got: %v", err)
}
return
}
if !errors.Is(err, tt.wantErr) {
t.Fatalf("got error %v, want %v", err, tt.wantErr)
}
})
}
}
// TestSolveVerifyManyChallenges runs many independent random challenges through the full
// solve + Validate path for every algorithm. It guards against rare, seed-dependent
// failures: most importantly the HashX ProgramConstraints seed rejection, which must be
// handled deterministically (see make_hashx in wasm/pow/hashx) rather than trapping.
func TestSolveVerifyManyChallenges(t *testing.T) {
counts := map[string]int{
"sha256": 200,
"hashx": 200,
"argon2id": 20, // argon2id is deliberately slow; keep the loop short
}
for _, algorithm := range []string{"sha256", "hashx", "argon2id"} {
t.Run(algorithm, func(t *testing.T) {
skipSlowArgon2id(t, algorithm)
n := counts[algorithm]
if testing.Short() {
n = 5
}
i := &Impl{algorithm: algorithm}
if err := i.Setup(http.NewServeMux()); err != nil {
t.Fatalf("can't set up %s challenge: %v", algorithm, err)
}
// One runner shared across iterations to avoid recompiling per solve.
fname := fmt.Sprintf("static/wasm/simd128/%s.wasm", algorithm)
fin, err := web.Static.Open(fname)
if err != nil {
t.Fatalf("can't open %s: %v", fname, err)
}
defer fin.Close() //nolint:errcheck
runner, err := wasm.NewRunner(t.Context(), fname, fin)
if err != nil {
t.Fatalf("can't create runner for %s: %v", algorithm, err)
}
lg := slog.New(slog.DiscardHandler)
bot := &policy.Bot{
Challenge: &config.ChallengeRules{
Algorithm: algorithm,
Difficulty: difficulty,
},
}
for j := range n {
challengeBytes := sha256.Sum256(fmt.Appendf(nil, "%s-%d", t.Name(), j))
nonce, hash, err := runner.Run(t.Context(), challengeBytes[:], difficulty, 0, 1)
if err != nil {
t.Fatalf("challenge %d: can't compute solution: %v", j, err)
}
req := mkRequest(t, map[string]string{
"nonce": strconv.Itoa(int(nonce)),
"elapsedTime": "42",
"response": hex.EncodeToString(hash),
})
in := &challenge.ValidateInput{
Rule: bot,
Challenge: &challenge.Challenge{RandomData: hex.EncodeToString(challengeBytes[:])},
}
if err := i.Validate(req, lg, in); err != nil {
t.Fatalf("challenge %d failed to validate: %v", j, err)
}
}
})
}
}
+89
View File
@@ -0,0 +1,89 @@
package lib
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/store"
)
func TestPassChallengeRequiresIssuedPolicy(t *testing.T) {
for _, change := range []string{"hash", "difficulty", "algorithm", "extensions", "action"} {
t.Run(change, func(t *testing.T) {
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: loadPolicies(t, "./testdata/zero_difficulty.yaml", 0)})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
t.Cleanup(ts.Close)
cli := httpClient(t)
issued := makeChallenge(t, ts, cli)
j := store.JSON[challenge.Challenge]{Underlying: srv.store}
c, err := j.Get(context.Background(), "challenge:"+issued.ID)
if err != nil {
t.Fatal(err)
}
switch change {
case "hash":
c.PolicyRuleHash = "other-rule"
case "difficulty":
c.Difficulty = 1
case "algorithm":
c.Method = "slow"
case "extensions":
c.Extensions = []string{"css-load"}
case "action":
for _, threshold := range srv.policy.Thresholds {
threshold.Action = "DENY"
}
}
if err := j.Set(context.Background(), "challenge:"+c.ID, c, 30*time.Minute); err != nil {
t.Fatal(err)
}
resp := handleChallengeZeroDifficulty(t, ts, cli, issued)
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 400 || authCookie(srv, resp) != nil {
t.Errorf("changed %s accepted: status %d", change, resp.StatusCode)
}
})
}
}
func TestChallengeCannotTransferToAnotherRule(t *testing.T) {
pol := loadPolicies(t, "testdata/rule_change.yaml", 0)
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: pol})
req := httptest.NewRequest("GET", "/old", nil)
req.Header.Set("X-Real-IP", "192.0.2.1")
lg, req := srv.getRequestLogger(req)
cr, rule, err := srv.check(req, lg)
if err != nil {
t.Fatal(err)
}
issued, err := srv.issueChallenge(req.Context(), req, lg, cr, rule)
if err != nil {
t.Fatal(err)
}
for _, path := range []string{"/old", "/new"} {
pass := httptest.NewRequest("GET", "/?redir="+path+"&id="+issued.ID+"&nonce=0&elapsedTime=1&response="+internal.SHA256sum(issued.RandomData+"0"), nil)
pass.Header.Set("X-Real-IP", "192.0.2.1")
pass.AddCookie(&http.Cookie{Name: srv.cookieName(anubis.TestCookieName), Value: issued.ID})
rec := httptest.NewRecorder()
srv.PassChallenge(rec, pass)
if path == "/old" {
if rec.Code != http.StatusFound {
t.Fatalf("same rule with omitted challenge config rejected: %d", rec.Code)
}
issued.Spent = false
j := store.JSON[challenge.Challenge]{Underlying: srv.store}
if err := j.Set(req.Context(), "challenge:"+issued.ID, *issued, time.Minute); err != nil {
t.Fatal(err)
}
} else if rec.Code != http.StatusForbidden || authCookie(srv, rec.Result()) != nil {
t.Fatalf("rule transfer accepted: %d", rec.Code)
}
}
}
+177
View File
@@ -0,0 +1,177 @@
package lib
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/internal"
)
// passChallengeCookie submits a solved zero difficulty challenge, optionally
// without the verification cookie as if the browser had dropped it.
func passChallengeCookie(t *testing.T, srv *Server, ts *httptest.Server, c challengeResp, userAgent string, withCookie bool) *http.Response {
t.Helper()
q := url.Values{}
q.Set("id", c.ID)
q.Set("response", internal.SHA256sum(c.Challenge+"0"))
q.Set("nonce", "0")
q.Set("redir", "/")
q.Set("elapsedTime", "420")
req, err := http.NewRequest(http.MethodGet, ts.URL+"/.within.website/x/cmd/anubis/api/pass-challenge?"+q.Encode(), nil)
if err != nil {
t.Fatalf("can't make request: %v", err)
}
req.Header.Set("User-Agent", userAgent)
if withCookie {
req.AddCookie(&http.Cookie{Name: srv.cookieName(anubis.TestCookieName), Value: c.ID})
}
cli := &http.Client{
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
resp, err := cli.Do(req)
if err != nil {
t.Fatalf("can't do request: %v", err)
}
t.Cleanup(func() { _ = resp.Body.Close() })
return resp
}
func TestPassChallengeMissingVerificationCookie(t *testing.T) {
type step struct {
reuse bool // reuse the previous step's challenge instead of issuing a new one
id string // override the challenge ID
userAgent string // defaults to Mozilla/5.0
withCookie bool
wantStatus int
wantAuth bool
}
for _, tt := range []struct {
name string
steps []step
}{
{
name: "cookie present passes",
steps: []step{
{withCookie: true, wantStatus: http.StatusFound, wantAuth: true},
},
},
{
name: "first miss retries then passes",
steps: []step{
{wantStatus: http.StatusFound},
{withCookie: true, wantStatus: http.StatusFound, wantAuth: true},
},
},
{
name: "repeated misses end in an error",
steps: []step{
{wantStatus: http.StatusFound},
{wantStatus: http.StatusInternalServerError},
{wantStatus: http.StatusInternalServerError},
},
},
{
name: "retry is per client",
steps: []step{
{wantStatus: http.StatusFound},
{userAgent: "Mozilla/5.0 other", wantStatus: http.StatusFound},
{wantStatus: http.StatusInternalServerError},
},
},
{
name: "unknown challenge is not retried",
steps: []step{
{id: "not-a-challenge", wantStatus: http.StatusInternalServerError},
},
},
{
name: "spent challenge is not retried",
steps: []step{
{withCookie: true, wantStatus: http.StatusFound, wantAuth: true},
{reuse: true, wantStatus: http.StatusInternalServerError},
},
},
} {
t.Run(tt.name, func(t *testing.T) {
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0)})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
t.Cleanup(ts.Close)
var c challengeResp
for i, st := range tt.steps {
if !st.reuse {
c = makeChallenge(t, ts, httpClient(t))
}
if st.id != "" {
c.ID = st.id
}
if st.userAgent == "" {
st.userAgent = "Mozilla/5.0"
}
resp := passChallengeCookie(t, srv, ts, c, st.userAgent, st.withCookie)
if resp.StatusCode != st.wantStatus {
t.Fatalf("step %d: wanted status %d, got %d", i, st.wantStatus, resp.StatusCode)
}
if got := authCookie(srv, resp) != nil; got != st.wantAuth {
t.Fatalf("step %d: wanted auth cookie %v, got %v", i, st.wantAuth, got)
}
if st.wantStatus == http.StatusFound && !st.wantAuth {
if loc := resp.Header.Get("Location"); loc != "/" {
t.Fatalf("step %d: retry should redirect to the original destination, got %q", i, loc)
}
}
}
})
}
}
// TestMissingVerificationCookieRetryIssuesFreshChallenge follows the retry
// redirect and makes sure the client gets a new challenge and verification
// cookie rather than an error page.
func TestMissingVerificationCookieRetryIssuesFreshChallenge(t *testing.T) {
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0)})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
t.Cleanup(ts.Close)
cli := httpClient(t)
c := makeChallenge(t, ts, cli)
resp := passChallengeCookie(t, srv, ts, c, "Mozilla/5.0", false)
if resp.StatusCode != http.StatusFound {
t.Fatalf("wanted retry redirect, got status %d", resp.StatusCode)
}
loc, err := resp.Location()
if err != nil {
t.Fatalf("retry redirect has no location: %v", err)
}
next, err := cli.Get(loc.String())
if err != nil {
t.Fatalf("can't follow retry redirect: %v", err)
}
t.Cleanup(func() { _ = next.Body.Close() })
var fresh *http.Cookie
for _, ckie := range next.Cookies() {
if ckie.Name == srv.cookieName(anubis.TestCookieName) && ckie.Value != "" {
fresh = ckie
}
}
if fresh == nil {
t.Fatal("retry did not issue a new verification cookie")
}
if fresh.Value == c.ID {
t.Error("retry reused the old challenge")
}
}
+41
View File
@@ -0,0 +1,41 @@
package lib
import (
"errors"
"io"
"log/slog"
"net/http"
)
func prepareChallengeForm(w http.ResponseWriter, r *http.Request) bool {
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
err := r.ParseForm()
if err == nil {
err = r.ParseMultipartForm(64 << 10)
}
// An empty body is not malformed. Some reverse proxies strip the body of
// auth subrequests (for example nginx' auth_request) while keeping the
// original Content-Type, and a chunked request whose body has not been
// buffered yet is indistinguishable from an empty one. Parsing an empty
// multipart body fails with an io.EOF-wrapped error instead of
// http.ErrNotMultipart, so tolerate it as well. Bodies that are actually
// malformed fail with a different error and are still rejected.
if err == nil || errors.Is(err, http.ErrNotMultipart) || errors.Is(err, io.EOF) {
return true
}
var limit *http.MaxBytesError
status := http.StatusBadRequest
if errors.As(err, &limit) {
status = http.StatusRequestEntityTooLarge
}
http.Error(w, http.StatusText(status), status)
return false
}
func cleanupChallengeForm(r *http.Request) {
if r.MultipartForm != nil {
if err := r.MultipartForm.RemoveAll(); err != nil {
slog.DebugContext(r.Context(), "can't remove multipart form files", "err", err)
}
}
}
+138
View File
@@ -0,0 +1,138 @@
package lib
import (
"bytes"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/TecharoHQ/anubis"
)
func TestChallengeEndpointsLimitMultipartBodies(t *testing.T) {
var body bytes.Buffer
form := multipart.NewWriter(&body)
part, err := form.CreateFormFile("upload", "file")
if err != nil {
t.Fatal(err)
}
if _, err := part.Write(bytes.Repeat([]byte("x"), 128<<10)); err != nil {
t.Fatal(err)
}
if err := form.Close(); err != nil {
t.Fatal(err)
}
for _, endpoint := range []string{"make", "pass", "forward"} {
t.Run(endpoint, func(t *testing.T) {
srv := spawnAnubis(t, Options{Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0)})
req := httptest.NewRequest("GET", "/?redir=/", bytes.NewReader(body.Bytes()))
req.Header.Set("Content-Type", form.FormDataContentType())
req.Header.Set("X-Real-IP", "192.0.2.1")
req.AddCookie(&http.Cookie{Name: srv.cookieName(anubis.TestCookieName), Value: "test"})
rec := httptest.NewRecorder()
switch endpoint {
case "make":
srv.MakeChallenge(rec, req)
case "pass":
srv.PassChallenge(rec, req)
case "forward":
srv.ServeHTTPNext(rec, req)
}
if rec.Code != http.StatusRequestEntityTooLarge {
t.Errorf("oversized multipart status %d", rec.Code)
}
})
}
}
func TestChallengeFormControls(t *testing.T) {
for _, tt := range []struct {
name, contentType, body string
want int
}{
{"query", "", "", http.StatusOK},
{"urlencoded", "application/x-www-form-urlencoded", "redir=%2F", http.StatusOK},
{"oversized urlencoded", "application/x-www-form-urlencoded", "redir=" + strings.Repeat("x", 128<<10), http.StatusRequestEntityTooLarge},
} {
t.Run(tt.name, func(t *testing.T) {
srv := spawnAnubis(t, Options{Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0)})
req := httptest.NewRequest("POST", "/?redir=/", strings.NewReader(tt.body))
req.Header.Set("Content-Type", tt.contentType)
req.Header.Set("X-Real-IP", "192.0.2.1")
rec := httptest.NewRecorder()
srv.MakeChallenge(rec, req)
if rec.Code != tt.want {
t.Errorf("status %d, want %d", rec.Code, tt.want)
}
})
}
}
func TestOriginUploadIsUnmodified(t *testing.T) {
body := strings.Repeat("x", 128<<10)
srv := spawnAnubis(t, Options{Next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, err := io.ReadAll(r.Body)
if err != nil || string(got) != body {
t.Errorf("upload changed: bytes %d, err %v", len(got), err)
}
})})
req := httptest.NewRequest("POST", "/upload", strings.NewReader(body))
srv.ServeHTTPNext(httptest.NewRecorder(), req)
}
// A reverse proxy that strips the request body for auth subrequests (for
// example nginx' auth_request) still forwards the original Content-Type. When
// that Content-Type is multipart/form-data and the body is empty,
// prepareChallengeForm must not treat the request as malformed.
func TestPrepareChallengeFormEmptyMultipartBody(t *testing.T) {
for _, tc := range []struct {
name string
mutate func(*http.Request)
}{
{"empty body", func(*http.Request) {}},
// A chunked request (unknown length) whose body is empty must be
// tolerated just like one that advertises a length of zero.
{"empty body with unknown length", func(r *http.Request) { r.ContentLength = -1 }},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/", nil)
req.Header.Set("Content-Type", "multipart/form-data; boundary=X")
req.Header.Set("X-Real-IP", "192.0.2.1")
tc.mutate(req)
rec := httptest.NewRecorder()
if !prepareChallengeForm(rec, req) {
t.Fatalf("prepareChallengeForm rejected an empty multipart body: status %d", rec.Code)
}
})
}
}
// The tolerance for empty bodies must not disable multipart parsing for
// requests that carry an unknown length (chunked) but do have a body.
func TestPrepareChallengeFormNonEmptyMultipartBodyUnknownLength(t *testing.T) {
var body bytes.Buffer
form := multipart.NewWriter(&body)
if err := form.WriteField("redir", "/somewhere"); err != nil {
t.Fatal(err)
}
if err := form.Close(); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body.Bytes()))
req.Header.Set("Content-Type", form.FormDataContentType())
req.Header.Set("X-Real-IP", "192.0.2.1")
req.ContentLength = -1 // simulate a chunked request
rec := httptest.NewRecorder()
if !prepareChallengeForm(rec, req) {
t.Fatalf("prepareChallengeForm rejected a non-empty multipart body: status %d", rec.Code)
}
if got := req.FormValue("redir"); got != "/somewhere" {
t.Fatalf("multipart body was not parsed: redir = %q", got)
}
}
+34
View File
@@ -0,0 +1,34 @@
package lib
import (
"log/slog"
"testing"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/policy"
)
func TestHydrateChallengeRulePreservesPolicy(t *testing.T) {
for _, configured := range []bool{false, true} {
t.Run(map[bool]string{false: "missing", true: "defaults"}[configured], func(t *testing.T) {
srv := &Server{policy: &policy.ParsedConfig{DefaultDifficulty: 4}, logger: slog.Default()}
rule := &policy.Bot{}
if configured {
rule.Challenge = &config.ChallengeRules{}
}
issued := &challenge.Challenge{Method: "fast", Difficulty: 3}
hydrated := srv.hydrateChallengeRule(rule, issued, slog.Default())
if hydrated.Challenge.Difficulty != 3 || hydrated.Challenge.Algorithm != "fast" {
t.Fatal("stored challenge settings were not hydrated")
}
if configured {
if rule.Challenge.Difficulty != 0 || rule.Challenge.Algorithm != "" {
t.Fatal("hydration modified shared policy settings")
}
} else if rule.Challenge != nil {
t.Fatal("hydration modified shared policy rule")
}
})
}
}
+75
View File
@@ -0,0 +1,75 @@
package lib
import (
"log/slog"
"net/http/httptest"
"strings"
"testing"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/challenge/challengetest"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/policy"
)
// TestChallengePagesHaveScriptWatchdog makes sure every challenge that hands
// its work to main.mjs also ships the bootstrap watchdog that re-injects
// main.mjs when it fails to load.
func TestChallengePagesHaveScriptWatchdog(t *testing.T) {
needsWatchdog := map[string]bool{
"argon2id": true,
"fast": true,
"hashx": true,
"metarefresh": false,
"preact": false,
"sha256": true,
"slow": true,
}
methods := challenge.Methods()
for _, method := range methods {
if _, ok := needsWatchdog[method]; !ok {
t.Errorf("challenge method %s is not listed in this test: does its page need the bootstrap watchdog?", method)
}
}
for _, method := range methods {
t.Run(method, func(t *testing.T) {
impl, ok := challenge.Get(method)
if !ok {
t.Fatalf("challenge method %s is registered but can't be fetched", method)
}
in := &challenge.IssueInput{
Rule: &policy.Bot{
Challenge: &config.ChallengeRules{
Algorithm: method,
Difficulty: 4,
},
},
Challenge: challengetest.New(t),
}
cmp, err := impl.Issue(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil), slog.With(), in)
if err != nil {
t.Fatalf("can't issue challenge: %v", err)
}
var sb strings.Builder
if err := cmp.Render(t.Context(), &sb); err != nil {
t.Fatalf("can't render challenge page: %v", err)
}
out := sb.String()
markers := []string{`id="anubis-main"`, `id="anubis-script-error"`, `id="progress"`}
for _, marker := range markers {
got := strings.Contains(out, marker)
if want := needsWatchdog[method]; got != want {
t.Errorf("page contains %s: got %v, wanted %v", marker, got, want)
}
}
})
}
}
+26
View File
@@ -0,0 +1,26 @@
package lib
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/TecharoHQ/anubis/internal"
)
func TestPassChallengeRedirectIsUncacheable(t *testing.T) {
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0)})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
t.Cleanup(ts.Close)
cli := httpClient(t)
c := makeChallenge(t, ts, cli)
resp := handleChallengeZeroDifficulty(t, ts, cli, c)
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusFound || authCookie(srv, resp) == nil {
t.Fatalf("challenge unsuccessful: %d", resp.StatusCode)
}
if !strings.Contains(resp.Header.Get("Cache-Control"), "no-store") {
t.Error("cookie redirect permits storage")
}
}
+75
View File
@@ -0,0 +1,75 @@
package lib
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/store"
)
type spendFailureStore struct{ store.Interface }
func (s spendFailureStore) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {
var c challenge.Challenge
if json.Unmarshal(value, &c) == nil && c.Spent {
return store.ErrCantEncode
}
return s.Interface.Set(ctx, key, value, expiry)
}
func TestChallengeSpendIsExclusive(t *testing.T) {
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0)})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
t.Cleanup(ts.Close)
c := makeChallenge(t, ts, httpClient(t))
j := store.JSON[challenge.Challenge]{Underlying: srv.store}
stored, err := j.Get(t.Context(), "challenge:"+c.ID)
if err != nil {
t.Fatal(err)
}
var accepted atomic.Int32
var wg sync.WaitGroup
gate := make(chan struct{})
for range 32 {
wg.Go(func() {
<-gate
req := httptest.NewRequest("GET", "/?redir=/&id="+c.ID+"&nonce=0&elapsedTime=1&response="+internal.SHA256sum(stored.RandomData+"0"), nil)
req.Header.Set("X-Real-IP", "192.0.2.1")
req.Header.Set("User-Agent", "Mozilla/5.0")
req.AddCookie(&http.Cookie{Name: srv.cookieName(anubis.TestCookieName), Value: c.ID})
rec := httptest.NewRecorder()
srv.PassChallenge(rec, req)
if authCookie(srv, rec.Result()) != nil {
accepted.Add(1)
}
})
}
close(gate)
wg.Wait()
if got := accepted.Load(); got != 1 {
t.Fatalf("challenge minted %d cookies", got)
}
}
func TestChallengeSpendWriteFailureRejectsClearance(t *testing.T) {
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0)})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
t.Cleanup(ts.Close)
cli := httpClient(t)
c := makeChallenge(t, ts, cli)
srv.store = spendFailureStore{srv.store}
resp := handleChallengeZeroDifficulty(t, ts, cli, c)
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 400 || authCookie(srv, resp) != nil {
t.Fatalf("failed spend accepted: %d", resp.StatusCode)
}
}
+51
View File
@@ -0,0 +1,51 @@
package lib
import (
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
)
type failingChallenge struct {
challenge.Impl
err error
}
func (f failingChallenge) Validate(*http.Request, *slog.Logger, *challenge.ValidateInput) error {
return f.err
}
func TestPassChallengeRejectsEveryValidationError(t *testing.T) {
original, _ := challenge.Get("fast")
t.Cleanup(func() { challenge.Register("fast", original) })
for _, tt := range []struct {
name string
err error
}{
{"plain", errors.New("validation unavailable")},
{"wrapped without sentinel", challenge.NewError("validate", "internal WASM error", errors.New("validation unavailable"))},
{"failed sentinel", challenge.NewError("validate", "invalid response", challenge.ErrFailed)},
} {
t.Run(tt.name, func(t *testing.T) {
challenge.Register("fast", failingChallenge{Impl: original, err: tt.err})
srv := spawnAnubis(t, Options{Next: http.NewServeMux(), Policy: loadPolicies(t, "./testdata/zero_difficulty.yaml", 0)})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
t.Cleanup(ts.Close)
cli := httpClient(t)
chall := makeChallenge(t, ts, cli)
resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 400 {
t.Errorf("validation error accepted: status %d", resp.StatusCode)
}
if authCookie(srv, resp) != nil {
t.Error("validation error minted clearance cookie")
}
})
}
}
+35
View File
@@ -0,0 +1,35 @@
package lib
import (
"net/http/httptest"
"testing"
"github.com/TecharoHQ/anubis"
)
func TestCheckResponsesNoStore(t *testing.T) {
for _, public := range []string{"", "https://anubis.example.com"} {
t.Run(public, func(t *testing.T) {
s := spawnAnubis(t, Options{PublicUrl: public})
r := httptest.NewRequest("GET", anubis.APIPrefix+"check", nil)
r.Header.Set("Accept-Encoding", "gzip")
r.Header.Set("User-Agent", "Mozilla/5.0")
r.Header.Set("X-Real-IP", "192.0.2.1")
r.Header.Set("X-Forwarded-Host", "example.com")
r.Header.Set("X-Forwarded-Proto", "https")
r.Header.Set("X-Forwarded-Uri", "/test")
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
want := 401
if public != "" {
want = 307
}
if w.Code != want {
t.Fatalf("status=%d want %d", w.Code, want)
}
if got := w.Header().Get("Cache-Control"); got != "no-store" {
t.Fatalf("status=%d cache=%q", w.Code, got)
}
})
}
}
+104 -57
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/sha512"
"errors"
"fmt"
"io"
@@ -19,43 +20,48 @@ import (
"github.com/TecharoHQ/anubis/internal/honeypot/naive"
"github.com/TecharoHQ/anubis/internal/ogtags"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/challenge/extension"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/localization"
"github.com/TecharoHQ/anubis/lib/policy"
"github.com/TecharoHQ/anubis/web"
"github.com/TecharoHQ/anubis/xess"
"github.com/a-h/templ"
"github.com/golang-jwt/jwt/v5"
)
type Options struct {
Next http.Handler
Policy *policy.ParsedConfig
Target string
TargetHost string
TargetSNI string
TargetInsecureSkipVerify bool
CookieDynamicDomain bool
CookieDomain string
CookieExpiration time.Duration
CookiePartitioned bool
BasePrefix string
WebmasterEmail string
RedirectDomains []string
ED25519PrivateKey ed25519.PrivateKey
HS512Secret []byte
StripBasePrefix bool
OpenGraph config.OpenGraph
ServeRobotsTXT bool
CookieSecure bool
CookieSameSite http.SameSite
Logger *slog.Logger
LogLevel string
PublicUrl string
JWTRestrictionHeader string
DifficultyInJWT bool
Next http.Handler
Policy *policy.ParsedConfig
Target string
TargetHost string
TargetSNI string
TargetInsecureSkipVerify bool
CookieDynamicDomain bool
CookieDomain string
CookieExpiration time.Duration
CookiePartitioned bool
DynamicCookieSuffix bool
BasePrefix string
WebmasterEmail string
RedirectDomains []string
ED25519PrivateKey ed25519.PrivateKey
HS512Secret []byte
StripBasePrefix bool
OpenGraph config.OpenGraph
ServeRobotsTXT bool
CookieSecure bool
CookieHttpOnly bool
CookieSameSite http.SameSite
Logger *slog.Logger
LogLevel string
PublicUrl string
JWTRestrictionHeader string
DifficultyInJWT bool
PreserveRefererQueryParam bool
}
func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int, logLevel string) (*policy.ParsedConfig, error) {
func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int, logLevel string, subrequestMode bool) (*policy.ParsedConfig, error) {
var fin io.ReadCloser
var err error
@@ -75,11 +81,11 @@ func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty
defer func(fin io.ReadCloser) {
err := fin.Close()
if err != nil {
slog.Error("failed to close policy file", "file", fname, "err", err)
slog.ErrorContext(ctx, "failed to close policy file", "file", fname, "err", err)
}
}(fin)
anubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty, logLevel)
anubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty, logLevel, subrequestMode)
if err != nil {
return nil, fmt.Errorf("can't parse policy file %s: %w", fname, err)
}
@@ -89,6 +95,15 @@ func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty
if _, ok := challenge.Get(b.Challenge.Algorithm); !ok {
validationErrs = append(validationErrs, fmt.Errorf("%w %s", policy.ErrChallengeRuleHasWrongAlgorithm, b.Challenge.Algorithm))
}
if err := checkExtensions(b.Name, b.Challenge); err != nil {
validationErrs = append(validationErrs, err)
}
}
for _, t := range anubisPolicy.Thresholds {
if err := checkExtensions(t.Name, t.Challenge); err != nil {
validationErrs = append(validationErrs, err)
}
}
if len(validationErrs) != 0 {
@@ -98,7 +113,30 @@ func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty
return anubisPolicy, err
}
func checkExtensions(ruleName string, cr *config.ChallengeRules) error {
if cr == nil {
return nil
}
var errs []error
for _, name := range cr.Extensions {
if _, ok := extension.Get(name); !ok {
errs = append(errs, fmt.Errorf("%w %q in rule %q, known extensions: %v", ErrUnknownChallengeExtension, name, ruleName, extension.Names()))
}
}
if len(errs) != 0 {
return errors.Join(errs...)
}
return nil
}
func New(opts Options) (*Server, error) {
if len(opts.HS512Secret) > 0 && len(opts.HS512Secret) < sha512.Size {
return nil, jwt.ErrInvalidKey
}
if opts.Logger == nil {
opts.Logger = slog.With("subsystem", "anubis")
}
@@ -165,42 +203,36 @@ func New(opts Options) (*Server, error) {
}
if opts.Policy.Impressum != nil {
registerWithPrefix(anubis.APIPrefix+"imprint", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
registerWithPrefix(anubis.APIPrefix+"imprint", internal.NoStoreCache(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
templ.Handler(
web.Base(opts.Policy.Impressum.Page.Title, opts.Policy.Impressum.Page, opts.Policy.Impressum, localization.GetLocalizer(r)),
web.Base(opts.Policy.Impressum.Page.Title, opts.Policy.Impressum.Page, opts.Policy.Impressum, opts.Policy.Honeypot, localization.GetLocalizer(r)),
).ServeHTTP(w, r)
}), "GET")
})), "GET")
}
registerWithPrefix(anubis.APIPrefix+"pass-challenge", http.HandlerFunc(result.PassChallenge), "GET")
registerWithPrefix(anubis.APIPrefix+"check", http.HandlerFunc(result.maybeReverseProxyHttpStatusOnly), "")
registerWithPrefix(anubis.APIPrefix+"pass-challenge", internal.NoStoreCache(http.HandlerFunc(result.PassChallenge)), "GET")
registerWithPrefix(anubis.APIPrefix+"check", internal.NoStoreCache(http.HandlerFunc(result.maybeReverseProxyHttpStatusOnly)), "")
registerWithPrefix("/", http.HandlerFunc(result.maybeReverseProxyOrPage), "")
mazeGen, err := naive.New(result.store, result.logger)
if err == nil {
registerWithPrefix(anubis.APIPrefix+"honeypot/{id}/{stage}", mazeGen, http.MethodGet)
if opts.Policy.Honeypot != nil && opts.Policy.Honeypot.Enabled {
mazeGen, err := naive.New(opts.Policy.Honeypot, result.store, result.logger)
if err == nil {
registerWithPrefix(anubis.APIPrefix+"honeypot/{id}/{stage}", internal.NoStoreCache(mazeGen), http.MethodGet)
opts.Policy.Bots = append(
opts.Policy.Bots,
policy.Bot{
Rules: mazeGen.CheckNetwork(),
Action: config.RuleWeigh,
Weight: &config.Weight{
Adjust: 30,
opts.Policy.Bots = append(
opts.Policy.Bots,
policy.Bot{
Rules: mazeGen.CheckNetwork(),
Action: config.RuleWeigh,
Weight: &config.Weight{
Adjust: 30,
},
Name: "honeypot/network",
},
Name: "honeypot/network",
},
policy.Bot{
Rules: mazeGen.CheckUA(),
Action: config.RuleWeigh,
Weight: &config.Weight{
Adjust: 30,
},
Name: "honeypot/user-agent",
},
)
} else {
result.logger.Error("can't init honeypot subsystem", "err", err)
)
} else {
result.logger.Error("can't init honeypot subsystem", "err", err)
}
}
//goland:noinspection GoBoolExpressions
@@ -209,9 +241,24 @@ func New(opts Options) (*Server, error) {
registerWithPrefix(anubis.APIPrefix+"make-challenge", http.HandlerFunc(result.MakeChallenge), "POST")
}
var challSetupErrs []error
for _, implKind := range challenge.Methods() {
impl, _ := challenge.Get(implKind)
impl.Setup(mux)
if err := impl.Setup(mux); err != nil {
challSetupErrs = append(challSetupErrs, fmt.Errorf("error setting up challenge method %s: %w", implKind, err))
}
}
for _, implKind := range extension.Names() {
impl, _ := extension.Get(implKind)
if err := impl.Setup(mux, result.store); err != nil {
challSetupErrs = append(challSetupErrs, fmt.Errorf("error setting up challenge method %s: %w", implKind, err))
}
}
if len(challSetupErrs) != 0 {
return nil, fmt.Errorf("error setting up challenge methods: %w", errors.Join(challSetupErrs...))
}
result.mux = mux
+82 -73
View File
@@ -4,30 +4,29 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"net/url"
"regexp"
"strings"
"time"
"github.com/TecharoHQ/anubis/data"
"k8s.io/apimachinery/pkg/util/yaml"
)
var (
ErrNoBotRulesDefined = errors.New("config: must define at least one (1) bot rule")
ErrBotMustHaveName = errors.New("config.Bot: must set name")
ErrBotMustHaveUserAgentOrPath = errors.New("config.Bot: must set either user_agent_regex, path_regex, headers_regex, or remote_addresses")
ErrBotMustHaveUserAgentOrPath = errors.New("config.Bot: must set one of user_agent_regex, path_regex, headers_regex, remote_addresses, remote_addresses_url, expression, asns, or geoip")
ErrBotMustHaveUserAgentOrPathNotBoth = errors.New("config.Bot: must set either user_agent_regex, path_regex, and not both")
ErrBotMustHaveRemoteAddrOrURLNotBoth = errors.New("config.Bot: must set either remote_addresses or remote_addresses_url, and not both")
ErrInvalidRemoteAddressesURL = errors.New("config.Bot: invalid remote_addresses_url")
ErrUnknownAction = errors.New("config.Bot: unknown action")
ErrInvalidUserAgentRegex = errors.New("config.Bot: invalid user agent regex")
ErrInvalidPathRegex = errors.New("config.Bot: invalid path regex")
ErrInvalidHeadersRegex = errors.New("config.Bot: invalid headers regex")
ErrInvalidCIDR = errors.New("config.Bot: invalid CIDR")
ErrRegexEndsWithNewline = errors.New("config.Bot: regular expression ends with newline (try >- instead of > in yaml)")
ErrInvalidImportStatement = errors.New("config.ImportStatement: invalid source file")
ErrCantSetBotAndImportValuesAtOnce = errors.New("config.BotOrImport: can't set bot rules and import values at the same time")
ErrMustSetBotOrImportRules = errors.New("config.BotOrImport: rule definition is invalid, you must set either bot rules or an import statement, not both")
ErrStatusCodeNotValid = errors.New("config.StatusCode: status code not valid, must be between 100 and 599")
@@ -63,13 +62,14 @@ type BotConfig struct {
Challenge *ChallengeRules `json:"challenge,omitempty" yaml:"challenge,omitempty"`
Weight *Weight `json:"weight,omitempty" yaml:"weight,omitempty"`
// Thoth features
// IP metadata features, backed by the top-level geoip block
GeoIP *GeoIP `json:"geoip,omitempty"`
ASNs *ASNs `json:"asns,omitempty"`
Name string `json:"name" yaml:"name"`
Action Rule `json:"action" yaml:"action"`
RemoteAddr []string `json:"remote_addresses,omitempty" yaml:"remote_addresses,omitempty"`
Name string `json:"name" yaml:"name"`
Action Rule `json:"action" yaml:"action"`
RemoteAddr []string `json:"remote_addresses,omitempty" yaml:"remote_addresses,omitempty"`
RemoteAddressesURL *string `json:"remote_addresses_url,omitempty" yaml:"remote_addresses_url,omitempty"`
}
func (b BotConfig) Zero() bool {
@@ -80,6 +80,7 @@ func (b BotConfig) Zero() bool {
len(b.HeadersRegex) != 0,
b.Action != "",
len(b.RemoteAddr) != 0,
b.RemoteAddressesURL != nil,
b.Challenge != nil,
b.GeoIP != nil,
b.ASNs != nil,
@@ -102,6 +103,7 @@ func (b *BotConfig) Valid() error {
allFieldsEmpty := b.UserAgentRegex == nil &&
b.PathRegex == nil &&
len(b.RemoteAddr) == 0 &&
b.RemoteAddressesURL == nil &&
len(b.HeadersRegex) == 0 &&
b.ASNs == nil &&
b.GeoIP == nil
@@ -114,6 +116,10 @@ func (b *BotConfig) Valid() error {
errs = append(errs, ErrBotMustHaveUserAgentOrPathNotBoth)
}
if len(b.RemoteAddr) > 0 && b.RemoteAddressesURL != nil {
errs = append(errs, ErrBotMustHaveRemoteAddrOrURLNotBoth)
}
if b.UserAgentRegex != nil {
if strings.HasSuffix(*b.UserAgentRegex, "\n") {
errs = append(errs, fmt.Errorf("%w: user agent regex: %q", ErrRegexEndsWithNewline, *b.UserAgentRegex))
@@ -158,6 +164,12 @@ func (b *BotConfig) Valid() error {
}
}
if b.RemoteAddressesURL != nil {
if err := validateRemoteAddressesURL(*b.RemoteAddressesURL); err != nil {
errs = append(errs, err)
}
}
if b.Expression != nil {
if err := b.Expression.Valid(); err != nil {
errs = append(errs, err)
@@ -188,16 +200,29 @@ func (b *BotConfig) Valid() error {
return nil
}
func validateRemoteAddressesURL(raw string) error {
raw = strings.TrimSpace(raw)
u, err := url.Parse(raw)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return fmt.Errorf("%w: %q", ErrInvalidRemoteAddressesURL, raw)
}
return nil
}
type ChallengeRules struct {
Algorithm string `json:"algorithm,omitempty" yaml:"algorithm,omitempty"`
Difficulty int `json:"difficulty,omitempty" yaml:"difficulty,omitempty"`
ReportAs int `json:"report_as,omitempty" yaml:"report_as,omitempty"`
Algorithm string `json:"algorithm,omitempty" yaml:"algorithm,omitempty"`
Difficulty int `json:"difficulty,omitempty" yaml:"difficulty,omitempty"`
ReportAs int `json:"report_as,omitempty" yaml:"report_as,omitempty"`
Extensions []string `json:"extensions,omitempty" yaml:"extensions,omitempty"`
}
var (
ErrChallengeDifficultyTooLow = errors.New("config.ChallengeRules: difficulty is too low (must be >= 0)")
ErrChallengeDifficultyTooHigh = errors.New("config.ChallengeRules: difficulty is too high (must be <= 64)")
ErrChallengeMustHaveAlgorithm = errors.New("config.ChallengeRules: must have algorithm name set")
ErrChallengeExtensionUnknown = errors.New("config.ChallengeRules: unknown challenge extension")
ErrChallengeExtensionEmpty = errors.New("config.ChallengeRules: extension name must not be empty")
ErrChallengeExtensionRepeated = errors.New("config.ChallengeRules: extension name was repeated")
)
func (cr ChallengeRules) Valid() error {
@@ -215,6 +240,20 @@ func (cr ChallengeRules) Valid() error {
errs = append(errs, fmt.Errorf("%w, got: %d", ErrChallengeDifficultyTooHigh, cr.Difficulty))
}
if len(cr.Extensions) != 0 {
seen := make(map[string]struct{}, len(cr.Extensions))
for _, name := range cr.Extensions {
_, repeated := seen[name]
switch {
case name == "":
errs = append(errs, ErrChallengeExtensionEmpty)
case repeated:
errs = append(errs, fmt.Errorf("%w: %q", ErrChallengeExtensionRepeated, name))
}
seen[name] = struct{}{}
}
}
if len(errs) != 0 {
return fmt.Errorf("config: challenge rules entry is not valid:\n%w", errors.Join(errs...))
}
@@ -222,64 +261,6 @@ func (cr ChallengeRules) Valid() error {
return nil
}
type ImportStatement struct {
Import string `json:"import"`
Bots []BotConfig
}
func (is *ImportStatement) open() (fs.File, error) {
if strings.HasPrefix(is.Import, "(data)/") {
fname := strings.TrimPrefix(is.Import, "(data)/")
fin, err := data.BotPolicies.Open(fname)
return fin, err
}
return os.Open(is.Import)
}
func (is *ImportStatement) load() error {
fin, err := is.open()
if err != nil {
return fmt.Errorf("%w: %s: %w", ErrInvalidImportStatement, is.Import, err)
}
defer fin.Close()
var imported []BotOrImport
var result []BotConfig
if err := yaml.NewYAMLToJSONDecoder(fin).Decode(&imported); err != nil {
return fmt.Errorf("can't parse %s: %w", is.Import, err)
}
var errs []error
for _, b := range imported {
if err := b.Valid(); err != nil {
errs = append(errs, err)
}
if b.ImportStatement != nil {
result = append(result, b.ImportStatement.Bots...)
}
if b.BotConfig != nil {
result = append(result, *b.BotConfig)
}
}
if len(errs) != 0 {
return fmt.Errorf("config %s is not valid:\n%w", is.Import, errors.Join(errs...))
}
is.Bots = result
return nil
}
func (is *ImportStatement) Valid() error {
return is.load()
}
type BotOrImport struct {
*BotConfig `json:",inline"`
*ImportStatement `json:",inline"`
@@ -325,7 +306,7 @@ func (sc StatusCodes) Valid() error {
}
type fileConfig struct {
OpenGraph openGraphFileConfig `json:"openGraph,omitempty"`
OpenGraph openGraphFileConfig `json:"openGraph"`
Impressum *Impressum `json:"impressum,omitempty"`
Store *Store `json:"store"`
Bots []BotOrImport `json:"bots"`
@@ -334,6 +315,9 @@ type fileConfig struct {
DNSBL bool `json:"dnsbl"`
DNSTTL DnsTTL `json:"dns_ttl"`
Logging *Logging `json:"logging"`
Metrics *Metrics `json:"metrics,omitempty"`
Honeypot *Honeypot `json:"honeypot"`
GeoIP *GeoIPDatabases `json:"geoip,omitempty"`
}
func (c *fileConfig) Valid() error {
@@ -375,6 +359,24 @@ func (c *fileConfig) Valid() error {
}
}
if c.Metrics != nil {
if err := c.Metrics.Valid(); err != nil {
errs = append(errs, err)
}
}
if c.Honeypot != nil {
if err := c.Honeypot.Valid(); err != nil {
errs = append(errs, err)
}
}
if c.GeoIP != nil {
if err := c.GeoIP.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return fmt.Errorf("config is not valid:\n%w", errors.Join(errs...))
}
@@ -395,7 +397,8 @@ func Load(fin io.Reader, fname string) (*Config, error) {
Store: &Store{
Backend: "memory",
},
Logging: (Logging{}).Default(),
Logging: (Logging{}).Default(),
Honeypot: new((Honeypot{}).Default()),
}
if err := yaml.NewYAMLToJSONDecoder(fin).Decode(&c); err != nil {
@@ -417,6 +420,9 @@ func Load(fin io.Reader, fname string) (*Config, error) {
StatusCodes: c.StatusCodes,
Store: c.Store,
Logging: c.Logging,
Metrics: c.Metrics,
Honeypot: c.Honeypot,
GeoIP: c.GeoIP,
}
if c.OpenGraph.TimeToLive != "" {
@@ -434,7 +440,7 @@ func Load(fin io.Reader, fname string) (*Config, error) {
continue
}
result.Bots = append(result.Bots, boi.ImportStatement.Bots...)
result.Bots = append(result.Bots, boi.Bots...)
}
if boi.BotConfig != nil {
@@ -508,6 +514,9 @@ type Config struct {
Logging *Logging
DNSBL bool
DNSTTL DnsTTL
Metrics *Metrics
Honeypot *Honeypot
GeoIP *GeoIPDatabases
}
func (c Config) Valid() error {
+65 -64
View File
@@ -2,12 +2,10 @@ package config_test
import (
"errors"
"io/fs"
"os"
"path/filepath"
"testing"
"github.com/TecharoHQ/anubis/data"
. "github.com/TecharoHQ/anubis/lib/config"
)
@@ -166,6 +164,62 @@ func TestBotValid(t *testing.T) {
},
err: nil,
},
{
name: "only filter by remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p("https://openai.com/searchbot.json"),
},
err: nil,
},
{
name: "filter by user agent and remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
UserAgentRegex: p("OAI-SearchBot"),
RemoteAddressesURL: p("https://openai.com/searchbot.json"),
},
err: nil,
},
{
name: "invalid remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p("not a url"),
},
err: ErrInvalidRemoteAddressesURL,
},
{
name: "remote addresses url ftp scheme",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p("ftp://example.com/bots.json"),
},
err: ErrInvalidRemoteAddressesURL,
},
{
name: "remote addresses url empty",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddressesURL: p(""),
},
err: ErrInvalidRemoteAddressesURL,
},
{
name: "remote addresses and remote addresses url",
bot: BotConfig{
Name: "openai-searchbot",
Action: RuleAllow,
RemoteAddr: []string{"0.0.0.0/0"},
RemoteAddressesURL: p("https://openai.com/searchbot.json"),
},
err: ErrBotMustHaveRemoteAddrOrURLNotBoth,
},
{
name: "weight rule without weight",
bot: BotConfig{
@@ -188,7 +242,6 @@ func TestBotValid(t *testing.T) {
}
for _, cs := range tests {
cs := cs
t.Run(cs.name, func(t *testing.T) {
err := cs.bot.Valid()
if err == nil && cs.err == nil {
@@ -216,13 +269,12 @@ func TestConfigValidKnownGood(t *testing.T) {
}
for _, st := range finfos {
st := st
t.Run(st.Name(), func(t *testing.T) {
fin, err := os.Open(filepath.Join("testdata", "good", st.Name()))
if err != nil {
t.Fatal(err)
}
defer fin.Close()
defer fin.Close() //nolint:errcheck
c, err := Load(fin, st.Name())
if err != nil {
@@ -240,62 +292,6 @@ func TestConfigValidKnownGood(t *testing.T) {
}
}
func TestImportStatement(t *testing.T) {
type testCase struct {
err error
name string
importPath string
}
var tests []testCase
for _, folderName := range []string{
"apps",
"bots",
"common",
"crawlers",
"meta",
} {
if err := fs.WalkDir(data.BotPolicies, folderName, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if d.Name() == "README.md" {
return nil
}
tests = append(tests, testCase{
name: "(data)/" + path,
importPath: "(data)/" + path,
err: nil,
})
return nil
}); err != nil {
t.Fatal(err)
}
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
is := &ImportStatement{
Import: tt.importPath,
}
if err := is.Valid(); err != nil {
t.Errorf("validation error: %v", err)
}
if len(is.Bots) == 0 {
t.Error("wanted bot definitions, but got none")
}
})
}
}
func TestConfigValidBad(t *testing.T) {
finfos, err := os.ReadDir("testdata/bad")
if err != nil {
@@ -303,17 +299,16 @@ func TestConfigValidBad(t *testing.T) {
}
for _, st := range finfos {
st := st
t.Run(st.Name(), func(t *testing.T) {
fin, err := os.Open(filepath.Join("testdata", "bad", st.Name()))
if err != nil {
t.Fatal(err)
}
defer fin.Close()
defer fin.Close() //nolint:errcheck
_, err = Load(fin, filepath.Join("testdata", "bad", st.Name()))
if err == nil {
t.Fatal("validation should have failed but didn't somehow")
t.Fatalf("validation should have failed but didn't somehow: %v", err)
} else {
t.Log(err)
}
@@ -357,6 +352,12 @@ func TestBotConfigZero(t *testing.T) {
t.Error("config.BotConfig with remote addresses is zero value")
}
var d BotConfig
d.RemoteAddressesURL = p("https://openai.com/searchbot.json")
if d.Zero() {
t.Error("config.BotConfig with remote_addresses_url is zero value")
}
b.Challenge = &ChallengeRules{
Difficulty: 4,
Algorithm: DefaultAlgorithm,
+218
View File
@@ -0,0 +1,218 @@
package config
import (
"errors"
"fmt"
"net/url"
"os"
"time"
)
var (
ErrGeoIPNoDatabases = errors.New("config.GeoIPDatabases: must define at least one of asn or country")
ErrGeoIPNoPath = errors.New("config.GeoIPDatabase: must define path")
ErrGeoIPCountryFieldOnASN = errors.New("config.GeoIPDatabase: country_field can only be set on the country database")
ErrGeoIPInvalidCountryField = errors.New("config.GeoIPDatabase: invalid country_field")
ErrGeoIPEmptyEditionID = errors.New("config.GeoIPDatabase: edition_id must not be empty when set")
ErrGeoIPNoAccountID = errors.New("config.GeoIPAutoUpdate: must define account_id")
ErrGeoIPNoLicenseKeyEnv = errors.New("config.GeoIPAutoUpdate: must define license_key_env")
ErrGeoIPLicenseKeyEnvNotSet = errors.New("config.GeoIPAutoUpdate: environment variable named by license_key_env is not set")
ErrGeoIPInvalidInterval = errors.New("config.GeoIPAutoUpdate: invalid interval")
ErrGeoIPIntervalTooShort = errors.New("config.GeoIPAutoUpdate: interval is too short")
ErrGeoIPInvalidEndpoint = errors.New("config.GeoIPAutoUpdate: invalid endpoint")
)
const (
DefaultGeoIPASNEditionID = "GeoLite2-ASN"
DefaultGeoIPCountryEditionID = "GeoLite2-Country"
DefaultGeoIPUpdateInterval = 24 * time.Hour
MinimumGeoIPUpdateInterval = time.Hour
DefaultGeoIPCountryField = CountryFieldCountry
)
// CountryField selects which country record in a MaxMind country database is
// used for geoip rules.
type CountryField string
const (
// CountryFieldCountry is the country where MaxMind believes the IP address is located.
CountryFieldCountry CountryField = "country"
// CountryFieldRegisteredCountry is the country the IP address is registered to.
CountryFieldRegisteredCountry CountryField = "registered_country"
)
func (cf CountryField) Valid() error {
switch cf {
case CountryFieldCountry, CountryFieldRegisteredCountry:
return nil
default:
return fmt.Errorf("%w: %q, must be one of %q or %q", ErrGeoIPInvalidCountryField, string(cf), CountryFieldCountry, CountryFieldRegisteredCountry)
}
}
// GeoIPDatabases configures the MaxMind databases used for asns and geoip
// rules and ASN logging.
type GeoIPDatabases struct {
ASN *GeoIPDatabase `json:"asn,omitempty" yaml:"asn,omitempty"`
Country *GeoIPDatabase `json:"country,omitempty" yaml:"country,omitempty"`
AutoUpdate *GeoIPAutoUpdate `json:"auto_update,omitempty" yaml:"auto_update,omitempty"`
}
func (g *GeoIPDatabases) Valid() error {
var errs []error
if g.ASN == nil && g.Country == nil {
errs = append(errs, ErrGeoIPNoDatabases)
}
if g.ASN != nil {
if err := g.ASN.Valid(); err != nil {
errs = append(errs, fmt.Errorf("asn: %w", err))
}
if g.ASN.CountryField != nil {
errs = append(errs, fmt.Errorf("asn: %w", ErrGeoIPCountryFieldOnASN))
}
}
if g.Country != nil {
if err := g.Country.Valid(); err != nil {
errs = append(errs, fmt.Errorf("country: %w", err))
}
}
if g.AutoUpdate != nil {
if err := g.AutoUpdate.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return fmt.Errorf("config.GeoIPDatabases: invalid geoip settings:\n%w", errors.Join(errs...))
}
return nil
}
// ASNEditionID returns the MaxMind edition ID for the ASN database.
func (g *GeoIPDatabases) ASNEditionID() string {
return g.ASN.editionID(DefaultGeoIPASNEditionID)
}
// CountryEditionID returns the MaxMind edition ID for the country database.
func (g *GeoIPDatabases) CountryEditionID() string {
return g.Country.editionID(DefaultGeoIPCountryEditionID)
}
// GeoIPDatabase is a single MaxMind database on disk.
type GeoIPDatabase struct {
Path string `json:"path" yaml:"path"`
EditionID *string `json:"edition_id,omitempty" yaml:"edition_id,omitempty"`
CountryField *CountryField `json:"country_field,omitempty" yaml:"country_field,omitempty"`
}
func (g *GeoIPDatabase) Valid() error {
var errs []error
if g.Path == "" {
errs = append(errs, ErrGeoIPNoPath)
}
if g.EditionID != nil && *g.EditionID == "" {
errs = append(errs, ErrGeoIPEmptyEditionID)
}
if g.CountryField != nil {
if err := g.CountryField.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Join(errs...)
}
return nil
}
// GetCountryField returns the configured country field or the default.
func (g *GeoIPDatabase) GetCountryField() CountryField {
if g == nil || g.CountryField == nil {
return DefaultGeoIPCountryField
}
return *g.CountryField
}
func (g *GeoIPDatabase) editionID(def string) string {
if g == nil || g.EditionID == nil {
return def
}
return *g.EditionID
}
// GeoIPAutoUpdate configures automatic database updates from MaxMind.
type GeoIPAutoUpdate struct {
AccountID int `json:"account_id" yaml:"account_id"`
LicenseKeyEnv string `json:"license_key_env" yaml:"license_key_env"`
Interval *string `json:"interval,omitempty" yaml:"interval,omitempty"`
Endpoint *string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"`
}
func (g *GeoIPAutoUpdate) Valid() error {
var errs []error
if g.AccountID <= 0 {
errs = append(errs, ErrGeoIPNoAccountID)
}
switch {
case g.LicenseKeyEnv == "":
errs = append(errs, ErrGeoIPNoLicenseKeyEnv)
case os.Getenv(g.LicenseKeyEnv) == "":
errs = append(errs, fmt.Errorf("%w: %s", ErrGeoIPLicenseKeyEnvNotSet, g.LicenseKeyEnv))
}
if g.Interval != nil {
d, err := time.ParseDuration(*g.Interval)
switch {
case err != nil:
errs = append(errs, fmt.Errorf("%w: %w", ErrGeoIPInvalidInterval, err))
case d < MinimumGeoIPUpdateInterval:
errs = append(errs, fmt.Errorf("%w: %s is less than %s", ErrGeoIPIntervalTooShort, d, MinimumGeoIPUpdateInterval))
}
}
if g.Endpoint != nil {
u, err := url.Parse(*g.Endpoint)
switch {
case err != nil:
errs = append(errs, fmt.Errorf("%w: %w", ErrGeoIPInvalidEndpoint, err))
case u.Scheme != "http" && u.Scheme != "https", u.Host == "":
errs = append(errs, fmt.Errorf("%w: %q must be an absolute http or https URL", ErrGeoIPInvalidEndpoint, *g.Endpoint))
}
}
if len(errs) != 0 {
return fmt.Errorf("auto_update: %w", errors.Join(errs...))
}
return nil
}
// GetInterval returns the parsed update interval or the default. Call Valid first.
func (g *GeoIPAutoUpdate) GetInterval() time.Duration {
if g.Interval == nil {
return DefaultGeoIPUpdateInterval
}
// XXX(Xe): already validated in Valid()
d, _ := time.ParseDuration(*g.Interval)
return d
}
// LicenseKey reads the license key from the configured environment variable.
func (g *GeoIPAutoUpdate) LicenseKey() string {
return os.Getenv(g.LicenseKeyEnv)
}
+214
View File
@@ -0,0 +1,214 @@
package config
import (
"errors"
"os"
"path/filepath"
"testing"
"time"
)
const testLicenseKeyEnv = "ANUBIS_TEST_MAXMIND_LICENSE_KEY"
func TestGeoIPDatabasesValid(t *testing.T) {
for _, tt := range []struct {
name string
input *GeoIPDatabases
setEnv bool
errs []error
}{
{
name: "asn only",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
},
},
{
name: "country only with registered_country",
input: &GeoIPDatabases{
Country: &GeoIPDatabase{
Path: "/tmp/country.mmdb",
CountryField: new(CountryFieldRegisteredCountry),
},
},
},
{
name: "both with auto update",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
Country: &GeoIPDatabase{Path: "/tmp/country.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
Interval: new("72h"),
Endpoint: new("https://updates.maxmind.com"),
},
},
setEnv: true,
},
{
name: "no databases",
input: &GeoIPDatabases{},
errs: []error{ErrGeoIPNoDatabases},
},
{
name: "no path",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{},
Country: &GeoIPDatabase{},
},
errs: []error{ErrGeoIPNoPath},
},
{
name: "empty edition id",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb", EditionID: new("")},
},
errs: []error{ErrGeoIPEmptyEditionID},
},
{
name: "country field on asn",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb", CountryField: new(CountryFieldCountry)},
},
errs: []error{ErrGeoIPCountryFieldOnASN},
},
{
name: "invalid country field",
input: &GeoIPDatabases{
Country: &GeoIPDatabase{Path: "/tmp/country.mmdb", CountryField: new(CountryField("continent"))},
},
errs: []error{ErrGeoIPInvalidCountryField},
},
{
name: "auto update missing everything",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{},
},
errs: []error{ErrGeoIPNoAccountID, ErrGeoIPNoLicenseKeyEnv},
},
{
name: "auto update license env not set",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
},
},
errs: []error{ErrGeoIPLicenseKeyEnvNotSet},
},
{
name: "auto update bad interval and endpoint",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
Interval: new("soon"),
Endpoint: new("updates.maxmind.com"),
},
},
setEnv: true,
errs: []error{ErrGeoIPInvalidInterval, ErrGeoIPInvalidEndpoint},
},
{
name: "auto update interval too short",
input: &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: testLicenseKeyEnv,
Interval: new("5m"),
},
},
setEnv: true,
errs: []error{ErrGeoIPIntervalTooShort},
},
} {
t.Run(tt.name, func(t *testing.T) {
if tt.setEnv {
t.Setenv(testLicenseKeyEnv, "hunter2")
} else {
t.Setenv(testLicenseKeyEnv, "")
}
err := tt.input.Valid()
if len(tt.errs) == 0 && err != nil {
t.Fatalf("wanted no error, got: %v", err)
}
if len(tt.errs) != 0 && err == nil {
t.Fatalf("wanted errors %v, got nil", tt.errs)
}
for _, want := range tt.errs {
if !errors.Is(err, want) {
t.Logf("want: %v", want)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
}
})
}
}
func TestGeoIPDatabasesDefaults(t *testing.T) {
g := &GeoIPDatabases{
ASN: &GeoIPDatabase{Path: "/tmp/asn.mmdb"},
Country: &GeoIPDatabase{Path: "/tmp/country.mmdb"},
AutoUpdate: &GeoIPAutoUpdate{},
}
if got := g.ASNEditionID(); got != DefaultGeoIPASNEditionID {
t.Errorf("ASNEditionID: want %q, got %q", DefaultGeoIPASNEditionID, got)
}
if got := g.CountryEditionID(); got != DefaultGeoIPCountryEditionID {
t.Errorf("CountryEditionID: want %q, got %q", DefaultGeoIPCountryEditionID, got)
}
if got := g.Country.GetCountryField(); got != CountryFieldCountry {
t.Errorf("GetCountryField: want %q, got %q", CountryFieldCountry, got)
}
if got := g.AutoUpdate.GetInterval(); got != DefaultGeoIPUpdateInterval {
t.Errorf("GetInterval: want %s, got %s", DefaultGeoIPUpdateInterval, got)
}
g.AutoUpdate.Interval = new("2h")
if got := g.AutoUpdate.GetInterval(); got != 2*time.Hour {
t.Errorf("GetInterval: want %s, got %s", 2*time.Hour, got)
}
}
func TestGeoIPDatabasesLoad(t *testing.T) {
fin, err := os.Open(filepath.Join("testdata", "geoip_databases.yaml"))
if err != nil {
t.Fatal(err)
}
defer fin.Close() //nolint:errcheck
c, err := Load(fin, "geoip_databases.yaml")
if err != nil {
t.Fatal(err)
}
if c.GeoIP == nil {
t.Fatal("wanted geoip block to be loaded, got nil")
}
if got := c.GeoIP.ASN.Path; got != "/var/lib/anubis/GeoLite2-ASN.mmdb" {
t.Errorf("asn path: got %q", got)
}
if got := c.GeoIP.Country.GetCountryField(); got != CountryFieldRegisteredCountry {
t.Errorf("country field: want %q, got %q", CountryFieldRegisteredCountry, got)
}
if c.GeoIP.AutoUpdate != nil {
t.Errorf("auto_update: want nil, got %+v", c.GeoIP.AutoUpdate)
}
}
+44
View File
@@ -0,0 +1,44 @@
package config
import (
"errors"
"fmt"
)
var ErrInvalidHoneypotMethod = errors.New("config.Honeypot: invalid implementation selected (try: \"naive\")")
type Honeypot struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Implementation string `json:"implementation" yaml:"implementation"`
IPLogFile string `json:"ip_log_file" yaml:"ip_log_file"`
}
func (h Honeypot) Valid() error {
var errs []error
// Short-circuit, if disabled then the implementation is moot.
if !h.Enabled {
return nil
}
if h.Implementation == "" {
errs = append(errs, fmt.Errorf("config.Honeypot: missing field \"implementation\": %w", ErrMissingValue))
}
if h.Implementation != "naive" {
errs = append(errs, fmt.Errorf("%w: got: %q", ErrInvalidHoneypotMethod, h.Implementation))
}
if len(errs) != 0 {
return errors.Join(errs...)
}
return nil
}
func (h Honeypot) Default() Honeypot {
return Honeypot{
Enabled: true,
Implementation: "naive",
}
}
+87
View File
@@ -0,0 +1,87 @@
package config
import (
"errors"
"testing"
)
func TestHoneypotValid(t *testing.T) {
for _, cs := range []struct {
err error
name string
inp Honeypot
}{
{
name: "naive enabled",
inp: Honeypot{
Enabled: true,
Implementation: "naive",
},
err: nil,
},
{
name: "naive disabled",
inp: Honeypot{
Enabled: false,
Implementation: "naive",
},
err: nil,
},
{
name: "empty implementation",
inp: Honeypot{
Enabled: true,
Implementation: "",
},
err: ErrInvalidHoneypotMethod,
},
{
name: "unknown implementation",
inp: Honeypot{
Enabled: true,
Implementation: "sophisticated",
},
err: ErrInvalidHoneypotMethod,
},
{
name: "wrong case implementation",
inp: Honeypot{
Enabled: true,
Implementation: "Naive",
},
err: ErrInvalidHoneypotMethod,
},
{
name: "zero value",
inp: Honeypot{},
err: nil,
},
} {
t.Run(cs.name, func(t *testing.T) {
if err := cs.inp.Valid(); !errors.Is(err, cs.err) {
t.Logf("want: %v", cs.err)
t.Logf("got: %v", err)
t.Error("validation returned an unexpected error")
}
})
}
}
func TestHoneypotDefault(t *testing.T) {
want := Honeypot{
Enabled: true,
Implementation: "naive",
}
got := (Honeypot{}).Default()
if got != want {
t.Errorf("Default() = %+v, want %+v", got, want)
}
}
func TestHoneypotDefaultIsValid(t *testing.T) {
h := (Honeypot{}).Default()
if err := h.Valid(); err != nil {
t.Fatal(err)
}
}
+155
View File
@@ -0,0 +1,155 @@
package config
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"github.com/TecharoHQ/anubis/data"
"github.com/TecharoHQ/anubis/internal/multifile"
"github.com/fvbommel/sortorder"
"github.com/goreleaser/fileglob"
"k8s.io/apimachinery/pkg/util/yaml"
)
var (
ErrInvalidImportStatement = errors.New("config.ImportStatement: invalid source file")
ErrCantReadImportedFile = errors.New("config.ImportStatement: can't read imported file")
ErrGlobMatchedNothing = errors.New("config.ImportStatement: glob pattern matched no files")
)
type ImportStatement struct {
Import string `json:"import"`
Bots []BotConfig
}
const globHints = `recursive wildcards ("**") and alternation ("{yaml,yml}") are not supported`
func globMatch(globbedPath string) (fs.FS, []string, error) {
var fsys fs.FS = nil
if after, ok := strings.CutPrefix(globbedPath, "(data)/"); ok {
globbedPath = after
fsys = data.BotPolicies
}
var matches []string
var err error
switch {
case fsys == nil:
matches, err = filepath.Glob(globbedPath)
case fsys != nil:
matches, err = fs.Glob(fsys, globbedPath)
}
if err != nil {
return nil, nil, fmt.Errorf("%w: %w", ErrInvalidImportStatement, err)
}
if len(matches) == 0 {
if strings.Contains(globbedPath, "**") || strings.Contains(globbedPath, "{") {
return nil, nil, fmt.Errorf("%w: note that %s", ErrGlobMatchedNothing, globHints)
}
return nil, nil, ErrGlobMatchedNothing
}
sort.Sort(sortorder.Natural(matches))
var errs []error
for _, fname := range matches {
switch {
case fsys == nil:
if _, err := os.Stat(fname); err != nil {
errs = append(errs, fmt.Errorf("%w: %q", ErrCantReadImportedFile, fname))
}
case fsys != nil:
if _, err := fs.Stat(fsys, fname); err != nil {
errs = append(errs, fmt.Errorf("%w: %q", ErrCantReadImportedFile, fname))
}
}
}
if len(errs) != 0 {
return nil, nil, fmt.Errorf("%w: %w", ErrInvalidImportStatement, errors.Join(errs...))
}
return fsys, matches, nil
}
func (is *ImportStatement) open() (fs.File, error) {
if fileglob.ContainsMatchers(is.Import) {
fsys, fnames, err := globMatch(is.Import)
if err != nil {
return nil, err
}
return multifile.YAMLList(fsys, fnames)
}
if after, ok := strings.CutPrefix(is.Import, "(data)/"); ok {
fname := after
fin, err := data.BotPolicies.Open(fname)
return fin, err
}
return os.Open(is.Import)
}
func (is *ImportStatement) load() error {
fin, err := is.open()
if err != nil {
return fmt.Errorf("%w: %s: %w", ErrInvalidImportStatement, is.Import, err)
}
defer fin.Close() //nolint:errcheck
var imported []BotOrImport
var result []BotConfig
dec := yaml.NewYAMLToJSONDecoder(fin)
for {
var doc []BotOrImport
if err := dec.Decode(&doc); err != nil {
if errors.Is(err, io.EOF) {
break
}
return fmt.Errorf("%w: can't parse %s: %w", ErrInvalidImportStatement, is.Import, err)
}
imported = append(imported, doc...)
}
var errs []error
for _, b := range imported {
if err := b.Valid(); err != nil {
errs = append(errs, err)
}
if b.ImportStatement != nil {
result = append(result, b.Bots...)
}
if b.BotConfig != nil {
result = append(result, *b.BotConfig)
}
}
if len(errs) != 0 {
return fmt.Errorf("config %s is not valid:\n%w", is.Import, errors.Join(errs...))
}
is.Bots = result
return nil
}
func (is *ImportStatement) Valid() error {
return is.load()
}
+146
View File
@@ -0,0 +1,146 @@
package config
import (
"errors"
"io/fs"
"path/filepath"
"slices"
"testing"
"github.com/TecharoHQ/anubis/data"
)
func TestGlobMatch(t *testing.T) {
for _, tt := range []struct {
globbedPath string
matches []string
err error
}{
{
globbedPath: "(data)/apps/allow-api-routes*.yaml",
matches: []string{"apps/allow-api-routes.yaml"},
},
{
globbedPath: "./testdata/hack-test.*",
matches: []string{"testdata/hack-test.json", "testdata/hack-test.yaml"},
},
{
globbedPath: "/does/not/exist/*",
err: ErrGlobMatchedNothing,
},
{
// filepath.Match has no alternation syntax, so the braces are
// matched literally and nothing is found.
globbedPath: "(data)/bots/*.{yaml,yml}",
err: ErrGlobMatchedNothing,
},
} {
t.Run(tt.globbedPath, func(t *testing.T) {
_, matches, err := globMatch(tt.globbedPath)
if !errors.Is(err, tt.err) {
t.Logf("wanted error: %v", tt.err)
t.Logf(" got error: %v", err)
t.Error("unexpected error received")
}
if !slices.Equal(tt.matches, matches) {
t.Logf("wanted files: %#v", tt.matches)
t.Logf(" got files: %#v", matches)
t.Error("unexpected file matches")
}
})
}
}
func TestImportMultiDocument(t *testing.T) {
for _, tt := range []struct {
name string
globbedPath string
botCount int
}{
{"multi-document", "./testdata/multi-document/*.yaml", 3},
{"single-file", "./testdata/multi-document/small-internet-browsers.yaml", 2},
} {
t.Run(tt.name, func(t *testing.T) {
is := &ImportStatement{Import: tt.globbedPath}
if err := is.Valid(); err != nil {
t.Fatal(err)
}
if len(is.Bots) != tt.botCount {
t.Errorf("wanted bot count: %d, got: %d", tt.botCount, len(is.Bots))
}
})
}
}
// TestImportStatementGlobMatchedNothing asserts that an import statement whose
// glob pattern matches no files fails with ErrGlobMatchedNothing instead of the
// io.EOF that the YAML decoder would return for an empty document.
func TestImportStatementGlobMatchedNothing(t *testing.T) {
for _, globbedPath := range []string{
"(data)/bots/*.yml",
"(data)/does-not-exist/*.yaml",
"./testdata/does-not-exist/*.yaml",
} {
t.Run(globbedPath, func(t *testing.T) {
is := &ImportStatement{Import: globbedPath}
err := is.Valid()
if !errors.Is(err, ErrGlobMatchedNothing) {
t.Logf("wanted error: %v", ErrGlobMatchedNothing)
t.Logf(" got error: %v", err)
t.Error("unexpected error received")
}
})
}
}
// TestImportStatement asserts that every policy snippet in the data folder can
// be imported and is valid. The list of files is discovered by walking the
// embedded filesystem so that new folders and new snippets are covered without
// having to remember to add them here.
func TestImportStatement(t *testing.T) {
var importPaths []string
if err := fs.WalkDir(data.BotPolicies, ".", func(path string, d fs.DirEntry, err error) error {
switch {
case err != nil:
return err
case d.IsDir():
return nil
case path == "botPolicies.yaml": // an entire config, not a list of bots
return nil
}
switch filepath.Ext(path) {
case ".yaml", ".yml":
importPaths = append(importPaths, "(data)/"+path)
}
return nil
}); err != nil {
t.Fatal(err)
}
if len(importPaths) == 0 {
t.Fatal("no policy snippets found in the embedded data folder")
}
for _, importPath := range importPaths {
t.Run(importPath, func(t *testing.T) {
is := &ImportStatement{
Import: importPath,
}
if err := is.Valid(); err != nil {
t.Errorf("validation error: %v", err)
}
if len(is.Bots) == 0 {
t.Error("wanted bot definitions, but got none")
}
})
}
}
+1
View File
@@ -17,6 +17,7 @@ type Logging struct {
Sink string `json:"sink"` // Logging sink, either "stdio" or "file"
Level *slog.Level `json:"level"` // Log level, if set supersedes the level in flags
Parameters *LoggingFileConfig `json:"parameters"` // Logging parameters, to be dynamic in the future
LogASN bool `json:"asn" yaml:"asn"`
}
const (
+170
View File
@@ -0,0 +1,170 @@
package config
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"strconv"
)
var (
ErrInvalidMetricsConfig = errors.New("config: invalid metrics configuration")
ErrInvalidMetricsTLSConfig = errors.New("config: invalid metrics TLS configuration")
ErrInvalidMetricsBasicAuthConfig = errors.New("config: invalid metrics basic auth configuration")
ErrNoMetricsBind = errors.New("config.Metrics: must define bind")
ErrNoMetricsNetwork = errors.New("config.Metrics: must define network")
ErrNoMetricsSocketMode = errors.New("config.Metrics: must define socket mode when using unix sockets")
ErrInvalidMetricsSocketMode = errors.New("config.Metrics: invalid unix socket mode")
ErrInvalidMetricsNetwork = errors.New("config.Metrics: invalid metrics network")
ErrNoMetricsTLSCertificate = errors.New("config.Metrics.TLS: must define certificate file")
ErrNoMetricsTLSKey = errors.New("config.Metrics.TLS: must define key file")
ErrInvalidMetricsTLSKeypair = errors.New("config.Metrics.TLS: keypair is invalid")
ErrInvalidMetricsCACertificate = errors.New("config.Metrics.TLS: invalid CA certificate")
ErrCantReadFile = errors.New("config: can't read required file")
ErrNoMetricsBasicAuthUsername = errors.New("config.Metrics.BasicAuth: must define username")
ErrNoMetricsBasicAuthPassword = errors.New("config.Metrics.BasicAuth: must define password")
)
type Metrics struct {
Bind string `json:"bind" yaml:"bind"`
Network string `json:"network" yaml:"network"`
SocketMode string `json:"socketMode" yaml:"socketMode"`
TLS *MetricsTLS `json:"tls" yaml:"tls"`
Debug bool `json:"debug" yaml:"debug"`
BasicAuth *MetricsBasicAuth `json:"basicAuth" yaml:"basicAuth"`
}
func (m *Metrics) Valid() error {
var errs []error
if m.Bind == "" {
errs = append(errs, ErrNoMetricsBind)
}
if m.Network == "" {
errs = append(errs, ErrNoMetricsNetwork)
}
switch m.Network {
case "tcp", "tcp4", "tcp6": // https://pkg.go.dev/net#Listen
case "unix":
if m.SocketMode == "" {
errs = append(errs, ErrNoMetricsSocketMode)
}
if _, err := strconv.ParseUint(m.SocketMode, 8, 0); err != nil {
errs = append(errs, fmt.Errorf("%w: %w", ErrInvalidMetricsSocketMode, err))
}
default:
errs = append(errs, ErrInvalidMetricsNetwork)
}
if m.TLS != nil {
if err := m.TLS.Valid(); err != nil {
errs = append(errs, err)
}
}
if m.BasicAuth != nil {
if err := m.BasicAuth.Valid(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Join(ErrInvalidMetricsConfig, errors.Join(errs...))
}
return nil
}
type MetricsTLS struct {
Certificate string `json:"certificate" yaml:"certificate"`
Key string `json:"key" yaml:"key"`
CA string `json:"ca" yaml:"ca"`
}
func (mt *MetricsTLS) Valid() error {
var errs []error
if mt.Certificate == "" {
errs = append(errs, ErrNoMetricsTLSCertificate)
}
if err := canReadFile(mt.Certificate); err != nil {
errs = append(errs, fmt.Errorf("%w %s: %w", ErrCantReadFile, mt.Certificate, err))
}
if mt.Key == "" {
errs = append(errs, ErrNoMetricsTLSKey)
}
if err := canReadFile(mt.Key); err != nil {
errs = append(errs, fmt.Errorf("%w %s: %w", ErrCantReadFile, mt.Key, err))
}
if _, err := tls.LoadX509KeyPair(mt.Certificate, mt.Key); err != nil {
errs = append(errs, fmt.Errorf("%w: %w", ErrInvalidMetricsTLSKeypair, err))
}
if mt.CA != "" {
caCert, err := os.ReadFile(mt.CA)
if err != nil {
errs = append(errs, fmt.Errorf("%w %s: %w", ErrCantReadFile, mt.CA, err))
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(caCert) {
errs = append(errs, fmt.Errorf("%w %s", ErrInvalidMetricsCACertificate, mt.CA))
}
}
if len(errs) != 0 {
return errors.Join(ErrInvalidMetricsTLSConfig, errors.Join(errs...))
}
return nil
}
func canReadFile(fname string) error {
fin, err := os.Open(fname)
if err != nil {
return err
}
data := make([]byte, 64)
if _, err := fin.Read(data); err != nil {
return fmt.Errorf("can't read %s: %w", fname, err)
}
if err := fin.Close(); err != nil {
return err
}
return nil
}
type MetricsBasicAuth struct {
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
}
func (mba *MetricsBasicAuth) Valid() error {
var errs []error
if mba.Username == "" {
errs = append(errs, ErrNoMetricsBasicAuthUsername)
}
if mba.Password == "" {
errs = append(errs, ErrNoMetricsBasicAuthPassword)
}
if len(errs) != 0 {
return errors.Join(ErrInvalidMetricsBasicAuthConfig, errors.Join(errs...))
}
return nil
}
+242
View File
@@ -0,0 +1,242 @@
package config
import (
"errors"
"testing"
)
func TestMetricsValid(t *testing.T) {
for _, tt := range []struct {
name string
input *Metrics
err error
}{
{
name: "basic TCP",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
},
},
{
name: "basic TCP4",
input: &Metrics{
Bind: ":9090",
Network: "tcp4",
},
},
{
name: "basic TCP6",
input: &Metrics{
Bind: ":9090",
Network: "tcp6",
},
},
{
name: "basic unix",
input: &Metrics{
Bind: "/tmp/anubis-metrics.sock",
Network: "unix",
SocketMode: "0770",
},
},
{
name: "no bind",
input: &Metrics{},
err: ErrNoMetricsBind,
},
{
name: "no network",
input: &Metrics{},
err: ErrNoMetricsNetwork,
},
{
name: "no unix socket mode",
input: &Metrics{
Bind: "/tmp/anubis-metrics.sock",
Network: "unix",
},
err: ErrNoMetricsSocketMode,
},
{
name: "invalid unix socket mode",
input: &Metrics{
Bind: "/tmp/anubis-metrics.sock",
Network: "unix",
SocketMode: "taco bell",
},
err: ErrInvalidMetricsSocketMode,
},
{
name: "invalid network",
input: &Metrics{
Bind: ":9090",
Network: "taco",
},
err: ErrInvalidMetricsNetwork,
},
{
name: "invalid TLS config",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{},
},
err: ErrInvalidMetricsTLSConfig,
},
{
name: "selfsigned TLS cert",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
},
},
},
{
name: "wrong path to selfsigned TLS cert",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls2/selfsigned.crt",
Key: "./testdata/tls2/selfsigned.key",
},
},
err: ErrCantReadFile,
},
{
name: "unparseable TLS cert",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/invalid.crt",
Key: "./testdata/tls/invalid.key",
},
},
err: ErrInvalidMetricsTLSKeypair,
},
{
name: "mTLS with CA",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
CA: "./testdata/tls/minica.pem",
},
},
},
{
name: "mTLS with nonexistent CA",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
CA: "./testdata/tls/nonexistent.crt",
},
},
err: ErrCantReadFile,
},
{
name: "mTLS with invalid CA",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
TLS: &MetricsTLS{
Certificate: "./testdata/tls/selfsigned.crt",
Key: "./testdata/tls/selfsigned.key",
CA: "./testdata/tls/invalid.crt",
},
},
err: ErrInvalidMetricsCACertificate,
},
{
name: "basic auth credentials set",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
BasicAuth: &MetricsBasicAuth{
Username: "admin",
Password: "hunter2",
},
},
},
{
name: "invalid basic auth config",
input: &Metrics{
Bind: ":9090",
Network: "tcp",
BasicAuth: &MetricsBasicAuth{},
},
err: ErrInvalidMetricsBasicAuthConfig,
},
} {
t.Run(tt.name, func(t *testing.T) {
if err := tt.input.Valid(); !errors.Is(err, tt.err) {
t.Logf("wanted error: %v", tt.err)
t.Logf("got error: %v", err)
t.Error("validation failed")
}
})
}
}
func TestMetricsBasicAuthValid(t *testing.T) {
for _, tt := range []struct {
name string
input *MetricsBasicAuth
err error
}{
{
name: "both set",
input: &MetricsBasicAuth{
Username: "admin",
Password: "hunter2",
},
},
{
name: "empty username and password",
input: &MetricsBasicAuth{},
err: ErrInvalidMetricsBasicAuthConfig,
},
{
name: "missing username",
input: &MetricsBasicAuth{
Password: "hunter2",
},
err: ErrNoMetricsBasicAuthUsername,
},
{
name: "missing password",
input: &MetricsBasicAuth{
Username: "admin",
},
err: ErrNoMetricsBasicAuthPassword,
},
{
name: "missing both surfaces wrapper error",
input: &MetricsBasicAuth{},
err: ErrNoMetricsBasicAuthUsername,
},
{
name: "missing both surfaces password error",
input: &MetricsBasicAuth{},
err: ErrNoMetricsBasicAuthPassword,
},
} {
t.Run(tt.name, func(t *testing.T) {
if err := tt.input.Valid(); !errors.Is(err, tt.err) {
t.Logf("wanted error: %v", tt.err)
t.Logf("got error: %v", err)
t.Error("validation failed")
}
})
}
}
@@ -0,0 +1,9 @@
bots:
- name: everyone
user_agent_regex: .
action: CHALLENGE
challenge:
algorithm: metarefresh
difficulty: 1
extensions:
- ""
@@ -0,0 +1,10 @@
bots:
- name: everyone
user_agent_regex: .
action: CHALLENGE
challenge:
algorithm: metarefresh
difficulty: 1
extensions:
- test-extension
- test-extension
@@ -0,0 +1,11 @@
bots:
- name: everything
action: CHALLENGE
path_regex: .*
geoip:
asn:
path: /var/lib/anubis/GeoLite2-ASN.mmdb
auto_update:
license_key_env: ANUBIS_TEST_MAXMIND_LICENSE_KEY_THAT_IS_NOT_SET
interval: 5m
@@ -0,0 +1,9 @@
bots:
- name: everything
action: CHALLENGE
path_regex: .*
geoip:
country:
path: /var/lib/anubis/GeoLite2-Country.mmdb
country_field: continent
+8
View File
@@ -0,0 +1,8 @@
bots:
- name: everything
action: CHALLENGE
path_regex: .*
geoip:
asn:
edition_id: GeoLite2-ASN
@@ -0,0 +1,8 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: true
implementation: ""
@@ -0,0 +1,13 @@
{
"bots": [
{
"name": "everything",
"user_agent_regex": ".*",
"action": "DENY"
}
],
"honeypot": {
"enabled": true,
"implementation": "sophisticated"
}
}
@@ -0,0 +1,8 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: true
implementation: sophisticated
+2
View File
@@ -0,0 +1,2 @@
bots:
- import: (data)/bots/never-matches/*[abc]abc]\.yaml
+2
View File
@@ -0,0 +1,2 @@
bots:
- import: (data)/bots/never-matches/*.yaml
+3
View File
@@ -0,0 +1,3 @@
metrics:
bind: ":9090"
network: taco
+6
View File
@@ -0,0 +1,6 @@
bots:
- name: both-addr-kinds
action: ALLOW
remote_addresses:
- "0.0.0.0/0"
remote_addresses_url: "https://openai.com/searchbot.json"
+23
View File
@@ -0,0 +1,23 @@
bots:
- name: countries-with-aggressive-scrapers
action: WEIGH
geoip:
countries:
- BR
- CN
weight:
adjust: 10
- name: aggressive-asns-without-functional-abuse-contact
action: WEIGH
asns:
match:
- 13335
weight:
adjust: 10
geoip:
asn:
path: /var/lib/anubis/GeoLite2-ASN.mmdb
country:
path: /var/lib/anubis/GeoLite2-Country.mmdb
country_field: registered_country
+5 -1
View File
@@ -5,5 +5,9 @@
"remote_addresses": ["0.0.0.0/0", "::/0"],
"action": "ALLOW"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -4,3 +4,7 @@ bots:
- "0.0.0.0/0"
- "::/0"
action: ALLOW
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -8,5 +8,9 @@
"action": "DENY"
}
],
"dnsbl": false
"dnsbl": false,
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -3,3 +3,7 @@ bots:
headers_regex:
CF-Worker: .*
action: DENY
metrics:
bind: ":9090"
network: "tcp"
+19
View File
@@ -0,0 +1,19 @@
bots:
- name: everyone
user_agent_regex: .
action: CHALLENGE
challenge:
algorithm: fast
difficulty: 2
extensions:
- test-extension
thresholds:
- name: extreme-suspicion
expression: weight >= 20
action: CHALLENGE
challenge:
algorithm: preact
difficulty: 1
extensions:
- test-extension
+4
View File
@@ -4,3 +4,7 @@ bots:
asns:
match:
- 13335 # Cloudflare
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -5,5 +5,9 @@
"user_agent_regex": "Mozilla",
"action": "CHALLENGE"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -2,3 +2,7 @@ bots:
- name: generic-browser
user_agent_regex: Mozilla
action: CHALLENGE
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -6,3 +6,7 @@ bots:
- name: "test"
user_agent_regex: ".*"
action: "DENY"
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -6,3 +6,7 @@ bots:
- '"Accept" in headers'
- headers["Accept"].contains("text/html")
- randInt(1) == 0
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -6,5 +6,9 @@
"action": "DENY"
}
],
"dnsbl": false
"dnsbl": false,
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -2,3 +2,7 @@ bots:
- name: everything
user_agent_regex: .*
action: DENY
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -4,3 +4,7 @@ bots:
geoip:
countries:
- US
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -10,5 +10,9 @@
]
}
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -6,3 +6,7 @@ bots:
- userAgent.startsWith("git/") || userAgent.contains("libgit")
- >
"Git-Protocol" in headers && headers["Git-Protocol"] == "version=2"
metrics:
bind: ":9090"
network: "tcp"
+7
View File
@@ -0,0 +1,7 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: false
+13
View File
@@ -0,0 +1,13 @@
{
"bots": [
{
"name": "everything",
"user_agent_regex": ".*",
"action": "DENY"
}
],
"honeypot": {
"enabled": true,
"implementation": "naive"
}
}
+8
View File
@@ -0,0 +1,8 @@
bots:
- name: everything
user_agent_regex: .*
action: DENY
honeypot:
enabled: true
implementation: naive
+2
View File
@@ -0,0 +1,2 @@
bots:
- import: (data)/bots/*.yaml
+5 -1
View File
@@ -3,5 +3,9 @@
{
"import": "./testdata/hack-test.json"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -1,2 +1,6 @@
bots:
- import: ./testdata/hack-test.yaml
metrics:
bind: ":9090"
network: "tcp"
@@ -0,0 +1,6 @@
bots:
- import: (data)/clients/google-user-triggered-fetchers.yaml
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -3,5 +3,9 @@
{
"import": "(data)/common/keep-internet-working.yaml"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
@@ -1,2 +1,6 @@
bots:
- import: (data)/common/keep-internet-working.yaml
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -8,3 +8,7 @@ impressum:
page:
title: Test
body: <p>This is a test</p>
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -13,3 +13,7 @@ logs:
oldFileTimeFormat: 2006-01-02T15-04-05 # RFC 3339-ish
compress: true
useLocalTime: false # timezone for rotated files is UTC
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -5,3 +5,7 @@ bots:
logging:
sink: "stdio"
metrics:
bind: ":9090"
network: "tcp"
+4
View File
@@ -6,3 +6,7 @@ bots:
adjust: 5
thresholds: []
metrics:
bind: ":9090"
network: "tcp"
+5 -1
View File
@@ -75,5 +75,9 @@
"user_agent_regex": "Mozilla",
"action": "CHALLENGE"
}
]
],
"metrics": {
"bind": ":9090",
"network": "tcp"
}
}
+4
View File
@@ -10,3 +10,7 @@ openGraph:
default:
"og:title": "Xe's magic land of fun"
"og:description": "We're no strangers to love, you know the rules and so do I"
metrics:
bind: ":9090"
network: "tcp"
Loaded 100 of 573 files, more files were not shown because too many files have changed in this diff. Show more