Update to Anubis v1.28.2 (#1)

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

## Approach

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

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

## Customizations kept

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

## Deploy notes

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

## Verification

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

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

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

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

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

No files matched your search

+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)
}
}
})
}
}