Files
masyunis/lib/extension_test.go
sol_bot Bot caf4d72880 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>
2026-11-28 12:10:27 +00:00

200 lines
5.3 KiB
Go

package lib
import (
"compress/gzip"
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/challenge/extension"
"github.com/TecharoHQ/anubis/lib/store"
"github.com/a-h/templ"
)
// XXX(Xe): This is the only real place this test can run because anywhere
// else incurs wicked import loops that I really don't want to trace down
// because that means a lot of drift across a lot of the program.
const testExtensionMarker = `<meta name="text-extension" />`
// testExtension is a test fixture extension that tests the extension
// loading and dispatch logic.
type testExtension struct {
lock sync.Mutex
validateErr error
seenIDs []string
}
func (te *testExtension) Setup(mux *http.ServeMux, st store.Interface) error { return nil }
func (te *testExtension) Head(r *http.Request, chall *challenge.Challenge) templ.Component {
return templ.Raw(testExtensionMarker)
}
func (te *testExtension) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {
te.lock.Lock()
defer te.lock.Unlock()
te.seenIDs = append(te.seenIDs, in.Challenge.ID)
return te.validateErr
}
func (te *testExtension) reset(validateErr error) {
te.lock.Lock()
defer te.lock.Unlock()
te.validateErr = validateErr
te.seenIDs = nil
}
func (te *testExtension) validatedIDs() []string {
te.lock.Lock()
defer te.lock.Unlock()
return append([]string(nil), te.seenIDs...)
}
var theTestExtension = &testExtension{}
func init() {
extension.Register("test-extension", theTestExtension)
}
func readChallengePageBody(t *testing.T, resp *http.Response) string {
t.Helper()
var body io.Reader = resp.Body
switch resp.Header.Get("Content-Encoding") {
case "gzip":
gz, err := gzip.NewReader(body)
if err != nil {
t.Fatalf("can't read gzipped response: %v", err)
}
defer gz.Close() //nolint:errcheck
body = gz
}
data, err := io.ReadAll(body)
if err != nil {
t.Fatalf("can't read challenge page: %v", err)
}
return string(data)
}
func authCookie(srv *Server, resp *http.Response) *http.Cookie {
name := srv.cookieName(anubis.CookieName)
for _, ckie := range resp.Cookies() {
if ckie.Name == name && ckie.Value != "" {
return ckie
}
}
return nil
}
func TestChallengeExtensionValidate(t *testing.T) {
for _, tt := range []struct {
name string
validateErr error
wantStatus int
wantCookie bool
}{
{
name: "accepted",
wantStatus: http.StatusFound,
wantCookie: true,
},
{
name: "refused with challenge error",
validateErr: challenge.NewError("validate", "browser failed", challenge.ErrFailed),
wantStatus: http.StatusForbidden,
},
{
name: "refused with plain error",
validateErr: errors.New("store is down"),
wantStatus: http.StatusInternalServerError,
},
} {
t.Run(tt.name, func(t *testing.T) {
theTestExtension.reset(tt.validateErr)
srv := spawnAnubis(t, Options{
Next: http.NewServeMux(),
Policy: loadPolicies(t, "./testdata/challenge-extension.yaml", 0),
})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
defer ts.Close()
cli := httpClient(t)
chall := makeChallenge(t, ts, cli)
resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
defer resp.Body.Close() //nolint:errcheck
if resp.StatusCode != tt.wantStatus {
t.Errorf("wanted status %d, got: %d", tt.wantStatus, resp.StatusCode)
}
if got := authCookie(srv, resp) != nil; got != tt.wantCookie {
t.Errorf("wanted auth cookie set: %v, got: %v", tt.wantCookie, got)
}
if got := theTestExtension.validatedIDs(); len(got) != 1 || got[0] != chall.ID {
t.Errorf("wanted extension to validate challenge %q once, got: %q", chall.ID, got)
}
})
}
}
func TestChallengeExtensionHeadIsRendered(t *testing.T) {
theTestExtension.reset(nil)
srv := spawnAnubis(t, Options{
Next: http.NewServeMux(),
Policy: loadPolicies(t, "./testdata/challenge-extension.yaml", 0),
})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
defer ts.Close()
cli := httpClient(t)
resp, err := cli.Get(ts.URL + "/")
if err != nil {
t.Fatalf("can't get challenge page: %v", err)
}
defer resp.Body.Close() //nolint:errcheck
body := readChallengePageBody(t, resp)
headMarker := strings.Index(body, testExtensionMarker)
if headMarker == -1 {
t.Fatalf("challenge page does not contain the extension head %q", testExtensionMarker)
}
// Extension scripts must run before the challenge script.
mainAt := strings.Index(body, "anubis-main")
if mainAt == -1 {
t.Fatal("challenge page does not contain the main script")
}
if headMarker > mainAt {
t.Error("extension head is rendered after the challenge script")
}
}
func TestChallengeKnownExtensionMakesPolicyLoad(t *testing.T) {
_, err := LoadPoliciesOrDefault(context.Background(), "./testdata/challenge-extension.yaml", 0, "info", false)
if err != nil {
t.Fatalf("unexpected config parsing failure: %v", err)
}
}
func TestChallengeExtensionUnknownFailsPolicyLoad(t *testing.T) {
_, err := LoadPoliciesOrDefault(context.Background(), "./testdata/challenge-extension-unknown.yaml", 0, "info", false)
if !errors.Is(err, ErrUnknownChallengeExtension) {
t.Fatalf("wanted %v, got: %v", ErrUnknownChallengeExtension, err)
}
}