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:   - 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:
1 parent
eb3e46d8d0
commit
caf4d72880
529 files changed
+33015
-6659
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
Executable
+64
@@ -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(`<a href="(https://[a-z-]{2,12}\.wikipedia\.org/wiki/[A-Za-z0-9_-]+)">(.*?)</a>`)
|
||||
|
||||
// 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
@@ -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 & 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: `<script>alert(1)</script>`,
|
||||
},
|
||||
{
|
||||
name: "javascript href",
|
||||
in: `<a href="javascript:alert(1)">x</a>`,
|
||||
want: `<a href="javascript:alert(1)">x</a>`,
|
||||
},
|
||||
{
|
||||
name: "attribute breakout",
|
||||
in: `<a href="https://en.wikipedia.org/wiki/X" onclick="alert(1)">x</a>`,
|
||||
want: `<a href="https://en.wikipedia.org/wiki/X" onclick="alert(1)">x</a>`,
|
||||
},
|
||||
{
|
||||
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"><img src=x onerror=alert(1)></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, "<a") || strings.Contains(out, "</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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)})();})();
|
||||
@@ -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(" ")
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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) {
|
||||
|
||||
Generated
+3
-3
@@ -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
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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>
|
||||
}
|
||||
Generated
+140
@@ -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
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user