+ );
+}
diff --git a/docs/blog/2026-09-06-anubis-wasm/diagrams/DifficultyVisualizer/styles.module.css b/docs/blog/2026-09-06-anubis-wasm/diagrams/DifficultyVisualizer/styles.module.css
new file mode 100644
index 0000000..69760fa
--- /dev/null
+++ b/docs/blog/2026-09-06-anubis-wasm/diagrams/DifficultyVisualizer/styles.module.css
@@ -0,0 +1,370 @@
+/* Theme tokens. Light values are the default, dark values override below. */
+.container {
+ --dv-surface: var(--ifm-background-surface-color);
+ --dv-raised: var(--ifm-color-emphasis-100);
+ --dv-sunken: var(--ifm-color-emphasis-200);
+ --dv-border: var(--ifm-color-emphasis-300);
+ --dv-muted: var(--ifm-color-emphasis-700);
+
+ --dv-hit-text: var(--ifm-color-primary-dark);
+ --dv-hit-border: var(--ifm-color-primary);
+ --dv-hit-bg: rgb(255 86 48 / 0.12);
+
+ --dv-ok-text: rgb(21 128 61);
+ --dv-ok-border: rgb(34 197 94);
+ --dv-ok-bg: rgb(34 197 94 / 0.12);
+
+ --dv-bad-text: rgb(185 28 28);
+ --dv-bad-border: rgb(239 68 68);
+ --dv-bad-bg: rgb(239 68 68 / 0.12);
+}
+
+[data-theme="dark"] .container {
+ --dv-hit-text: var(--ifm-color-primary-lighter);
+ --dv-hit-bg: rgb(255 86 48 / 0.18);
+
+ --dv-ok-text: rgb(74 222 128);
+ --dv-ok-bg: rgb(34 197 94 / 0.18);
+
+ --dv-bad-text: rgb(248 113 113);
+ --dv-bad-bg: rgb(239 68 68 / 0.18);
+}
+
+/* Main container styles */
+.container {
+ width: 100%;
+ max-width: 40rem;
+ margin: 1.5rem auto;
+ overflow: hidden;
+ color: var(--ifm-font-color-base);
+ background-color: var(--dv-raised);
+ border: 1px solid var(--dv-border);
+ border-radius: var(--ifm-global-radius);
+}
+
+/* Control panel styles */
+.controls {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ padding: 0.75rem;
+ border-bottom: 1px solid var(--dv-border);
+}
+
+.controlGroup {
+ flex: 1;
+ min-width: 0;
+}
+
+.label {
+ display: block;
+ font-size: 0.8125rem;
+ font-weight: 600;
+ margin-bottom: 0.375rem;
+}
+
+.labelRow {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.5rem;
+}
+
+.difficultyValue {
+ font-family: var(--ifm-font-family-monospace);
+ font-weight: 400;
+ padding: 0.125rem 0.375rem;
+ background-color: var(--dv-sunken);
+ border-radius: var(--ifm-global-radius);
+}
+
+/* Mode switch styles */
+.modeButtons {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.375rem;
+}
+
+.modeButton {
+ font: inherit;
+ font-size: 0.875rem;
+ font-weight: 600;
+ padding: 0.375rem 0.75rem;
+ color: var(--ifm-font-color-base);
+ background-color: var(--dv-sunken);
+ border: 1px solid transparent;
+ border-radius: var(--ifm-global-radius);
+ cursor: pointer;
+ transition:
+ background-color 200ms,
+ color 200ms;
+}
+
+.modeButton:hover {
+ background-color: var(--dv-border);
+}
+
+.modeButtonActiveHit,
+.modeButtonActiveHit:hover {
+ color: var(--ifm-button-color);
+ background-color: var(--ifm-color-primary);
+}
+
+.modeButtonActiveOk,
+.modeButtonActiveOk:hover {
+ color: var(--ifm-button-color);
+ background-color: rgb(21 128 61);
+}
+
+/* Difficulty slider styles */
+.slider {
+ display: block;
+ width: 100%;
+ accent-color: var(--ifm-color-primary);
+ cursor: pointer;
+}
+
+.hintRow {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 0.5rem;
+ margin-top: 0.25rem;
+}
+
+.hint {
+ font-size: 0.75rem;
+ font-family: var(--ifm-font-family-monospace);
+ color: var(--dv-muted);
+ margin-bottom: 0;
+}
+
+.warning {
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--ifm-color-warning-darkest);
+ margin-bottom: 0;
+ animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
+}
+
+[data-theme="dark"] .warning {
+ color: var(--ifm-color-warning);
+}
+
+/* Mining dashboard styles */
+.dashboard {
+ position: relative;
+ overflow: hidden;
+ padding: 0.75rem;
+}
+
+.successGlow {
+ position: absolute;
+ inset: 0;
+ background-color: var(--dv-ok-bg);
+ pointer-events: none;
+ animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
+}
+
+.statusRow {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.5rem;
+ margin-bottom: 0.75rem;
+}
+
+.nonce {
+ font-family: var(--ifm-font-family-monospace);
+ font-size: 0.8125rem;
+ color: var(--dv-muted);
+ padding: 0.375rem 0.625rem;
+ background-color: var(--dv-surface);
+ border: 1px solid var(--dv-border);
+ border-radius: var(--ifm-global-radius);
+}
+
+.nonceValue {
+ color: var(--ifm-font-color-base);
+ margin-left: 0.375rem;
+}
+
+.mineButton {
+ font: inherit;
+ font-size: 0.875rem;
+ font-weight: 700;
+ padding: 0.5rem 1rem;
+ color: var(--ifm-button-color);
+ background-color: var(--ifm-color-primary);
+ border: 1px solid transparent;
+ border-radius: var(--ifm-global-radius);
+ cursor: pointer;
+ transition: background-color 200ms;
+}
+
+.mineButton:hover {
+ background-color: var(--ifm-color-primary-dark);
+}
+
+.mineButtonMining,
+.mineButtonMining:hover {
+ color: var(--dv-bad-text);
+ background-color: var(--dv-bad-bg);
+ border-color: var(--dv-bad-border);
+}
+
+/* Hash display styles */
+.hashGrid {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ max-width: 32rem;
+ margin: 0 auto;
+}
+
+.chunk {
+ padding: 0.5rem;
+ background-color: var(--dv-surface);
+ border: 1px solid var(--dv-border);
+ border-radius: var(--ifm-global-radius);
+}
+
+.sectionLabel {
+ font-size: 0.6875rem;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--dv-muted);
+ margin-bottom: 0.25rem;
+}
+
+/* Both rows share one 16 column grid, and each hex cell spans four columns.
+ That puts every hex character directly above the four bits it encodes
+ without needing spacer elements. */
+.hexRow,
+.binRow {
+ display: grid;
+ grid-template-columns: repeat(16, minmax(0, 1fr));
+ gap: 2px;
+ font-family: var(--ifm-font-family-monospace);
+}
+
+.hexRow {
+ margin-bottom: 0.5rem;
+ font-size: 1.125rem;
+}
+
+.hexCell {
+ grid-column: span 4;
+ height: 2.25rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--dv-muted);
+ background-color: var(--dv-sunken);
+ border: 1px solid var(--dv-border);
+ border-radius: var(--ifm-global-radius);
+ transition: all 200ms;
+}
+
+.binRow {
+ font-size: 0.75rem;
+}
+
+.binCell {
+ height: 1.75rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--dv-muted);
+ background-color: var(--dv-sunken);
+ border-bottom: 2px solid var(--dv-border);
+ transition: all 200ms;
+}
+
+/* Cell highlight states */
+.cellHit {
+ color: var(--dv-hit-text);
+ background-color: var(--dv-hit-bg);
+ border-color: var(--dv-hit-border);
+}
+
+.cellOk {
+ color: var(--dv-ok-text);
+ background-color: var(--dv-ok-bg);
+ border-color: var(--dv-ok-border);
+}
+
+.cellBad {
+ color: var(--dv-bad-text);
+ background-color: var(--dv-bad-bg);
+ border-color: var(--dv-bad-border);
+}
+
+/* Glow animation */
+@keyframes pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+ 50% {
+ opacity: 0.5;
+ }
+}
+
+/* Responsive styles */
+@media (min-width: 768px) {
+ .controls {
+ flex-direction: row;
+ gap: 1rem;
+ }
+}
+
+/* Every nested padding costs the bit grid 16 columns worth of width, so trim
+ the padding and the type together on small screens. */
+@media (max-width: 480px) {
+ .controls,
+ .dashboard {
+ padding: 0.5rem;
+ }
+
+ .chunk {
+ padding: 0.375rem;
+ }
+
+ .hexRow {
+ font-size: 1rem;
+ }
+
+ .hexCell {
+ height: 2rem;
+ }
+
+ .binRow {
+ font-size: 0.625rem;
+ }
+
+ .binCell {
+ height: 1.5rem;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .warning,
+ .successGlow {
+ animation: none;
+ }
+
+ .modeButton,
+ .mineButton,
+ .hexCell,
+ .binCell {
+ transition: none;
+ }
+}
diff --git a/docs/blog/2026-09-06-anubis-wasm/index.mdx b/docs/blog/2026-09-06-anubis-wasm/index.mdx
new file mode 100644
index 0000000..059b062
--- /dev/null
+++ b/docs/blog/2026-09-06-anubis-wasm/index.mdx
@@ -0,0 +1,362 @@
+---
+slug: 2026/anubis-wasm
+title: It took a year to ship WebAssembly in Anubis
+authors: [xe]
+tags: [wasm, engineering]
+image: chrystarium.webp
+---
+
+
+
+After a year of work, hundreds of commits, 5 generations of pull requests, dozens of tests, rewriting part of Anubis in Rust, the first compiler bug of my career, and at least three times making my tower run out of ram I think I have finally done it. The next version of Anubis will ship with [WebAssembly-based proof of work checks](https://anubis.techaro.lol/docs/admin/configuration/challenges/wasm) that admins can enable in their thresholds or bot rules:
+
+{/* truncate */}
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: argon2id
+ difficulty: 6
+```
+
+This makes Anubis challenges use a [memory-hard](https://en.wikipedia.org/wiki/Memory-hard_function) proof of work function ([argon2id](https://en.wikipedia.org/wiki/Argon2)) instead of just a CPU hard one. It also means that the "hey Claude vibeslop me a CUDA Anubis solver" route is on its way to being fundamentally dead. Overall, this project taught me a lot of things about how WebAssembly works in practice, what the rough edges are when operating on the bleeding edge like I am, and led to the first genuine compiler bug of my career.
+
+Today I want to take you through the journey and process behind adding these WebAssembly based proof of work checks and all the problems that came up along the way.
+
+## Why use WebAssembly in the first place?
+
+The big impetus behind wanting to use WebAssembly in Anubis is that there's a constant tension that's underlined a lot of the performance work I've been doing: phone CPUs suck and trying to balance equitability to phone CPUs with trying to punish scraper CPUs is a huge challenge.
+
+:::note Aside
+
+To be clear: I am tackling the "Anubis makes my phone overheat" problem. It's hard to just lower the difficulty for phones without giving attackers enough information to lower the difficulty for scrapers. If you want to contribute performance data so that I can improve my classification process and/or target future development, please [get in touch with me](https://xeiaso.net/contact/). I want to make things better but can't without data. I am actively testing with a [Moto G8 Power](https://www.gsmarena.com/motorola_moto_g8_power-10052.php) alongside my normal testing steps.
+
+:::
+
+Using WebAssembly here means that the binary will run faster, which will make Anubis _go away_ faster, which is what we all want, right?
+
+### The same binary runs on both the client and the server
+
+One of the other big advantages of this setup is that it lets clients and servers run the same binary in order to solve and validate challenges. Note that I didn't say the same code, I said the same _binary_. This means that the client and server are in lockstep, much like the [CIC chip in the NES](). This also does mean that a bug in the shared code means that the client could send an invalid value that the server would accept as valid, but I don't think this is a practical concern until something like that happens.
+
+Right now the [`fast` challenge](https://anubis.techaro.lol/docs/admin/configuration/challenges/proof-of-work) has two implementations in Anubis: one [in JavaScript](https://github.com/TecharoHQ/anubis/blob/main/web/js/worker/sha256.ts) and the other [in Go](https://github.com/TecharoHQ/anubis/blob/main/lib/challenge/proofofwork/proofofwork.go). Updating it in one place means making the same updates in other places and also making sure that everywhere else that assumes how challenges work is also updated.
+
+:::note Aside
+
+Yeah, it's probably bad to have made those assumptions about how challenges work across the codebase. There's a lot of weird technical debt here that needs to be solved at some point. I expect that to be a fair bit of effort to untangle, it may end up with keeping the `fast` challenge only for tests when the WebAssembly based routes are working out well enough to make the default/only option.
+
+:::
+
+Making the same binary run on both the client and the server means that future experiments like per-client program synthesis can also proceed. I'll get more into that sometime in the future.
+
+### This lets us sneak Rust into Anubis
+
+Right now the core of Anubis is written in Go. Go's standard library HTTP server is surprisingly performant and is the key component of things like Google's HTTP frontend service. I have no intention to rewrite Anubis in Rust or anything as drastic as that.
+
+However breaking up Anubis from one monolithic binary into what amounts to a plugin loader is a lot more interesting from a maintenance standpoint. One of the main problems with Anubis is that the combination of rules I've set for myself (no CGo allowed and everything must cross compile to prod from my MacBook) means that updating any part of Anubis means recompiling all of Anubis across prod. Making Anubis be _able_ to have parts of it downloaded and swapped out at runtime is really interesting to me because it means being able to adapt to threats _as soon as the threat actors change behaviour_.
+
+Also I figured out pretty quickly that Rust builds some of the smallest WebAssembly binaries that run hilariously fast, so I wrote all the WebAssembly code in Rust (no-std, wasm32-unknown-unknown)\!
+
+### Finally fixing the challenge difficulty scaling issue
+
+Along the way this also lets me fix one of the bigger administrative problems with Anubis: challenges scale incorrectly with the `fast` challenge. Anubis uses string comparison to count the number of leading zero _nibbles_ in a hash instead of the number of leading zero _bits_. This means that adding one (1) to the difficulty of a challenge makes it 16 (sixteen) times as hard to solve in the worst case.
+
+Here's an interactive diagram to help you understand the difference in scaling at play:
+
+import DiffViz from "./diagrams/DifficultyVisualizer";
+
+
+
+This was a mistake in retrospect, but if we're changing details about how challenges work here then we may as well wrap up the fix into that.
+
+## How you normally add WebAssembly to something like this
+
+In a normal world you'd not have about half of the restrictions that I have when working with Anubis. Normally you just write your code, compile it to WebAssembly, and then make sure it runs on modern browsers. This is nice and simple. I wish I could live in this world.
+
+Comparatively, this is what it's like getting all of this working across browser versions, platforms, and so many other things:
+
+

+
+Anubis supports Chrome 75 and newer. I wanted to reduce the support range to not have to deal with Chrome that old (the feature difference between Chrome 155 and Chrome 75 is [absolutely massive](https://caniuse.com/?compare=chrome+75,chrome+155&compareCats=all)), but there are a lot of smartphones, smart TVs, and other electronic devices running Android out there that are just marooned on Chrome that old with _no path to upgrade it_. As a result, I gotta target Chrome 75 for features, but out of an abundance of caution and to make sure that things are generally compatible with browsers older than Chrome 75 (eg: old iOS releases), I target my JavaScript to Chrome 66 as an abundance of caution.
+
+I haven't been able to test with iOS or Android versions of the same vintage as Chrome 75, so a lot of this is aspirational backwards compatibility. I sure hope it's good enough\!
+
+### The host -> guest WASM ABI
+
+When you're doing this kind of work, you're effectively writing an operating system kernel that makes the WebAssembly guests run as processes. Any calls you pass to the WebAssembly guest are effectively system calls into the host. Normally I'd love to be able to reuse the [WebAssembly Component Model](https://component-model.bytecodealliance.org/introduction.html) so that a lot of the "hard part" is done for me. WebAssembly Components make you define your calls in packages that contain interfaces with functions in worlds.
+
+Here's an example of the kind of WebAssembly Interface Types world Anubis would need:
+
+```wit
+// theoretical/wit/proof-of-work.wit
+package techaro:anubis;
+
+interface update-ui {
+ // update the UI with the current nonce every 1024 iterations.
+ update-nonce: func(u32);
+}
+
+interface proof-of-work {
+ // possible ways the computation can go wrong.
+ enum error {
+ no-error,
+ input-too-big,
+ cant-find-solution,
+ computed-different-result,
+ }
+
+ // write up to 4096 bytes of challenge data to the challenge buffer,
+ // if the user tries to write more then throw an error.
+ write-data: func(data: list) -> result;
+
+ // read the generated result
+ read-result: func() -> list;
+
+ // write to the verification buffer, if the user tries to write more
+ // than the buffer supports throw an error.
+ write-verification: func(data: list) -> error;
+
+ // grind at the right hash in a loop and return the nonce that passes
+ // validation to send to the server.
+ anubis-work: func(difficulty: u32, initial-nonce: u32, difficulty: u32, iterand: u32) -> result;
+
+ // validate that running the proof of work function on the data buffer
+ // with the given nonce results in the same output that the client
+ // calculated.
+ anubis-validate: func(difficulty: u32, nonce: u32) -> result;
+}
+
+world anubis {
+ import update-ui;
+ export proof-of-work;
+}
+```
+
+If this worked (I wrote this all out in one go based on how the current handcrafted ABI works and have not tested it, sorry), this would describe the shape of the API that we need for doing the proof of work operations. At the time I wrote the API/ABI that Anubis uses, the main tool for generating the server-side bindings for WebAssembly Component Model stuff in Go [gravity](https://github.com/arcjet/gravity) didn't support passing records (structs) or bytestrings (`list` or `Vec` / `[]byte`) from the host to the guest. As such, I had to do it by hand.
+
+### API design
+
+So given that we can't do it the "right way", we have to do it the "bad way". Also given that no matter what I pick for this I'm going to be "wrong", I just decided to treat the WebAssembly modules as dynamic libraries that just happen to use WebAssembly as an implementation detail. There only needs to be three buffers that are read from / written to, so let's just focus around those:
+
+1. The data buffer: up to 4096 bytes of challenge data. This is 4096 bytes so that it can (hopefully) land in its own 4Ki machine page. This is the only variable-length buffer in the setup, so it needs two calls:
+ 1. `data_ptr() -> *const u8`: return the pointer to the data buffer in WASM linear memory. This is used as the base address for copying data into the guest.
+ 2. `set_data_length(len: u32)`: update the globally mutable "data length" variable to signal to the guest how much data was actually written into the data buffer. The combination of these two calls lets you treat that global data buffer as a slice.
+2. The result buffer: a challenge-defined buffer that usually has about 32 bytes of data. This is read out of the guest's linear memory when the challenge is done processing.
+ 1. `result_hash_ptr() -> *const u8`: return the pointer to the result buffer in WASM linear memory. This is used as the base address for reading out of the guest.
+ 2. `result_hash_size() -> usize`: return the length of the result buffer (a compile time constant based on the needs of the challenge, but the runtime can't know that).
+3. The verification buffer: a challenge-defined buffer that usually has about 32 bytes of data. This is written into when the server is validating a challenge.
+ 1. `verification_hash_ptr() -> *const u8`: return the pointer to the result buffer in WASM linear memory. This is used as the base address for reading out of the guest.
+ 2. `verification_hash_size() -> usize`: return the length of the result buffer (a compile time constant based on the needs of the challenge, but the runtime can't know that).
+
+Challenge modules also expose two entrypoints:
+
+1. `anubis_work`: the main entrypoint for browsers. Given the data loaded into the challenge buffer, hash it in a tight loop until you get a solution that matches the difficulty.
+2. `anubis_verify`: the main entrypoint for the server. Given the data loaded into the challenge and verification buffers, ensuring that one run through the hashing function produces a result that both meets the difficulty demands and exactly matches what the client sent.
+
+Challenge modules also import `anubis.anubis_update_nonce` from the environment so that they can periodically report their hash rate back to the frontend. This allows users to see a progress bar based on how long it should take to finish the process.
+
+This works enough for now. It'll be interesting to see how this falls short in the real world\!
+
+## The ride never ends
+
+Honestly, the first bit of this took a few days at most. Most of the hard work was making sure that pointers, offsets, and whatnot were all wired up correctly so that the browser worked the same way as the server. My experience building and messing around with [many](https://github.com/Xe/olin) [WebAssembly](https://github.com/Xe/pahi) [runtimes](https://xeiaso.net/talks/unix-philosophy-logical-extreme-wasm/) and [egregious hacks](https://xeiaso.net/talks/wazero-lightning-2023/) meant that making it was really easy for me.
+
+The devil came out in the details. Here are all the things that came up while I was working on this. All of these problems added up is the sole reason that this took a year instead of a week.
+
+### SIMD means speed in my dispatch
+
+Early on in development I found out that WebAssembly has a [SIMD extension](https://developer.mozilla.org/en-US/docs/WebAssembly/Reference/SIMD). SIMD stands for [Single Instruction Multiple Data](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) and is a family of instructions that let you do operations on multiple values at a time. This gives programmers data-level parallelism (this is distinct from multi-threading) so that things like hash calculations and MP3 decoding can be done faster than they would be if each operation had to be its own instruction.
+
+[CanIUse considers WebAssembly SIMD to be "baseline"](https://caniuse.com/wasm-simd) (supported by browsers newer than Chrome 91), but I have a lower version bound of Chrome 75\. However the benefits from SIMD on mobile devices are _so drastic_ that it's worth having two builds of the WebAssembly code: one with SIMD and one without it. In the browser it dispatches which version to use by using [wasm-feature-detect](https://www.npmjs.com/package/wasm-feature-detect) to probe WebAssembly functionality by trying to parse/run trivial minimal programs that exercise those features.
+
+Hopefully I don't need to add [an additional build](https://github.com/TecharoHQ/anubis/blob/4578023de7b631537e3a43d89b1998e802beb7e0/web/js/algorithms/wasm.ts#L58-L62) into this process, but there is nothing in the tooling that would prevent it\!
+
+### The birth and death of Yavascript
+
+One of the big things that blocked this shipping for so long was not having an escape hatch of some kind to allow clients that disable WebAssembly by policy to get through the gate. In my experience most clients don't have JavaScript enabled but WebAssembly disabled, however there are a few notable usecases that forced my hand: iOS [Lockdown mode](https://support.apple.com/en-us/105120) and GrapheneOS' [Vanadium](https://discuss.grapheneos.org/d/4196-webassembly-on-vanadium)'s default configuration. This combination of factors means that there would need to be another implementation of the proof of work code in JavaScript that would actually execute the number crunching.
+
+I don't want to make another implementation of the proof of work function (the entire point of this is to only have _one_ implementation\!) so while I was browsing around I came across the legendary talk [The Birth & Death of JavaScript](https://www.destroyallsoftware.com/talks/the-birth-and-death-of-javascript) and got a horrible idea. What if you just compiled the WebAssembly to JavaScript? Would that even work? It's "just" turning one Turing machine into another, right? How would it fare in practice?
+
+Turns out I'm not the first person to think about this\! The team behind [binaryen](https://github.com/WebAssembly/binaryen) have made this escape hatch in the form of [wasm2js](https://github.com/WebAssembly/binaryen/blob/main/src/tools/wasm2js.cpp) which takes WebAssembly binaries and produces moderately cromulent JavaScript in response. One of the main downsides is that the generated binaries tend to be rather large.
+
+For example consider this simple WebAssembly module that exposes a function that adds two numbers together:
+
+```
+(module
+ (func $add (param $lhs i32) (param $rhs i32) (result i32)
+ local.get $lhs
+ local.get $rhs
+ i32.add)
+ (export "add" (func $add))
+)
+```
+
+Seems simple enough, right? Here's the JavaScript that generates:
+
+```javascript
+function asmFunc(imports) {
+ var Math_imul = Math.imul;
+ var Math_fround = Math.fround;
+ var Math_abs = Math.abs;
+ var Math_clz32 = Math.clz32;
+ var Math_min = Math.min;
+ var Math_max = Math.max;
+ var Math_floor = Math.floor;
+ var Math_ceil = Math.ceil;
+ var Math_trunc = Math.trunc;
+ var Math_sqrt = Math.sqrt;
+ function $0($0_1, $1) {
+ $0_1 = $0_1 | 0;
+ $1 = $1 | 0;
+ return ($0_1 + $1) | 0 | 0;
+ }
+
+ return {
+ add: $0,
+ };
+}
+
+var retasmFunc = asmFunc({});
+export var add = retasmFunc.add;
+```
+
+As you can imagine, this only gets [progressively worse](https://anubis.techaro.lol/.within.website/x/cmd/anubis/static/js/worker/wasm2js.mjs) as you end up making the Rust standard library get compiled from WASM to JavaScript, and even worse when you actually get hashing functions into the mix. The end result is probably very optimized when you run it through a JIT, but given that this runs on an interpreter it's probably gonna be slow no matter what I do.
+
+Sorry\! I tried\!
+
+### How I found the first compiler bug in my career
+
+This ended up working fairly well in testing, but I tried building it in GitHub Actions and ran into an issue. I noticed that wasm2js was [packaged in Ubuntu](https://manpages.ubuntu.com/manpages/resolute/man1/wasm2js.1.html) and that the version in Fedora worked fine but the version in Ubuntu did not and threw an obscure error message about not understanding the tail call extension that Rust was using for some reason.
+
+I ended up bisecting versions of binaryen by downloading a tarball, building it from source, and then seeing if the result of running it on the Anubis WebAssembly modules worked in a browser. I ended up selecting Binaryen version 128, the newest version at the time. It was new enough that most of [the distributions that package Anubis](https://repology.org/project/anubis-anti-crawler/versions) don't have that version of Binaryen packaged.
+
+However I didn't want to make my life more complicated by having some kind of conditional compilation step that would effectively tell end users "sorry, the admin is using an unofficial build that just so happens to not support your browser, please complain to them" because they'll just end up complaining to me. In my experience the kinds of people who run this exact combination of circumstances also tend to be the kind of people that have a wide variance in the level of kindness they display to the authors of open source programs that happen to be in their way. So I needed an escape hatch that would _force_ build systems to use _the exact version_ that I use in my builds.
+
+Then inspiration hit me as if Apollo himself sniped me from the heavens. We're dealing with WebAssembly here right? What's stopping us from just compiling the WebAssembly to JS tool to WebAssembly with some kind of reproducible build, committing that blob to the repo, and then moving on with life?
+
+I ended up [finding a bug in LLVM](https://github.com/llvm/llvm-project/issues/204883) around how it was iterating over exception handling blocks by the compiler iterating over them in machine pointer order. As a result each build would drift by about 29 bytes per build:
+
+```diff
+ i32.load offset=4 ;; 28 02 04
+ i32.const 6 ;; 41 06
+ i32.ne ;; 47
+ br_if 0 ;; 0d 00
+- try_table (catch_all_ref 8) ;; 1f 40 01 03 08
++ try_table (catch_all_ref 4) ;; 1f 40 01 03 04
++ try_table (catch_all_ref 9) ;; 1f 40 01 03 09
+ local.get 2 ;; 20 02
+ i32.const 32 ;; 41 20
+ i32.add ;; 6a
+ local.set 3 ;; 21 03
+ local.get 2 ;; 20 02
+ i32.const 56 ;; 41 38
+ i32.add ;; 6a
+ local.get 1 ;; 20 01
+ i32.const 8 ;; 41 08
+ i32.add ;; 6a
+ call 17461 ;; 10 b5 88 81 80 00
+ local.set 4 ;; 21 04
+ end ;; 0b
+- try_table (catch_all_ref 4) ;; 1f 40 01 03 04
+ local.get 3 ;; 20 03
+ local.get 4 ;; 20 04
+```
+
+This is what lead me to write [I hate compilers](https://xeiaso.net/notes/2026/anubis-wasm-vendor-binary/) as a combination blogpost/cry for help which made me realize this was actually an LLVM bug. I didn't instantly lean towards it being an LLVM bug until I figured out that disabling ASLR (via `setarch --addr-no-randomize`) made the results consistent on the same host within the same boot.
+
+Honestly this is the first time in my career I've ever run into a compiler bug like this. When I do a lot of my work I usually work under the assumption that the compiler is bug-free and that my inputs are wrong somehow. As such, even thinking it could possibly be an LLVM bug was just outside of the realm of possibility for me.
+
+Once that LLVM bug got fixed and a new version of [wasi-sdk](https://github.com/WebAssembly/wasi-sdk) with that fix got released, I was off to the races, updated my build of wasm-opt/wasm2js, made my build scripts run it with [wasmtime](https://wasmtime.dev/) (alongside a wazero-based fallback process that would be slower, but did work enough) and everything worked out. Every time Anubis builds the WebAssembly in CI it uses the version of wasm-opt and wasm2js that ships in the repo to ensure that everything is as byte-for-byte deterministic as possible.
+
+Your build tools can't differ from my build tools if I ship you the build tools I use.
+
+### Okay, but will it work on Ukrainian Smart TVs?
+
+Then we get into the other big problem that made this difficult: browser testing. One of the most common failure modes of Anubis is that someone uses some browser that I don't test in CI and then things don't work with it. I'm tired of installing 50 different browsers on several machines to test things and I have gone through so many throwaway VMs that I'm sure it's reduced the lifetime of my SSD.
+
+:::note Aside
+
+Yes, I really have been testing Anubis by hand in god knows how many browsers. Why do you think it takes so long to tag new releases?
+
+:::
+
+I built a harness that I call "chromesweep" that lets me spawn many Googles Chrome (term c.f. Attorneys General, et.al) in their default configuration to try and hit a version of Anubis listening over HTTPS. Getting this far meant making a library of all of these browser versions. I've put that library up on Github at [TecharoHQ/gubal](https://github.com/TecharoHQ/gubal) in case it's useful for you.
+
+One of the other big problems I ran into while getting browser testing working was making sure that my Googles Chrome strictly stay within the bounds of my Kubernetes cluster's network. Chrome this old is actively radioactive and I want to treat it like the security threat it is. As such, I set up a strict [NetworkPolicy](https://kubernetes.io/docs/concepts/services-networking/network-policies/) to only allow it to access the Anubis instance under test and make DNS queries. I also wrap each Chrome pod in a microVM with [Kata containers](https://katacontainers.io/) as an additional layer of security.
+
+:::note Aside
+
+It honestly terrifies me to think that I am putting more effort into securing these Googles Chrome than [big AI companies are putting into securing their AI agent testing infrastructure](https://collusion.wiki/). It literally doesn't take much to put a big dent into securing things! The current state of our industry boggles the mind. All I want is for Techaro's [FelonyBench](https://www.felonybench.com/) score to remain at 0, is that too much to ask?
+
+:::
+
+I also rigged the browser testing infrastructure up to a single slash command in GitHub pull requests. Doing it makes my office very warm so I try to avoid doing it when possible. This works well enough that it lets me move on to the next stage and has already caught something that lead to building all the JavaScript with the `--chrome66` flag.
+
+
+
+I wonder if this is yet another case where making infrastructure for Anubis could result in that infrastructure alone being its own viable tech product. I run into a lot of those.
+
+### Yo dawg, heard you liked compiling
+
+In the process of doing that automated browser testing I found out that Chrome 75 had a weird error pop up when it tried to compile Anubis' WASM to native code:
+
+```
+CompileError: WebAssembly.compile(): Compiling function
+#4:\"_RINvMs0_NtNtNtNtCsdl5sGgnNXvY_3std3sys4sync4on...\" failed:
+expected table index 0, found 128 @+664
+```
+
+This also caused failures up to Chrome 100, so this signaled to me that something I was doing with my "strict MVP" build of Anubis' WASM wasn't in fact sticking to just the MVP features of WebAssembly. It turns out that the function referenced (probably somewhere in [std::sync::Once](https://doc.rust-lang.org/std/sync/struct.Once.html)? I probably should have traced it down to the exact bit) was in the standard library. This surprised me because I assumed that building Rust code with CPU features selected would apply that to everything, including the standard library, right?
+
+No, turns out that when you download the [`rust-std` component](https://rust-lang.github.io/rustup/concepts/components.html) in [rustup](https://rustup.rs/), that doesn't just download the standard library. To aid in cross compilation and I guess to avoid disk space waste, the Rust standard library is precompiled. This surprised me as Go typically has you recompile the standard library (and runtime for that matter) when doing normal builds and cross compilation.
+
+:::note Aside
+
+The actual issue here is that the stdlib function in question was compiled down to use [reference types](https://bytecodealliance.org/articles/reference-types-in-wasmtime), which made [`call_indirect`](https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-call-indirect-x-y) references get stored as a table index instead of what MVP WebAssembly would put there. Chrome tried to read a null byte, got not a null byte, and then understandably exploded.
+
+:::
+
+I looked into the process involved for rebuilding the standard library twice: once with only MVP wasm features enabled and once with an "all yes config" like usual. Based on [some research I did](https://wiki.osdev.org/Porting_Rust_standard_library) this seemed like a massive pain.
+
+However, I had gone through that effort to build reproducible WASI versions of wasm2js and wasm-opt. [wasm-opt](https://github.com/WebAssembly/binaryen#tools) is a tool that lets you take compiled WebAssembly modules, optimize them, and more importantly remove features from them so they can run in older browsers. After a bit of hacking to make sure that the tools were able to run properly, I set up a Claude Opus / GLM 5.2 loop to fuzz various wasm-opt flags and make sure Chrome 75 could parse the output. I ended up with these flags:
+
+```shell
+# Chrome shipped sign-ext and mutable-globals in 74, bulk-memory and
+# nontrapping-fptoint in 75, multivalue in 85 and simd in 91.
+baseline_features="-mvp --enable-sign-ext --enable-mutable-globals \
+--enable-bulk-memory --enable-nontrapping-float-to-int"
+simd128_features="${baseline_features} --enable-multivalue --enable-simd"
+```
+
+This strips away all the other WebAssembly features from the build like unwanted paint (the `-mvp` flag means "disable everything not in the original MVP definition of WebAssembly"). I think that it'd be safe-ish to enable reference types in the SIMD build (they were added before Chrome added SIMD), but it's not hurting anything to remove them so I'll just let cowardice win here. Either way, I threw the results into chromesweep and got a successful response, so win\! If/when this comes to bite me I'll try and improve it.
+
+## Things that probably need to be fixed at some point but I want to see what's on fire in practice first, you know?
+
+I'm pretty sure that this work isn't _perfect_, but at some point you gotta cut your losses, ship it, and then see where things fail to prioritize perfecting it. These issues include but are not limited to:
+
+- The wasm2js flow doesn't currently have a way to update the progress bar with its `update_nonce` import stubbed out. I have no idea how to properly wire that up with the constraints of my runtime, but I'm sure I can figure it out eventually.
+- The WebAssembly that's shipped with this flow is ridiculously performant. This may mean you need to adjust the difficulty to compensate for this. Oops\! Sorry\!
+- This is better on mobile phones, but I'm working on a mobile request classifier that will use a combination of IP address reputation, TLS fingerprinting, and other signals to determine if a request is from a phone and give it the appropriate amount of grace. This is hard. Please contact me if you have ideas on how to make my current prototype better.
+- I need some way to dynamically rotate out challenge programs at runtime instead of just at compile time when I work on Anubis. Eventually I hope to have this pull WebAssembly files and supporting bundles from OCI/Docker registries, but I need to do a lot more experimentation with this before I can conclude how good/bad of an idea this is.
+
+Overall though, I'm hopeful that most of the worst parts of this can be solved. It would be nice if I didn't have to work what amounts to two full time jobs.
+
+## Ad astra per aspera
+
+I'm pretty sure that this is stable enough to ship as off-by-default in Anubis v1.28.0: [Wuk Lamat](https://ffxiv.consolegameswiki.com/wiki/Wuk_Lamat). Based on the feedback I get from administrators and users, I'll enable it in the default configuration in Anubis v1.29.0.
+
+I hope this look into how Anubis is developed can give you ideas as to the scale and challenge involved. Making something like this is tireless and thankless work and it's really weird to see people talk about it in the same breath as Cloudflare or AWS' WAF.
+
+Have a good day all!
+
+:::note Aside
+
+AI was not used in the production of the prose of this article. I have my draft as [a Google Doc](https://docs.google.com/document/d/1n-KE0M3gvXXmkWVRy-stT0pWHrz0u0aApaOastqwNEM/edit?tab=t.cknmv81px79i#heading=h.bh5cic8vnftr) so you can see exactly where and when I typed every word myself. The only use of AI was Claude Opus to help me make the visual bit/nibble diagram.
+
+:::
diff --git a/docs/blog/2026-09-06-anubis-wasm/mental-gymnastics.webp b/docs/blog/2026-09-06-anubis-wasm/mental-gymnastics.webp
new file mode 100644
index 0000000..521a19b
Binary files /dev/null and b/docs/blog/2026-09-06-anubis-wasm/mental-gymnastics.webp differ
diff --git a/docs/docs/CHANGELOG.md b/docs/docs/CHANGELOG.md
index 4f234cf..81cb0de 100644
--- a/docs/docs/CHANGELOG.md
+++ b/docs/docs/CHANGELOG.md
@@ -13,6 +13,243 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
+## v1.28.2: Wuk Lamat Echo 2
+
+- Add Catalan (ca) localization.
+- Allow Renovate in git clients for github/gitlab api endpoint.
+- Bump minimum Go version to 1.27.3 in light of eMudhra (fixes CVE-2026-111943).
+
+### Fixed
+
+- Add `utils/cmd/botgenerate` for automatically updating crawler IP ranges. Also apply the updates.
+- Do not reject with `400 Bad Request` a request whose `Content-Type` is `multipart/form-data` but whose body is empty, including when the content length is unknown (`-1`, for example a chunked request). Reverse proxies that strip the body for auth subrequests (for example nginx' `auth_request`) still forward the original `Content-Type`, which made `prepareChallengeForm` fail and answer with a spurious 400.
+- Reject requests with no `User-Agent` header or an empty `User-Agent` header via `(data)/bots/spec-violations.yaml`.
+- Accept GeoIP2 ISP databases for ASN lookups and GeoLite2 City databases for country lookups.
+- Fix concurrent WASM challenge validation failures by instantiating transient modules anonymously, allowing the existing four-slot verifier concurrency limit to work as intended.
+
+## v1.28.1: Wuk Lamat Echo 1
+
+- Revert systemd isolation change that worked fine in testing but failed in prod.
+
+## v1.28.0: Wuk Lamat
+
+This release adds WebAssembly based proof of work checks to Anubis. They are documented in the [Proof of Work (WebAssembly)](https://anubis.techaro.lol/docs/admin/configuration/challenges/wasm) page. This uses Rust code compiled to WebAssembly to run proof of work code. When browsers support SIMD, the WASM will use hardware acceleration.
+
+When clients are configured to disable WebAssembly, Anubis falls back to a pure JavaScript implementation of the WebAssembly-based check logic. As clients that disable WebAssembly usually disable the JavaScript JIT (the thing that makes JavaScript fast), this makes checks slower.
+
+Additionally due to complicated facts and circumstances involving it being complicated to pass the messages from the wasm2js world back to JavaScript, the progress bar will not update while a wasm2js check is running. This is a known issue and will be fixed in a later release.
+
+The difficulty values for the WebAssembly based checks are going to be much greater than the equivalent difficulty values for the JavaScript based checks. Generally these count the number of leading _bits_ that much match instead of the number of leading _nibbles_ that must match. Here's a rough translation table:
+
+| `fast` difficulty | `argon2id` difficulty | `sha256` difficulty | `hashx` difficulty |
+| :---------------- | :-------------------- | :------------------ | :----------------- |
+| `4` | `4` | `16` | `15` |
+| `2` | `2` | `8` | `7` |
+| `6` | `6` | `24` | `20` |
+
+As I'm not certain this will work fine out of the box for a few edge cases, I have disabled these new challenge methods by default. I will enable the new methods by default in a future version after they have been sufficiently tested.
+
+- Use node.js for running wasm in CI.
+- Fix [GHSA-5gwm-367w-7fgj](https://github.com/TecharoHQ/anubis/security/advisories/GHSA-5gwm-367w-7fgj), which allowed attackers that control the PTR records for their IP addresses to bypass Anubis via setting multiple PTR records pointing to various search engines.
+- Replace Thoth with [GeoIP databases](./admin/geoip.mdx). GeoIP databases are configured in the `geoip` block.
+- Thoth functionality has been removed. `THOTH_URL`, `THOTH_TOKEN`, and `THOTH_INSECURE` are now deprecated environment variables that will log a warning upon startup.
+- ASN description values now use the Maxmind values instead of the values that Thoth returned. This may impact your fail2ban rules.
+- Native packages now create an `anubis` group and assign all Anubis instances permissions to `/var/lib/anubis`.
+- Fix the original-referer cookie not being affected by the `COOKIE_PREFIX` setting ([#1977](https://github.com/TecharoHQ/anubis/pull/1977))
+- Default to the simplified explanation to avoid people misinterpreting words. `USE_SIMPLIFIED_EXPLANATION` is now deprecated.
+- Add Portuguese (Portugal) (`pt-PT`) localization.
+- Add documentation for the [Headless Browser Detection](./admin/configuration/challenges/extensions/headless.mdx) extension and the [Soteria](./admin/configuration/challenges/) challenge methods exclusive to BotStopper.
+- Add DYNAMIC_COOKIE_SUFFIX setting for toggling the dynamically generated cookie suffix [#1992](https://github.com/TecharoHQ/anubis/pull/1992)
+- Retry a missing challenge verification cookie once per client before reporting that cookies are disabled, allowing browsers affected by transient cookie loss during navigation to recover without creating an infinite challenge loop ([#1916](https://github.com/TecharoHQ/anubis/issues/1916)).
+- Use a bundled version of `wasm2js` in order to make the WebAssembly proof of work checks run in non-wasm environments.
+- Make the bundled `wasm2js`/`wasm-opt` WebAssembly modules build reproducibly and fix the build on arm64.
+- Add the concept of [Challenge Extensions](./admin/configuration/challenges/extensions/index.mdx) and add the sample [css-load](./admin/configuration/challenges/extensions/css-load.mdx) extension.
+- Fix `npm run test:integration` so the Playwright suite can connect to browsers and Firefox can reach the test server again.
+- Add weighing rule for [Cloudflare Kitesurf](https://blog.cloudflare.com/kitesurf/). Kitesurf doesn't currently support Cookies, but it might in the future.
+- Improved Norwegian Nynorsk localization.
+- Stop clearing the authorization cookie when a challenged request did not send one. A subresource request that starts before the challenge is passed but finishes after it no longer deletes the cookie that `pass-challenge` just issued ([#1314](https://github.com/TecharoHQ/anubis/issues/1314)).
+- Fix proof of work worker spawning fallback logic to properly detect Content-Security-Policy failures and fall back to the older logic that fans out to one request per hardware core ([#1864](https://github.com/TecharoHQ/anubis/issues/1864)).
+- [Content-Security-Policy advice](./admin/configuration/content-security-policy.mdx) has been added to the documentation.
+- Passthru `Host` header as `X-Forwarded-Host` in Open Graph requests so backends can dispatch based on host.
+- Detect and block trivial attempts at [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting) as bots have been starting to use that to try and turn web applications or HTTP servers into open proxies.
+- Add [HyperAgent](https://github.com/hyperbrowserai/HyperAgent/issues/91) to the headless browsers block rule.
+- Fix Dutch localization typo in the "go home" link.
+- WASM challenges now share watchdog, CSP, and defer fixes from v1.27.0.
+- WASM challenge workers now report errors to the challenge page instead of failing silently.
+- Add prebuilt binaries for NetBSD on amd64 and arm64.
+- Fix WASM build scripts on macOS, which has ancient coreutils that lacks features present on GNU+Linux.
+- Consolidate the purejs and webcrypto workers into one sha256 browser worker to avoid code duplication.
+- Rename X-Real-Ip to X-Real-I**P** in challenge metadata.
+- Fix client-supplied `X-Anubis-*` header spoofing
+- Log "challenge accepted" at INFO level when challenge is accepted, providing challenge lifecycle observability at quieter log levels than DEBUG.
+- Fix `npm run test:integration` and the Playwright CI step, which were pinned to `playwright@1.61.1` while `go.mod`'s `mxschmitt/playwright-go` had already been bumped to a client expecting protocol 1.62.x, causing every Playwright-driven test to fail with a version mismatch.
+- Restore the original `Referer` header on the request forwarded to the target after a challenge is passed, so server-side logs and analytics no longer see the internal challenge page as the referrer. Add an opt-in `--preserve-referer-query-param` flag that also appends `utm_source`/`utm_medium` query parameters to the post-challenge redirect for client-side analytics tools (e.g. Plausible) that read query parameters instead of `document.referrer`, which cannot be corrected from the server side ([#1596](https://github.com/TecharoHQ/anubis/issues/1596)).
+- Clarify getChallenge failure response and cite related log entry.
+- Share redirect validation between challenge completion and subrequest authentication. Reject ambiguous URL forms before checking allowed domains.
+- Respond with the configured `DENY` status code instead of HTTP 500 when a challenged client is rejected for not advertising gzip support, and log that rejection at `INFO` instead of `ERROR`. The rejection is deliberate, so it no longer shows up in 5xx rates or as a server fault. The log message text is unchanged, but fail2ban filters that match on the `ERROR` level need updating ([#1009](https://github.com/TecharoHQ/anubis/issues/1009)).
+- Anubis now can use dynamic IP lists from providers like OpenAI or Google instead of static IP lists.
+
+### Small security fixes
+
+As part of a continuous security posture, the following issues were identified and remediated:
+
+- Challenge validation for WASM based checks could fail open when users pass specifically crafted invalid input.
+- WASM challenges may only have four in-flight validations at once per process, the rest will wait in line.
+- Challenge solutions are now strictly bound to the issuing rule.
+- Path policies now prevent path traversal bypasses in some edge cases.
+- Duplicate header values are now consistently handled across edge cases.
+- Forwarded URI paths are evaluated separately from query strings.
+- Disallow clients from sending their JA4H value by using the Set header verb instead of Add.
+- Avoid a panic when parsing IPv6 answers from DNSBL hits in edge cases.
+- Avoid caching negative hits from DNSBL servers.
+- CDNs and middleware are now instructed to NOT cache Anubis challenge, completion, forward-auth, and error pages.
+- When a dynamic IP list updates to a list that has no entries, keep using the previous entry instead of deleting all IP list contents from memory.
+- Reject short HS512 secrets.
+- Restrict honeypot log permissions.
+- Handle malformed client IP addresses safely.
+- Fix concurrent TLS SNI handling in edge cases.
+- DNSBL hits are now cached correctly, even when the result is no entry found.
+
+## v1.27.0: Moenbryda Wilfsunnwyn
+
+Anubis v1.27.0 adds Windows Server support, automatically renames cookies based on settings to avoid infinite challenge loops, adds two new localizations, and more.
+
+### Breaking change: cookie names are dynamically created based on cookie settings
+
+Anubis tries to avoid breaking changes as much as possible, but sometimes we have to make them for the sake of the users. This is technically a breaking change in something that is not part of the public API of Anubis; but some administrators rely heavily on cookie names in advanced configurations.
+
+It seems that browsers store cookies disambiguated with their options. This means you can have multiple cookies named the same but with different options. Browsers will send these cookies to the server without the list of options. This means that changing any cookie settings requires you to change `COOKIE_PREFIX`, creating a new "cookie epoch" that will set things properly.
+
+In order to be more robust, Anubis will automatically change cookie names based on the cookie settings. For example, the default configuration creates cookies named `techaro.lol-anubis-auth-347ddb4a`.
+
+Without this change, changing _any_ cookie setting without every client clearing their cookies causes challenges to become an infinite loop of thrashing, making it appear that Anubis "blocked" them.
+
+If this becomes onerous in practice for administrators of HAProxy and other advanced setups that rely on cookie names, we will add an escape hatch in the policy file.
+
+### Windows Server support (beta)
+
+Anubis now publishes `.msi` packages, allowing administrators to install and run Anubis on Windows Server. Please read the [Windows Server page](./admin/environments/windows.mdx) for more information.
+
+This support is beta-grade as the Anubis team does not have a lot of experience with developing software for Windows Server. Feedback is more than welcome.
+
+Please let us know how it works for you!
+
+### Pre-release docker images no longer populate the `latest` tag
+
+Due to a misconfiguration of the GitHub Action [docker/metadata-action](https://github.com/docker/metadata-action), pre-release Docker images previously populated the `:latest` tag. This means that administrators that expected the `:latest` tag to result in a stable release of Anubis got a prerelease version suddenly when they ran automatic updates.
+
+If administrators want to opt-in to the prerelease build track of Anubis for more frequent access to new features, they can use the `:pre` tag:
+
+```yaml
+image: ghcr.io/techarohq/anubis:pre
+```
+
+### Features
+
+- Allow importing bot policy rules [using wildcard matching](./admin/configuration/import.mdx#importing-many-files-at-once) ([#1815](https://github.com/TecharoHQ/anubis/issues/1815)).
+- Add support for JSON sources to iplist2rule ([#1833](https://github.com/TecharoHQ/anubis/pull/1833))
+- Make the honeypot feature log detected addresses to the disk every minute when `honeypot.ip_log_file` is set. See the [IP address logging](./admin/honeypot/overview.mdx#ip-address-logging) section for more information.
+- Add standard library rules for making Dillo less threatening to Anubis and [document how to enable them](./admin/faq.mdx#how-do-i-allow-small-internet-browsers-like-dillo-netsurf-and-pale-moon-to-bypass-anubis).
+
+#### Crawlers
+
+- Allow [Arquivo.pt](https://arquivo.pt), the Portuguese web archive, by default via its crawling network.
+- Add `(data)/bots/lyrenth.yaml` snippet that denies [Lyrenth](https://lyrenth.com/bot)'s `AIWebIndex` crawler and `AIWebIndex-Agent` on-demand fetcher by user agent and by their [published IP ranges](https://www.lyrenth.com/bot/ip-ranges.json). This is imported by `(data)/bots/_deny-pathological.yaml`.
+- Updates Alibaba cloud IP list ([#1813](https://github.com/TecharoHQ/anubis/pull/1813))
+- Updates Googlebot IP list ([#1812](https://github.com/TecharoHQ/anubis/pull/1812))
+- Updates IP list for DuckDuckBot ([#1810](https://github.com/TecharoHQ/anubis/pull/1810))
+- Update Huawei Cloud IP list ([#1814](https://github.com/TecharoHQ/anubis/pull/1814))
+
+### Fixes
+
+- Fix bot policy imports to not require pedantically correct YAML formatting when using wildcard matching.
+- JavaScript served by the `fast` challenge is loaded using [`defer`](https://www.w3schools.com/tags/att_script_defer.asp) instead of `async` ([#1782](https://github.com/TecharoHQ/anubis/issues/1782)).
+- Amend default [Lightpanda](https://lightpanda.io/) rule to match current behaviour, add smoke test to ensure it keeps working ([#1822](https://github.com/TecharoHQ/anubis/issues/1822)).
+- Fix a panic when a request asks for the undetermined language tag, such as `Accept-Language: und` ([#1776](https://github.com/TecharoHQ/anubis/issues/1776)).
+- Allow user agents that start with capital-G `Git` in `(data)/clients/git.yaml`.
+- Enabled the Partitioned flag on cookies by default ([#1701](https://github.com/TecharoHQ/anubis/issues/1701)).
+- Fix Windows MSI builds on prerelease tags such as `v1.27.0-pre1`.
+- Bump AI-robots.txt to version 1.47.
+
+### i18n
+
+- Add Basque (eu) localization.
+- Update Bulgarian locale ([#1708](https://github.com/TecharoHQ/anubis/pull/1708))
+- Add Croatian (hr) localization.
+
+## v1.26.2: Papalymo Totolymo: Echo 2
+
+- Automatically verify correct parsing of everything in `(data)`. While doing post-release checks on v1.26.1, I discovered that I incorrectly merged `(data)/services/updown.yaml` in such a way that it became syntactically invalid. This has been mended and multiple layers of CI have been put into place to make sure that `(data)` entries are syntactically and semantically valid.
+
+## v1.26.1: Papalymo Totolymo: Echo 1
+
+- Fix support for semicolon-delimited query parameters that was dropped when moving from [net/http/httputil#ReverseProxy](https://pkg.go.dev/net/http/httputil#ReverseProxy).Director (deprecated) to net/http/httputil#ReverseProxy.Rewrite. This re-enables support for upstreams like gitweb ([#1763](https://github.com/TecharoHQ/anubis/issues/1763)). A functional test has been added to ensure this does not repeat.
+
+### Challenge page robustness
+
+The challenge page can now survive transient failures, reduces the number of requests it makes to the Anubis app, and adds exponential backoff with retries to counteract an overwhelmed server being unable to serve any assets.
+
+Previously if any request for JavaScript assets failed, the entire challenge attempt failed and users were forced to manually refresh the page, which is a bit of a bad user experience. This was made worse when the load balancer does not support HTTP/2, did not have resumable sessions enabled, and was implemented with Apache httpd pre-fork; making each asset fetch do its own TCP/TLS handshake. Under periods of heavy load such that TCP/TLS handshakes timed out, this made Anubis unable to fetch assets consistently or even made in-progress challenge attempts fail, which made challenges impossible to pass.
+
+This has been fixed in a few ways:
+
+- Fetch operations now retry with [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) in hopes that they will eventually be able to get through when the server is less stressed.
+- Attempting to fetch the `main.mjs` script now has fallback watchdog logic that periodically re-attempts to load the script.
+- Worker source code is fetched _once_ and then loaded into workers with a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) instead of having each worker do an independent fetch of the worker source code.
+- Individual workers can now die without making the entire challenge attempt fail. Surviving workers will cover the rest of the nonce space.
+- When worker construction fails, already running proof of work workers are terminated instead of staying active as headless unmonitored infinite loops.
+- Proof of work failures are now exposed as untranslated real errors. Browsers signal script load failures with real Events so the challenge failure page now shows a useful message.
+
+## v1.26.0: Papalymo Totolymo
+
+- Add option to [disable the honeypot](./admin/policies.mdx#honeypot-configuration).
+- Add `(data)/clients/google-user-triggered-fetchers.yaml` snippet that allows Google-owned user-triggered fetchers (Google Translate's website translation proxy, Google Read Aloud, Google Messages link previews) by their [published IP ranges](https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers-google.json), fixing the infinite challenge loop for visitors using Google Translate ([#444](https://github.com/TecharoHQ/anubis/issues/444))
+- Update QwantBot remote addresses range with latest value
+- Migrate check-spelling workflow config to [cspell](https://cspell.org/)
+- Add [Anubis Kubernetes Operator](https://github.com/eznix86/anubis-kubernetes-operator/) to the docs ([#1675](https://github.com/TecharoHQ/anubis/pull/1675)).
+- Bump Playwright browser tooling to 1.61.1 and playwright-go to v0.6100.0.
+- Add FreeBSD/Windows binaries to the yeetfile.
+- Add systemd system extensions to the yeetfile.
+- Set an explicit esbuild `--target=chrome66` so modern syntax (e.g. optional chaining) is transpiled down. This lowers the minimum supported browser from Chrome 80 to Chrome 66.
+- Patch [GHSA-6wcg-mqvh-fcvg](https://github.com/TecharoHQ/anubis/security/advisories/GHSA-6wcg-mqvh-fcvg) by containing subrequest logic to Anubis instances in subrequest mode.
+- Implement robot9001 style delays on the honeypot feature so that the first hit takes 1 millisecond, the second takes 2, etc.
+- Move metrics server configuration to [the policy file](./admin/policies.mdx#metrics-server).
+- Expose [pprof endpoints](https://pkg.go.dev/net/http/pprof) on the metrics listener to enable profiling Anubis in production.
+- fix: prevent nil pointer panic in challenge validation when threshold rules match during PassChallenge (#1463)
+- Instruct reverse proxies to not cache error pages.
+- Fixed mixed tab/space indentation in Caddy documentation code block
+- Improve error messages and fix broken REDIRECT_DOMAINS link in docs ([#1193](https://github.com/TecharoHQ/anubis/issues/1193))
+- Add Bulgarian locale ([#1394](https://github.com/TecharoHQ/anubis/pull/1394))
+- Fixed case-sensitivity mismatch in geoipchecker.go
+- Use [Go's native version stamping](https://michael.stapelberg.ch/posts/2026-04-05-stamp-it-all-programs-must-report-their-version/) instead of a handrolled variant.
+- Fix CEL internal errors when iterating `headers`/`query` map wrappers by implementing map iterators for `HTTPHeaders` and `URLValues` ([#1465](https://github.com/TecharoHQ/anubis/pull/1465)).
+- Enable [metrics serving via TLS](./admin/policies.mdx#tls), including [mutual TLS (mTLS)](./admin/policies.mdx#mtls).
+- Enable [HTTP basic auth](./admin/policies.mdx#http-basic-authentication) for the metrics server.
+- Fix a bug in the dataset poisoning maze that could allow denial of service [#1580](https://github.com/TecharoHQ/anubis/issues/1580).
+- Add config option to add ASN to logs/metrics.
+- Log weight when issuing challenge.
+- Block x.ai's crawler for code review training.
+- Gate pprof endpoints behind `metrics.debug` in the policy file.
+- Limit naive honeypot r9k delay to one second.
+- Fix an obscure case where adding query values to a subrequest match could cause an invalid rule match when using path based matching for protected resources.
+- Anubis now requires Go 1.26 to build.
+- Fix an edge case where load average expression values could nil pointer dereference when Anubis just started up.
+- Fix an obscure case where Anubis in subrequest mode could allow redirects to invalid domains with strange instructions.
+- Fix `path_regex` and CEL `path` rules not matching when using Traefik `forwardAuth` middleware. Anubis now checks `X-Forwarded-Uri` (Traefik) in addition to `X-Original-URI` (nginx) when resolving the request path in subrequest mode ([#1628](https://github.com/TecharoHQ/anubis/issues/1628)).
+- Validate bounds in the CEL `randInt` helper so non-positive or platform-overflowing arguments surface a typed CEL error instead of an evaluator panic.
+- Fix a race in the bbolt store where the asynchronous cleanup scheduled by an expired read could delete a value that had just been refreshed; the delete now only fires when the key still carries the same expired generation it observed.
+- Marginally increase the performances of requests processing
+- Marginally improve the performances of PoW validation
+- Marginally improve the performances of challenges generation/display
+- Significantly improve the performances of the gzip middleware
+- Significantly improve the performances of the PoW validation
+- Add trimpath option to artifact builds
+- Add COOKIE_HTTP_ONLY option to set the HttpOnly flag on Anubis cookies
+- Improve the performances of rules validation
+- Only compute the JA4H fingerprint when a policy references the `X-Http-Fingerprint-JA4H` header, taking it off the hot path for configurations that don't use it ([#834](https://github.com/TecharoHQ/anubis/pull/834)).
+- Migrate the target reverse proxy off the deprecated `httputil.ReverseProxy.Director` to `Rewrite` for Go 1.26 compatibility, preserving the inbound `Host` and `X-Forwarded-*`/`Forwarded` headers.
+- The bbolt storage backend no longer writes its freelist to disk on every commit and now uses the faster hashmap freelist. This can significantly reduce write overhead with the tradeoff that the freelist needs to be rebuilt in memory on a database open. Change works with existing databases.
+
## v1.25.0: Necron
Hey all,
@@ -406,7 +643,7 @@ Anubis now is able to store things persistently [in memory](./admin/policies.mdx
Anubis now supports localized responses. Locales can be added in [lib/localization/locales/](https://github.com/TecharoHQ/anubis/tree/main/lib/localization/locales). This release includes support for the following languages:
-- [Brazilian Portugese](https://github.com/TecharoHQ/anubis/pull/726)
+- [Brazilian Portuguese](https://github.com/TecharoHQ/anubis/pull/726)
- [Chinese (Simplified)](https://github.com/TecharoHQ/anubis/pull/774)
- [Chinese (Traditional)](https://github.com/TecharoHQ/anubis/pull/759)
- English
@@ -878,7 +1115,7 @@ Livia sas Junius: Echo 2
Livia sas Junius: Echo 1
-- Set the `X-Real-Ip` header based on the contents of `X-Forwarded-For`
+- Set the `X-Real-IP` header based on the contents of `X-Forwarded-For`
[#62](https://github.com/TecharoHQ/anubis/issues/62)
## v1.14.0
diff --git a/docs/docs/admin/botstopper.mdx b/docs/docs/admin/botstopper.mdx
index 1839ba5..6c8296d 100644
--- a/docs/docs/admin/botstopper.mdx
+++ b/docs/docs/admin/botstopper.mdx
@@ -13,7 +13,6 @@ If you want to use Anubis but organizational policies prevent you from using the
In the near future this will expand to:
- A private challenge implementation that does advanced fingerprinting to check if the client is a genuine browser or not
-- Advanced fingerprinting via [Thoth-based advanced checks](./thoth.mdx)
In order to sign up for BotStopper, please do one of the following:
diff --git a/docs/docs/admin/caveats-gitea-forgejo.mdx b/docs/docs/admin/caveats-gitea-forgejo.mdx
index 6569a7a..3b1b3f9 100644
--- a/docs/docs/admin/caveats-gitea-forgejo.mdx
+++ b/docs/docs/admin/caveats-gitea-forgejo.mdx
@@ -2,7 +2,7 @@
title: When using Caddy with Gitea/Forgejo
---
-Gitea/Forgejo relies on the reverse proxy setting the `X-Real-Ip` header. Caddy does not do this out of the gate. Modify your Caddyfile like this:
+Gitea/Forgejo relies on the reverse proxy setting the `X-Real-IP` header. Caddy does not do this out of the gate. Modify your Caddyfile like this:
```python
ellenjoe.int.within.lgbt {
@@ -12,7 +12,7 @@ ellenjoe.int.within.lgbt {
# diff-add
reverse_proxy http://localhost:3000 {
# diff-add
- header_up X-Real-Ip {remote_host}
+ header_up X-Real-IP {remote_host}
# diff-add
}
# ...
diff --git a/docs/docs/admin/configuration/challenges/extensions/_category_.json b/docs/docs/admin/configuration/challenges/extensions/_category_.json
new file mode 100644
index 0000000..539af9e
--- /dev/null
+++ b/docs/docs/admin/configuration/challenges/extensions/_category_.json
@@ -0,0 +1,5 @@
+{
+ "label": "Challenge Extensions",
+ "position": 10,
+ "link": null
+}
\ No newline at end of file
diff --git a/docs/docs/admin/configuration/challenges/extensions/css-load.mdx b/docs/docs/admin/configuration/challenges/extensions/css-load.mdx
new file mode 100644
index 0000000..d50eb43
--- /dev/null
+++ b/docs/docs/admin/configuration/challenges/extensions/css-load.mdx
@@ -0,0 +1,23 @@
+# CSS Loading
+
+This extension asserts that a client is able to load CSS from the server. It works by sending instructions to import a test route and then ensures that the client actually hits that route.
+
+## Configuration
+
+Add it to an `extensions` block in an existing `challenge` definition:
+
+```yaml
+thresholds:
+ - name: mild-suspicion
+ expression:
+ all:
+ - weight > 0
+ - weight < 10
+ action: CHALLENGE
+ challenge:
+ algorithm: sha256
+ difficulty: 8
+ report_as: 8
+ extensions:
+ - css-load
+```
diff --git a/docs/docs/admin/configuration/challenges/extensions/headless.mdx b/docs/docs/admin/configuration/challenges/extensions/headless.mdx
new file mode 100644
index 0000000..e78d053
--- /dev/null
+++ b/docs/docs/admin/configuration/challenges/extensions/headless.mdx
@@ -0,0 +1,91 @@
+---
+title: Headless Browser Detection
+---
+
+import EnterpriseOnly from "@site/src/components/EnterpriseOnly";
+
+
+
+BotStopper can run basic headless browser detection on challenge pages. This detector is a small proprietary bit of code that examines browsers for signs of automation tooling. Before the client submits a challenge, the detector sends a report to BotStopper. This report is used in a few ways:
+
+- If the report contains any hard signals, the challenge fails no matter what the browser submitted. This catches many careless implementations of browser automation tooling.
+- If any component request for any part of the detector module contains unexpected changes (IE: User-Agent strings changing mid detection), the challenge fails.
+
+## Enabling the extension
+
+To enable headless browser detection, add `headless` to the `extensions` list of a challenge:
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: sha256
+ difficulty: 16
+ extensions:
+ - headless
+```
+
+:::note
+
+This detection process requires the execution of JavaScript and WebAssembly in user browsers. There is currently no way to mitigate this requirement and a no-JS mode for this detector is not currently planned. Please adjust your deployment expectations around this fact.
+
+:::
+
+## Caveats to keep in mind
+
+This challenge extension relies on many _subtle_ behaviors of browser behaviour. You **MUST** keep these caveats in mind when deploying this extension:
+
+- Your site **MUST** be served over HTTPS. All of the component assets for this extension are precompressed with [Brotli](https://developer.mozilla.org/en-US/docs/Glossary/Brotli_compression). Browsers do not accept plaintext server responses that are compressed with Brotli.
+- Your reverse proxy or CDN **MUST** send all the headers that clients sent **unaltered**, including but not limited to the `User-Agent` string, client hints headers, and any `Accept-*` headers.
+- If BotStopper sees any discrepancies between what it expects to see from browsers and what browsers actually return, the challenge will fail.
+- The detector adds about 35Ki to challenge pages served to browsers.
+- The detector uses the `eval` JavaScript function. If your `Content-Security-Policy` header on the challenge page blocks `unsafe-eval`, none of the detection probes will work.
+
+## CEL variables
+
+This extension exposes an expression variable:
+
+| Name | Type | Description |
+| :--------------------------- | :---- | :------------------------------------------------------------------ |
+| `headlessNetworkHardReports` | int32 | The stored hard reports for the network associated with the client. |
+
+### `headlessNetworkHardReports`
+
+As headless browsers fail checks, the IPv4/IPv6 minimum routable prefix associated with that failure is stored in BotStopper's store. This can be used to give clients from those networks more difficult challenges as a deterrence method. For example:
+
+```yaml
+bots:
+ - name: headless-network
+ action: CHALLENGE
+ expression: headlessNetworkHardReports >= 3
+ challenge:
+ algorithm: soteria # A difficult challenge for most hardware
+ difficulty: 20
+```
+
+Headless network hard reports will expire after 24 hours by default. This may be configured with the headless extension flags.
+
+## Flags
+
+| Flag / environment variable | Default | Value |
+| :------------------------------------------------ | :------ | :---------------------------------------------------------------------- |
+| `--headless-network-ttl` / `HEADLESS_NETWORK_TTL` | `24h` | The time that BotStopper keeps the count of hard reports for a network. |
+
+This will be replaced with a configuration file value in the near future.
+
+## Metrics
+
+This extension exposes metrics that may be useful for internal dashboards:
+
+- `botstopper_headless_reports_total{result}`: The number of reports for each result, broken down by reason.
+- `botstopper_headless_signal_hits_total{signal}`: The number of hits for each signal.
+- `botstopper_headless_refusals_total{reason}`: The number of challenges that failed because of the detector by reason (such as `missing`, `assets`, `hard`, and `error`).
+
+## Methodology flaws
+
+Headless browsers are constantly evolving to evade these kinds of checks. This will need to become a dynamically updating component of BotStopper. Additionally, many of the checks involved with this are sent by the client as there is no way for the server to determine these values without getting them from the client. Clients may lie.
diff --git a/docs/docs/admin/configuration/challenges/extensions/index.mdx b/docs/docs/admin/configuration/challenges/extensions/index.mdx
new file mode 100644
index 0000000..e3f22f8
--- /dev/null
+++ b/docs/docs/admin/configuration/challenges/extensions/index.mdx
@@ -0,0 +1,28 @@
+---
+title: Challenge Extensions
+position: 0
+---
+
+Challenge Extensions are extra conditions you can layer on top of existing challenges. This allows Anubis to assert more behaviour from clients without having to modify existing challenge implementations.
+
+To enable extensions on an existing challenge, add it to the `extensions` field under your challenge definition:
+
+```yaml
+thresholds:
+ - name: mild-suspicion
+ expression:
+ all:
+ - weight > 0
+ - weight < 10
+ action: CHALLENGE
+ challenge:
+ algorithm: sha256
+ difficulty: 8
+ report_as: 8
+ extensions:
+ - css-load
+```
+
+This will augment the [sha256 challenge](../wasm.mdx#sha256) with the [`css-load`](./css-load.mdx) extension.
+
+Extensions are designed to be very cheap and easy to add to existing challenges and can be useful for evading bypass/detection logic for Anubis solving scripts.
diff --git a/docs/docs/admin/configuration/challenges/soteria.mdx b/docs/docs/admin/configuration/challenges/soteria.mdx
new file mode 100644
index 0000000..e4fccf3
--- /dev/null
+++ b/docs/docs/admin/configuration/challenges/soteria.mdx
@@ -0,0 +1,73 @@
+# Soteria (WebAssembly, SIMD)
+
+import EnterpriseOnly from "@site/src/components/EnterpriseOnly";
+
+
+
+[Soteria](https://github.com/Xe/soteria) is an experimental dynamic challenge implementation abusing SIMD instructions in WebAssembly to run four challenge programs at once. All challenge programs are synthesized on the fly akin to RandomX, but re-synthesizes the challenge program every so often to be more forgiving to less powerful hardware. Clients that do not have WebAssembly support or support for WebAssembly SIMD operations cannot run this challenge method. Please take this into consideration when planning your deployment.
+
+As an additional bit of grace granted to less powerful hardware, Soteria cuts the challenge difficulty and complexity when the client is explicitly a mobile phone.
+
+## Configuration
+
+Soteria scales exponentially based on the difficulty configured in the policy file. Here are examples for light, medium, and hard challenges:
+
+### Light challenge
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: soteria
+ difficulty: 14
+ extensions:
+ - headless
+```
+
+### Moderate challenge
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: soteria
+ difficulty: 17
+ extensions:
+ - headless
+```
+
+### Hard challenge
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: soteria
+ difficulty: 20
+ extensions:
+ - headless
+```
+
+## Technical notes
+
+An upcoming blogpost will go into detail about how Soteria works in detail, but here are the highlights:
+
+- Soteria VM operations are run against four copies of synthesized challenge programs at once using SIMD operations to eke all performance out of mobile phone hardware possible.
+- The Soteria VM is based on a [Very Long Instruction Word](https://en.wikipedia.org/wiki/Very_long_instruction_word) architecture, enabling optimizations specific to that instruction set type.
+- As clients calculate four programs at once, they are required to submit four solutions which are chained in order to prevent challenge program reuse.
+- Requests classified as being from mobile phones have the difficulty and solution complexity cut drastically in order to be equitable to them. Soteria's architecture should be amenable to phones already, but this additional bit of grace will help make sure of it.
diff --git a/docs/docs/admin/configuration/challenges/wasm.mdx b/docs/docs/admin/configuration/challenges/wasm.mdx
new file mode 100644
index 0000000..3fb5785
--- /dev/null
+++ b/docs/docs/admin/configuration/challenges/wasm.mdx
@@ -0,0 +1,94 @@
+# Proof of Work (WebAssembly)
+
+Anubis supports using [WebAssembly](https://en.wikipedia.org/wiki/WebAssembly) to speed up proof of work validation. Proof of work functions as a randomized delay to prevent clients from overwhelming your server with traffic. All WebAssembly proof of work functions are written in Rust.
+
+:::note
+
+When clients are configured to disable WebAssembly, Anubis falls back to a pure JavaScript implementation of the WebAssembly-based check logic. As clients that disable WebAssembly usually disable the JavaScript JIT (the thing that makes JavaScript fast), this makes checks slower.
+
+Additionally due to complicated facts and circumstances involving it being complicated to pass the messages from the wasm2js world back to JavaScript, the progress bar will not update while a wasm2js check is running. This is a known issue and will be fixed in a later release.
+
+:::
+
+## Implementations
+
+Anubis offers the following WebAssembly proof of work functions:
+
+- [argon2id](#argon2id) (via the [`argon2id`](https://docs.rs/argon2/latest/argon2/) crate)
+- [hashx](#hashx) (via the [`hashx`](https://docs.rs/hashx/latest/hashx/index.html) crate)
+- [sha256](#sha256) (via the [`sha2`](https://docs.rs/sha2/latest/sha2/) crate)
+
+:::note
+
+The difficulty values for the WebAssembly based checks are going to be much greater than the equivalent difficulty values for the [JavaScript based checks](./proof-of-work.mdx). Generally these count the number of leading _bits_ that much match instead of the number of leading _nibbles_ that must match. Here's a rough translation table:
+
+| `fast` difficulty | `argon2id` difficulty | `sha256` difficulty | `hashx` difficulty |
+| :---------------- | :-------------------- | :------------------ | :----------------- |
+| `4` | `4` | `16` | `15` |
+| `2` | `2` | `8` | `7` |
+| `6` | `6` | `24` | `20` |
+
+:::
+
+## `argon2id`
+
+Uses the memory-hard [Argon2](https://en.wikipedia.org/wiki/Argon2) key derivation function as a hashing algorithm. This uses a large fixed-size memory region in order to make brute-force attacks computationally expensive.
+
+Usage:
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: argon2id
+ difficulty: 6
+```
+
+## `hashx`
+
+Uses the ASIC-resistant [hashx](https://github.com/tevador/hashx) as the proof of work function. This is resistant to GPU and ASIC attacks. In practice this means that users need to be using a standards-compliant browser to pass the challenge.
+
+Usage:
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: hashx
+ difficulty: 16
+```
+
+## `sha256`
+
+Uses [SHA-256](https://en.wikipedia.org/wiki/SHA-2) as the proof of work function.
+
+:::note
+
+This is included mostly as a fallback for usecases that specifically require this hashing function. There are known tools that solve this particular challenge. Prefer [`argon2id`](#argon2id) or [`hashx`](#hashx) unless you know what you are doing and have a very specific usecase in mind.
+
+:::
+
+Usage:
+
+```yaml
+thresholds:
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ algorithm: sha256
+ difficulty: 16
+```
diff --git a/docs/docs/admin/configuration/content-security-policy.mdx b/docs/docs/admin/configuration/content-security-policy.mdx
new file mode 100644
index 0000000..9968e5a
--- /dev/null
+++ b/docs/docs/admin/configuration/content-security-policy.mdx
@@ -0,0 +1,42 @@
+# Content-Security-Policy advice
+
+Many web server configuration guides recommend setting a strict [Content-Security-Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) on your web applications in order to avoid [Cross-Site-Scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) from being able to affect your services. The way Anubis works can conflict with some common CSP settings that many guides and web applications enforce out of the gate.
+
+:::warning
+
+Browsers cache the contents of `Content-Security-Policy` headers for a very long time. Please be sure to test any of these changes on staging domains before deploying changes to production.
+
+:::
+
+The most strict yet correct CSP for Anubis looks like this (reformatted for readability):
+
+```text
+default-src 'none';
+script-src 'self' 'unsafe-inline';
+style-src 'self' 'unsafe-inline';
+img-src 'self';
+font-src 'self' data:;
+connect-src 'self';
+worker-src 'self' blob:;
+base-uri 'none';
+form-action 'self';
+```
+
+This is an overly strict CSP and you **will** need to edit this as it **will** interfere with the normal operation of many web applications, especially ones that include resources from remote destinations to function (EG: the image CDN for a social media network).
+
+Breaking it down:
+
+| Setting | Justification |
+| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `default-src 'none'` | Blocks every kind of subresource load unless specified below. This denies by default. This setting alone is likely to break web applications. |
+| `script-src 'self'` | Anubis checks that load JavaScript from the server via the `
+```
+
+Any hits that match the URL `^/.within.website/x/cmd/anubis/api/honeypot/.*` are _malicious_ and should be blocked. A spec-compliant HTML parser will not parse this link, so any parser that does and visits it is categorically in the wrong.
+
## Plans
Future versions of this feature will allow for more customization. In the near future this will be configurable via the following mechanisms:
@@ -37,4 +53,25 @@ Right now Anubis assigns 30 weight points if the following criteria are met:
- A client's User-Agent has been observed in the dataset poisoning maze at least 25 times.
- The network-clamped IP address (/24 for IPv4 and /48 for IPv6) has been observed in the dataset poisoning maze at least 25 times.
-Additionally, when any given client by both User-Agent and network-clamped IP address has been observed, Anubis will emit log lines warning about it so that administrative action can be taken up to and including [filing abuse reports with the network owner](/blog/2025/file-abuse-reports).
+When any given client by both User-Agent and network-clamped IP address has been observed, Anubis will emit log lines warning about it so that administrative action can be taken up to and including [filing abuse reports with the network owner](/blog/2025/file-abuse-reports).
+
+### IP address logging
+
+Anubis' honeypot feature can log IP addresses to a file. These logs let you configure fail2ban pipelines or integrate with other software to block bot traffic (eg: Panorama).
+
+To use this feature:
+
+- Anubis must have access to storage it can write to.
+- The backing filesystem must support writes, seeking, and truncation.
+- The Anubis user must have write permissions to the log file.
+
+Configure this log file in the `honeypot` section of your [policy file](../policies.mdx):
+
+```yaml
+honeypot:
+ enabled: true
+ implementation: naive
+ ip_log_file: /data/anubis/honeypot.addrs
+```
+
+Anubis collects the IP addresses that hit the honeypot feature continuously and buffers them into memory. Anubis writes collected IP addresses every minute or when Anubis collects 32 kilobytes of addresses, whichever happens first. Once the file gets bigger than 64 kilobytes, the file is reset to avoid infinite growth.
diff --git a/docs/docs/admin/installation.mdx b/docs/docs/admin/installation.mdx
index 7000afe..bb1114c 100644
--- a/docs/docs/admin/installation.mdx
+++ b/docs/docs/admin/installation.mdx
@@ -39,6 +39,7 @@ Anubis is shipped in the Docker repo [`ghcr.io/techarohq/anubis`](https://github
| Tag | Meaning |
| :------------------ | :--------------------------------------------------------------------------------------------------------------------------------- |
| `latest` | The latest [tagged release](https://github.com/TecharoHQ/anubis/releases), if you are in doubt, start here. |
+| `pre` | The latest prerelease of Anubis. These releases will soon become full tagged releases. |
| `v` | The Anubis image for [any given tagged release](https://github.com/TecharoHQ/anubis/tags) |
| `main` | The current build on the `main` branch. Only use this if you need the latest and greatest features as they are merged into `main`. |
@@ -66,46 +67,48 @@ Currently the following settings are configurable via the policy file:
Anubis uses these environment variables for configuration:
-| Environment Variable | Default value | Explanation |
-| :----------------------------- | :---------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `ASSET_LOOKUP_HEADER` | unset | If set, use the contents of this header in requests when looking up custom assets in `OVERLAY_FOLDER`. See [Header-based overlay dispatch](./botstopper.mdx#header-based-overlay-dispatch) for more details. |
-| `BASE_PREFIX` | unset | If set, adds a global prefix to all Anubis endpoints (everything starting with `/.within.website/x/anubis/`). For example, setting this to `/myapp` would make Anubis accessible at `/myapp/` instead of `/`. This is useful when running Anubis behind a reverse proxy that routes based on path prefixes. |
-| `BIND` | `:8923` | The network address that Anubis listens on. For `unix`, set this to a path: `/run/anubis/instance.sock` |
-| `BIND_NETWORK` | `tcp` | The address family that Anubis listens on. Accepts `tcp`, `unix` and anything Go's [`net.Listen`](https://pkg.go.dev/net#Listen) supports. |
-| `CHALLENGE_TITLE` | unset | If set, override the translation stack to show a custom title for challenge pages such as "Making sure your connection is secure!". See [Customizing messages](./botstopper.mdx#customizing-messages) for more details. |
-| `COOKIE_DOMAIN` | unset | The domain the Anubis challenge pass cookie should be set to. This should be set to the domain you bought from your registrar (EG: `techaro.lol` if your webapp is running on `anubis.techaro.lol`). See this [stackoverflow explanation of cookies](https://stackoverflow.com/a/1063760) for more information.
Note that unlike `REDIRECT_DOMAINS`, you should never include a port number in this variable. |
-| `COOKIE_DYNAMIC_DOMAIN` | false | If set to true, automatically set cookie domain fields based on the hostname of the request. EG: if you are making a request to `anubis.techaro.lol`, the Anubis cookie will be valid for any subdomain of `techaro.lol`. |
-| `COOKIE_EXPIRATION_TIME` | `168h` | The amount of time the authorization cookie is valid for. |
-| `CUSTOM_REAL_IP_HEADER` | unset | If set, Anubis will read the client's real IP address from this header, and set it in `X-Real-IP` header. |
-| `COOKIE_PARTITIONED` | `false` | If set to `true`, enables the [partitioned (CHIPS) flag](https://developers.google.com/privacy-sandbox/cookies/chips), meaning that Anubis inside an iframe has a different set of cookies than the domain hosting the iframe. |
-| `COOKIE_PREFIX` | `anubis-cookie` | The prefix used for browser cookies created by Anubis. Useful for customization or avoiding conflicts with other applications. |
-| `COOKIE_SECURE` | `true` | If set to `true`, enables the [Secure flag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#block_access_to_your_cookies), meaning that the cookies will only be transmitted over HTTPS. If Anubis is used in an unsecure context (plain HTTP), this will be need to be set to false |
-| `COOKIE_SAME_SITE` | `None` | Controls the cookieās [`SameSite` attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value). Allowed: `None`, `Lax`, `Strict`, `Default`. `None` permits cross-site use but modern browsers require it to be **Secure**āso if `COOKIE_SECURE=false` or you serve over plain HTTP, use `Lax` (recommended) or `Strict` or the cookie will be rejected. `Default` uses the Go runtimeās `SameSiteDefaultMode`. `None` will be downgraded to `Lax` automatically if cookie is set NOT to be secure. |
-| `DIFFICULTY` | `4` | The difficulty of the challenge, or the number of leading zeroes that must be in successful responses. |
-| `DIFFICULTY_IN_JWT` | `false` | If set to `true`, adds the `difficulty` field into JWT claims, which indicates the difficulty the token has been generated. This may be useful for statistics and debugging. |
-| `ED25519_PRIVATE_KEY_HEX` | unset | The hex-encoded ed25519 private key used to sign Anubis responses. If this is not set, Anubis will generate one for you. This should be exactly 64 characters long. **Required when using persistent storage backends** (like bbolt) to ensure challenges survive service restarts. When running multiple instances on the same base domain, the key must be the same across all instances. See below for details. |
-| `ED25519_PRIVATE_KEY_HEX_FILE` | unset | Path to a file containing the hex-encoded ed25519 private key. Only one of this or its sister option may be set. **Required when using persistent storage backends** (like bbolt) to ensure challenges survive service restarts. When running multiple instances on the same base domain, the key must be the same across all instances. |
-| `ERROR_TITLE` | unset | If set, override the translation stack to show a custom title for error pages such as "Something went wrong!". See [Customizing messages](./botstopper.mdx#customizing-messages) for more details. |
-| `JWT_RESTRICTION_HEADER` | `X-Real-IP` | If set, the JWT is only valid if the current value of this header matches the value when the JWT was created. You can use it e.g. to restrict a JWT to the source IP of the user using `X-Real-IP`. |
-| `METRICS_BIND` | `:9090` | The network address that Anubis serves Prometheus metrics on. See `BIND` for more information. |
-| `METRICS_BIND_NETWORK` | `tcp` | The address family that the Anubis metrics server listens on. See `BIND_NETWORK` for more information. |
-| `OG_EXPIRY_TIME` | `24h` | The expiration time for the Open Graph tag cache. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
-| `OG_PASSTHROUGH` | `false` | If set to `true`, Anubis will enable Open Graph tag passthrough. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
-| `OG_CACHE_CONSIDER_HOST` | `false` | If set to `true`, Anubis will consider the host in the Open Graph tag cache key. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
-| `OVERLAY_FOLDER` | unset | If set, treat the given path as an [overlay folder](./botstopper.mdx#custom-images-and-css), allowing you to customize CSS, fonts, images, and add other assets to BotStopper deployments. |
-| `POLICY_FNAME` | unset | The file containing [bot policy configuration](./policies.mdx). See the bot policy documentation for more details. If unset, the default bot policy configuration is used. |
-| `PUBLIC_URL` | unset | The externally accessible URL for this Anubis instance, used for constructing redirect URLs (e.g., for Traefik forwardAuth). Leave it unset when Anubis terminates traffic directly (sidecar/standalone deployments) or redirect building will fail with `redir=null`. |
-| `REDIRECT_DOMAINS` | unset | Comma-separated list of domain names that Anubis should allow redirects to when passing a challenge. See [Redirect Domain Configuration](./configuration/redirect-domains) for more details. |
-| `SERVE_ROBOTS_TXT` | `false` | If set `true`, Anubis will serve a default `robots.txt` file that disallows all known AI scrapers by name and then additionally disallows every scraper. This is useful if facts and circumstances make it difficult to change the underlying service to serve such a `robots.txt` file. |
-| `SLOG_LEVEL` | `INFO` | The log level for structured logging. Valid values are `DEBUG`, `INFO`, `WARN`, and `ERROR`. Set to `DEBUG` to see all requests, evaluations, and detailed diagnostic information. |
-| `SOCKET_MODE` | `0770` | _Only used when at least one of the `*_BIND_NETWORK` variables are set to `unix`._ The socket mode (permissions) for Unix domain sockets. |
-| `STRIP_BASE_PREFIX` | `false` | If set to `true`, strips the base prefix from request paths when forwarding to the target server. This is useful when your target service expects to receive requests without the base prefix. For example, with `BASE_PREFIX=/foo` and `STRIP_BASE_PREFIX=true`, a request to `/foo/bar` would be forwarded to the target as `/bar`. |
-| `TARGET` | `http://localhost:3923` | The URL of the service that Anubis should forward valid requests to. Supports Unix domain sockets, set this to a URI like so: `unix:///path/to/socket.sock`. |
-| `USE_REMOTE_ADDRESS` | unset | If set to `true`, Anubis will take the client's IP from the network socket. For production deployments, it is expected that a reverse proxy is used in front of Anubis, which pass the IP using headers, instead. |
-| `USE_SIMPLIFIED_EXPLANATION` | false | If set to `true`, replaces the text when clicking "Why am I seeing this?" with a more simplified text for a non-tech-savvy audience. |
-| `USE_TEMPLATES` | false | If set to `true`, enable [custom HTML template support](./botstopper.mdx#custom-html-templates), allowing you to completely rewrite how BotStopper renders its HTML pages. |
-| `WEBMASTER_EMAIL` | unset | If set, shows a contact email address when rendering error pages. This email address will be how users can get in contact with administrators. |
-| `XFF_STRIP_PRIVATE` | `true` | If set, strip private addresses from `X-Forwarded-For` headers. To unset this, you must set `XFF_STRIP_PRIVATE=false` or `--xff-strip-private=false`. |
+| Environment Variable | Default value | Explanation |
+| :---------------------------------------- | :---------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `ASSET_LOOKUP_HEADER` | unset | If set, use the contents of this header in requests when looking up custom assets in `OVERLAY_FOLDER`. See [Header-based overlay dispatch](./botstopper.mdx#header-based-overlay-dispatch) for more details. |
+| `BASE_PREFIX` | unset | If set, adds a global prefix to all Anubis endpoints (everything starting with `/.within.website/x/anubis/`). For example, setting this to `/myapp` would make Anubis accessible at `/myapp/` instead of `/`. This is useful when running Anubis behind a reverse proxy that routes based on path prefixes. |
+| `BIND` | `:8923` | The network address that Anubis listens on. For `unix`, set this to a path: `/run/anubis/instance.sock` |
+| `BIND_NETWORK` | `tcp` | The address family that Anubis listens on. Accepts `tcp`, `unix` and anything Go's [`net.Listen`](https://pkg.go.dev/net#Listen) supports. |
+| `CHALLENGE_TITLE` | unset | If set, override the translation stack to show a custom title for challenge pages such as "Making sure your connection is secure!". See [Customizing messages](./botstopper.mdx#customizing-messages) for more details. |
+| `COOKIE_DOMAIN` | unset | The domain the Anubis challenge pass cookie should be set to. This should be set to the domain you bought from your registrar (EG: `techaro.lol` if your webapp is running on `anubis.techaro.lol`). See this [stackoverflow explanation of cookies](https://stackoverflow.com/a/1063760) for more information.
Note that unlike `REDIRECT_DOMAINS`, you should never include a port number in this variable. |
+| `COOKIE_DYNAMIC_DOMAIN` | false | If set to true, automatically set cookie domain fields based on the hostname of the request. EG: if you are making a request to `anubis.techaro.lol`, the Anubis cookie will be valid for any subdomain of `techaro.lol`. |
+| `COOKIE_EXPIRATION_TIME` | `168h` | The amount of time the authorization cookie is valid for. |
+| `CUSTOM_REAL_IP_HEADER` | unset | If set, Anubis will read the client's real IP address from this header, and set it in `X-Real-IP` header. |
+| `COOKIE_PARTITIONED` | `false` | If set to `true`, enables the [partitioned (CHIPS) flag](https://developers.google.com/privacy-sandbox/cookies/chips), meaning that Anubis inside an iframe has a different set of cookies than the domain hosting the iframe. |
+| `COOKIE_PREFIX` | `anubis-cookie` | The prefix used for browser cookies created by Anubis. Useful for customization or avoiding conflicts with other applications. |
+| `COOKIE_HTTP_ONLY` | `false` | If set to `true`, enables the [HttpOnly flag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#block_access_to_your_cookies), meaning that the cookies will only be readable by the server. |
+| `COOKIE_SECURE` | `true` | If set to `true`, enables the [Secure flag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#block_access_to_your_cookies), meaning that the cookies will only be transmitted over HTTPS. If Anubis is used in an unsecure context (plain HTTP), this will be need to be set to false |
+| `COOKIE_SAME_SITE` | `None` | Controls the cookieās [`SameSite` attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value). Allowed: `None`, `Lax`, `Strict`, `Default`. `None` permits cross-site use but modern browsers require it to be **Secure**āso if `COOKIE_SECURE=false` or you serve over plain HTTP, use `Lax` (recommended) or `Strict` or the cookie will be rejected. `Default` uses the Go runtimeās `SameSiteDefaultMode`. `None` will be downgraded to `Lax` automatically if cookie is set NOT to be secure. |
+| `DIFFICULTY` | `4` | The difficulty of the challenge, or the number of leading zeroes that must be in successful responses. |
+| `DIFFICULTY_IN_JWT` | `false` | If set to `true`, adds the `difficulty` field into JWT claims, which indicates the difficulty the token has been generated. This may be useful for statistics and debugging. |
+| `DYNAMIC_COOKIE_SUFFIX` | `true` | If set to `true`, generates a suffix for cookie names based on current cookie settings. Leaving it `true` is recommended to [circumvent infinite loops](https://github.com/TecharoHQ/anubis/releases/tag/v1.27.0). Disabling this feature is only required when needing to work with a specific cookie name (e.g. in the [HAProxy advanced config](./environments/haproxy.mdx#advanced-variant)). |
+| `ED25519_PRIVATE_KEY_HEX` | unset | The hex-encoded ed25519 private key used to sign Anubis responses. If this is not set, Anubis will generate one for you. This should be exactly 64 characters long. **Required when using persistent storage backends** (like bbolt) to ensure challenges survive service restarts. When running multiple instances on the same base domain, the key must be the same across all instances. See below for details. |
+| `ED25519_PRIVATE_KEY_HEX_FILE` | unset | Path to a file containing the hex-encoded ed25519 private key. Only one of this or its sister option may be set. **Required when using persistent storage backends** (like bbolt) to ensure challenges survive service restarts. When running multiple instances on the same base domain, the key must be the same across all instances. |
+| `ERROR_TITLE` | unset | If set, override the translation stack to show a custom title for error pages such as "Something went wrong!". See [Customizing messages](./botstopper.mdx#customizing-messages) for more details. |
+| `JWT_RESTRICTION_HEADER` | `X-Real-IP` | If set, the JWT is only valid if the current value of this header matches the value when the JWT was created. You can use it e.g. to restrict a JWT to the source IP of the user using `X-Real-IP`. |
+| `METRICS_BIND` | `:9090` | The legacy configuration value for the network address that Anubis serves Prometheus metrics on. Please migrate this to [the policy file](./policies.mdx#metrics-server) as soon as possible. |
+| `METRICS_BIND_NETWORK` | `tcp` | The legacy configuration value for the address family that Anubis serves Prometheus metrics on. Please migrate this to [the policy file](./policies.mdx#metrics-server) as soon as possible. |
+| `OG_EXPIRY_TIME` | `24h` | The expiration time for the Open Graph tag cache. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
+| `OG_PASSTHROUGH` | `false` | If set to `true`, Anubis will enable Open Graph tag passthrough. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
+| `OG_CACHE_CONSIDER_HOST` | `false` | If set to `true`, Anubis will consider the host in the Open Graph tag cache key. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
+| `OVERLAY_FOLDER` | unset | If set, treat the given path as an [overlay folder](./botstopper.mdx#custom-images-and-css), allowing you to customize CSS, fonts, images, and add other assets to BotStopper deployments. |
+| `POLICY_FNAME` | unset | The file containing [bot policy configuration](./policies.mdx). See the bot policy documentation for more details. If unset, the default bot policy configuration is used. |
+| `PUBLIC_URL` | unset | The externally accessible URL for this Anubis instance, used for constructing redirect URLs (e.g., for Traefik forwardAuth). Leave it unset when Anubis terminates traffic directly (sidecar/standalone deployments) or redirect building will fail with `redir=null`. |
+| `REDIRECT_DOMAINS` | unset | Comma-separated list of domain names that Anubis should allow redirects to when passing a challenge. See [Redirect Domain Configuration](./configuration/redirect-domains.mdx) for more details. |
+| `SERVE_ROBOTS_TXT` | `false` | If set `true`, Anubis will serve a default `robots.txt` file that disallows all known AI scrapers by name and then additionally disallows every scraper. This is useful if facts and circumstances make it difficult to change the underlying service to serve such a `robots.txt` file. |
+| `SLOG_LEVEL` | `INFO` | The log level for structured logging. Valid values are `DEBUG`, `INFO`, `WARN`, and `ERROR`. Set to `DEBUG` to see all requests, evaluations, and detailed diagnostic information. |
+| `SOCKET_MODE` | `0770` | _Only used when at least one of the `*_BIND_NETWORK` variables are set to `unix`._ The socket mode (permissions) for Unix domain sockets. |
+| `STRIP_BASE_PREFIX` | `false` | If set to `true`, strips the base prefix from request paths when forwarding to the target server. This is useful when your target service expects to receive requests without the base prefix. For example, with `BASE_PREFIX=/foo` and `STRIP_BASE_PREFIX=true`, a request to `/foo/bar` would be forwarded to the target as `/bar`. |
+| `TARGET` | `http://localhost:3923` | The URL of the service that Anubis should forward valid requests to. Supports Unix domain sockets, set this to a URI like so: `unix:///path/to/socket.sock`. |
+| `USE_REMOTE_ADDRESS` | unset | If set to `true`, Anubis will take the client's IP from the network socket. For production deployments, it is expected that a reverse proxy is used in front of Anubis, which pass the IP using headers, instead. |
+| `USE_SIMPLIFIED_EXPLANATION` (deprecated) | true | If set to `true`, replaces the text when clicking "Why am I seeing this?" with a more simplified text for a non-tech-savvy audience. |
+| `USE_TEMPLATES` | false | If set to `true`, enable [custom HTML template support](./botstopper.mdx#custom-html-templates), allowing you to completely rewrite how BotStopper renders its HTML pages. |
+| `WEBMASTER_EMAIL` | unset | If set, shows a contact email address when rendering error pages. This email address will be how users can get in contact with administrators. |
+| `XFF_STRIP_PRIVATE` | `true` | If set, strip private addresses from `X-Forwarded-For` headers. To unset this, you must set `XFF_STRIP_PRIVATE=false` or `--xff-strip-private=false`. |
Advanced configuration settings
diff --git a/docs/docs/admin/policies.mdx b/docs/docs/admin/policies.mdx
index 159d1ab..f4ca067 100644
--- a/docs/docs/admin/policies.mdx
+++ b/docs/docs/admin/policies.mdx
@@ -117,6 +117,96 @@ remote_addresses:
- 100.64.0.0/10
```
+## Metrics server
+
+Anubis includes support for [Prometheus-style metrics](https://prometheus.io/docs/introduction/overview/), allowing systems administrators to monitor Anubis' performance and effectiveness. This is a separate HTTP server with metrics, health checking, and debug routes.
+
+Anubis' metrics server is configured with the `metrics` block in the configuration file:
+
+```yaml
+metrics:
+ bind: ":9090"
+ network: "tcp"
+```
+
+If you want to bind metrics to a Unix socket, make sure to set the network to `unix` and add a socket mode:
+
+```yaml
+metrics:
+ bind: "/tmp/anubis_metrics.sock"
+ network: unix
+ socketMode: "0700" # must be a string
+```
+
+### Debug routes
+
+Anubis' metrics server supports [pprof](https://pkg.go.dev/runtime/pprof), the Go standard library tool for profiling Go applications. This is very useful for debugging how Anubis works in the wild with regards to CPU, multicore, and RAM usage. pprof is very powerful and can expose command line arguments as part of the debugging setup (inside Google, everything is done with command line flags).
+
+Prior versions of Anubis exposed pprof endpoints on all TCP bindhosts by default. This means that machines with incorrectly configured firewalls can expose command line arguments to the public internet in the right conditions.
+
+In order to enable pprof profiling endpoints on the Metrics server, set the `debug` flag under the `metrics` block:
+
+```yaml
+metrics:
+ bind: ":9090"
+ network: "tcp"
+
+ debug: true
+```
+
+To err on the side of caution, this defaults to disabled. If this defaults migration breaks your configuration, please let us know in a ticket.
+
+### TLS
+
+If you want to serve the metrics server over TLS, use the `tls` block:
+
+```yaml
+metrics:
+ bind: ":9090"
+ network: "tcp"
+
+ tls:
+ certificate: /path/to/tls.crt
+ key: /path/to/tls.key
+```
+
+The certificate and key will automatically be reloaded when the respective files change.
+
+### mTLS
+
+If you want to validate requests to ensure that they use a client certificate signed by a certificate authority (mutual TLS or mTLS), set the `ca` value in the `tls` block:
+
+```yaml
+metrics:
+ bind: ":9090"
+ network: "tcp"
+
+ tls:
+ certificate: /path/to/tls.crt
+ key: /path/to/tls.key
+ ca: /path/to/ca.crt
+```
+
+As it is not expected for certificate authority certificates to change often, the CA certificate will NOT be automatically reloaded when the respective file changes.
+
+### HTTP basic authentication
+
+Anubis' metrics server also supports setting HTTP basic auth as a lightweight protection against unauthorized users viewing metrics data. As the basic auth credentials are hardcoded in the configuration file, administrators SHOULD use randomly generated credentials, such as type-4 UUIDs or other high entropy strings. These credentials MUST NOT be sensitive or used to protect other high value systems.
+
+Configure it with the `basicAuth` block under `metrics`:
+
+```yaml
+metrics:
+ bind: ":9090"
+ network: "tcp"
+
+ basicAuth:
+ username: azurediamond
+ password: hunter2
+```
+
+If you have Python installed, you can generate a high entropy password with `python -c 'import secrets; print(secrets.token_urlsafe(32))'`.
+
## Imprint / Impressum support
Anubis has support for showing imprint / impressum information. This is defined in the `impressum` block of your configuration. See [Imprint / Impressum configuration](./configuration/impressum.mdx) for more information.
@@ -129,6 +219,7 @@ Anubis offers the following storage backends:
- [`memory`](#memory) -- A simple in-memory hashmap
- [`bbolt`](#bbolt) -- An on-disk key/value store backed by [bbolt](https://github.com/etcd-io/bbolt), an embedded key/value database for Go programs
+- [`s3api`](#s3api) -- A network-backed storage layer backed by [object storage](https://en.wikipedia.org/wiki/Object_storage), specifically using the [S3 API](https://docs.aws.amazon.com/AmazonS3/latest/API/Type_API_Reference.html).
- [`valkey`](#valkey) -- A remote in-memory key/value database backed by [Valkey](https://valkey.io/) (or another database compatible with the [RESP](https://redis.io/docs/latest/develop/reference/protocol-spec/) protocol)
If no storage backend is set in the policy file, Anubis will use the [`memory`](#memory) backend by default. This is equivalent to the following in the policy file:
@@ -339,6 +430,7 @@ Anubis exposes the following logging settings in the policy file:
| `level` | [log level](#log-levels) | `info` | The logging level threshold. Any logs that are at or above this threshold will be drained to the sink. Any other logs will be discarded. |
| `sink` | string | `stdio`, `file` | The sink where the logs drain to as they are being recorded in Anubis. |
| `parameters` | object | | Parameters for the given logging sink. This will vary based on the logging sink of choice. See below for more information. |
+| `asn` | bool | `true`, `false` | Add ASN information to logs/metrics. (Requires [GeoIP](./geoip.mdx) configuration) |
Anubis supports the following logging sinks:
@@ -393,6 +485,32 @@ logging:
When files are rotated out, the old files will be named after the rotation timestamp in [RFC 3339 format](https://www.rfc-editor.org/rfc/rfc3339).
+:::note
+
+If you are running Anubis in systemd via a native package, the default systemd unit settings are very restrictive and will forbid writing to folders in `/var/log`. In order to fix this, please make a [drop-in unit](https://www.flatcar.org/docs/latest/setup/systemd/drop-in-units/) like the following:
+
+```text
+# /etc/systemd/anubis@instance-name.service.d/50-var-log-readwrite.conf
+[Service]
+ReadWritePaths=/run /var/log/anubis
+```
+
+Once you write this to the correct place, reload the systemd configuration:
+
+```text
+sudo systemctl daemon-reload
+```
+
+And then restart Anubis:
+
+```text
+sudo systemctl restart anubis@instance-name
+```
+
+You may be required to make drop-ins for each Anubis instance depending on the facts and circumstances of your deployment.
+
+:::
+
### `stdio` sink
By default, Anubis logs everything to the standard error stream of its process. This requires no configuration:
@@ -404,6 +522,36 @@ logging:
If you use a service orchestration platform that does not capture the standard error stream of processes, you need to use a different logging sink.
+## Honeypot configuration
+
+Anubis has support for [dataset poisoning](./honeypot/overview.mdx). Out of the box this is enabled so that administrators can feed fail2ban pipelines. This works by adding an entry point to the honeypot maze in every page like this:
+
+```html
+
+```
+
+Any hits that match the URL `^/.within.website/x/cmd/anubis/api/honeypot/.*` are _malicious_ and should be blocked. A spec-compliant HTML parser will not parse this link, so any parser that does and visits it is categorically in the wrong.
+
+The following configuration options are supported:
+
+```yaml
+## Honeypot configuration
+honeypot:
+ ## If not set, Anubis will assume you meant `true`.
+ enabled: true
+ ## Currently the only supported method is the naive method.
+ ## See https://anubis.techaro.lol/docs/admin/honeypot/overview#implementation-notes for more information
+ implementation: naive
+```
+
+For more information about this feature, consult the [Dataset Poisoning](./honeypot/overview.mdx) page.
+
## Risk calculation for downstream services
In case your service needs it for risk calculation reasons, Anubis exposes information about the rules that any requests match using a few headers:
diff --git a/docs/docs/admin/thoth.mdx b/docs/docs/admin/thoth.mdx
index 364d655..d52c0b1 100644
--- a/docs/docs/admin/thoth.mdx
+++ b/docs/docs/admin/thoth.mdx
@@ -1,6 +1,15 @@
-# Thoth-based advanced checks
+---
+title: Thoth-based advanced checks
+unlisted: true
+---
-Status: Beta
+:::note
+
+This page describes a service that has since been cancelled and is scheduled for removal from the codebase. Please use [GeoIP databases](./geoip.mdx) instead. Thoth will be reused for other things eventually.
+
+:::
+
+Status: Cancelled
Anubis instances are normally isolated. Each Anubis instance has its own configuration and exists in roughly its own world without any long term memory between requests. As threats, workarounds, and AI scraper toolchains evolve, administrators will need a way to get more up to date information faster than Anubis' release cycle.
diff --git a/docs/docs/design/how-anubis-works.mdx b/docs/docs/design/how-anubis-works.mdx
index e274320..69b32b0 100644
--- a/docs/docs/design/how-anubis-works.mdx
+++ b/docs/docs/design/how-anubis-works.mdx
@@ -104,4 +104,4 @@ This ensures that the token has enough metadata to prove that the token is valid
## JWT signing
-Anubis uses an ed25519 keypair to sign the JWTs issued when challenges are passed. Anubis will generate a new ed25519 keypair every time it starts. At this time, there is no way to share this keypair between instance of Anubis, but that will be addressed in future versions.
+Anubis uses an ed25519 keypair to sign the JWTs issued when challenges are passed. Anubis will generate a new ed25519 keypair every time it starts. At this time, there is no way to share this keypair between instances of Anubis, but that will be addressed in future versions.
diff --git a/docs/docs/developer/CODE_OF_CONDUCT.md b/docs/docs/developer/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..a545f08
--- /dev/null
+++ b/docs/docs/developer/CODE_OF_CONDUCT.md
@@ -0,0 +1,132 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, caste, color, religion, or sexual
+identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+- Demonstrating empathy and kindness toward other people
+- Being respectful of differing opinions, viewpoints, and experiences
+- Giving and gracefully accepting constructive feedback
+- Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+- Focusing on what is best not just for us as individuals, but for the overall
+ community
+
+Examples of unacceptable behavior include:
+
+- The use of sexualized language or imagery, and sexual attention or advances of
+ any kind
+- Trolling, insulting or derogatory comments, and personal or political attacks
+- Public or private harassment
+- Publishing others' private information, such as a physical or email address,
+ without their explicit permission
+- Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official email address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+[INSERT CONTACT METHOD].
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of
+actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or permanent
+ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the
+community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.1, available at
+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by
+[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at
+[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
+[https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
diff --git a/docs/docs/developer/CONTRIBUTING.md b/docs/docs/developer/CONTRIBUTING.md
new file mode 100644
index 0000000..73bd65d
--- /dev/null
+++ b/docs/docs/developer/CONTRIBUTING.md
@@ -0,0 +1,161 @@
+# Contributing to Anubis
+
+Anubis is a Web AI Firewall Utility (WAIFU) written in Go. This is security software, correctness and test coverage matters.
+
+## Build & Run
+
+Prerequisites:
+
+- Go 1.27.3 or later.
+- Node.js (any supported LTS version).
+- Rust version 1.80 or later.
+- Optionally: Wasmtime
+- Optionally: binaryen version 130 (exact match).
+- esbuild, gzip, zstd, brotli, msitools
+
+If you have [Homebrew](https://brew.sh) installed: install all development tools at once with `brew bundle`.
+
+### Useful commands
+
+```shell
+npm ci # install source-level dependencies
+npm run assets # build JS/CSS (required before any Go build/test)
+npm run build # assets + go build -> ./var/anubis
+npm run dev # assets + run locally with --use-remote-address
+npm run format # format all code to project standards
+```
+
+When using `npm run dev`, Anubis runs on `http://localhost:8923` and points to `http://localhost:3000`. The documentation site listens on port `3000` by default.
+
+## Testing
+
+```shell
+# Run all unit tests (assets must be built first)
+npm run test
+
+# Run integration tests with real browsers
+npm run test:integration
+
+# Run a single test by name
+go test -run TestClampIP ./internal/
+
+# Run a single test file's package
+go test ./lib/config/
+
+# Run tests with verbose output
+go test -v -run TestBotValid ./lib/config/
+```
+
+### Smoke tests
+
+Anubis has functionality tests called smoke tests. Read more about them in the [smoke testing page](./smoke-tests.mdx).
+
+## Linting
+
+```shell
+go vet ./...
+go tool staticcheck ./...
+go tool govulncheck ./...
+```
+
+## Code Generation
+
+Anubis makes heavy use of code generation with `go generate` for HTML templating with [templ](https://templ.guide/), CSS optimization, and JavaScript building.
+
+Run all code generation logic with `npm run assets`.
+
+## Project Layout
+
+Important folders:
+
+- `cmd/anubis`: Main entrypoint for the project. Parses command line flags and starts listening over HTTP.
+- `lib/*`: The core library for Anubis and all of its features. This is internal code that is made public for ease of downstream consumption by [BotStopper](../admin/botstopper.mdx).
No API stability is guaranteed. Use at your own risk.
+- `internal/*`: Actual internal code that is private to the implementation of Anubis. If you need to use a package in this, please copy it out and manually vendor it in your own project.
+- `test/*`: [Smoke tests](./smoke-tests.mdx).
+- `web`: Frontend HTML templates.
+- `xess`: Frontend CSS framework and build logic.
+
+## Code Style
+
+Anubis is written in several programming languages. Please keep these guidelines in mind:
+
+### Go
+
+This project follows standard Go idioms. These include:
+
+- The standard library is already a dependency. Use the standard library as much as possible.
+- Avoid package import aliases unless you have no other choice.
+- Use `go tool goimports` to format code. Run with `npm run format`.
+- Use sentinel errors as package-level variables prefixed with `Err` (such as `ErrImportIsInvalid`). Wrap errors with [`fmt.Errorf`](https://pkg.go.dev/fmt#Errorf)'s `%w` formatting verb. Compare against sentinel errors in tests with `errors.Is`.
+- Use [`log/slog`](https://pkg.go.dev/log/slog) for all logging. Use the local logger variable named `lg` or create it from the `Server` instance. Preload context with [`lg.With`](https://pkg.go.dev/log/slog#With).
+- Pass logger instances to functions as a variable right after the context argument.
+- Do not log messages with a level above `Debug` unless the condition being logged is important for administrators to know.
+- Administrators have configured fail2ban pipelines on Anubis' logging output. Keep this in mind when changing any aspect of any log line.
+- Be conservative in what you send but liberal in what you accept.
+- Use [table-driven tests](https://go.dev/wiki/TableDrivenTests) when writing test code.
+- Use [`t.Helper()`](https://pkg.go.dev/testing#T.Helper) in helper code (setup/teardown scaffolding).
+- Use [`t.Cleanup()`](https://pkg.go.dev/testing#T.Cleanup) to tear down per-test or per-suite scaffolding.
+
+### Configuration parsing
+
+The configuration file is the main interface administrators have into Anubis. Keep these things in mind when adding features to the configuration file:
+
+- Return all configuration errors at once from validators (`Valid() error` methods that return many errors at once with `errors.Join`) so administrators can fix all their configuration problems at once.
+- Enumerations should use strong types with validation logic for parsing remote input.
+- All configuration values should have both `json` and `yaml` struct tags set.
+- Use pointer values for optional configuration values.
+
+### TypeScript
+
+Please follow these guidelines:
+
+- Prefer writing all front-end code in TypeScript. It is mostly there to ensure that development is done correctly.
+- Try to avoid JavaScript features newer than Chrome 75 unless you have a polyfill for backwards compatibility.
+- Keep functions small.
+- Use `const` by default and `let` if values need to change.
+- Make the code as unambiguous as possible.
+
+### HTML Templates
+
+Anubis uses [templ](https://templ.guide) for generating HTML on the server.
+
+- Running `go generate` or `npm run assets` must regenerate HTML templates.
+- Templates receive typed Go parameters.
+- Templates are for presentation only. Any business logic belongs in Go, not templ.
+
+## Commit Messages
+
+Commit messages follow the [**Conventional Commits**](https://www.conventionalcommits.org/en/v1.0.0/) format:
+
+```text
+[optional scope]:
+
+[optional body]
+
+[optional footer(s)]
+```
+
+**Types**: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`
+
+- Avoid breaking changes when possible. If you must introduce a breaking change, add `!` after the type/scope and include `BREAKING CHANGE:` with the reason for the breaking change in the bottom of your commit message.
+- Keep descriptions concise, imperative, lowercase, and without trailing punctuation.
+- All git commits must include a [Developer Certificate of Origin](https://en.wikipedia.org/wiki/Developer_Certificate_of_Origin). TL;DR: `git commit --signoff`.
+
+Mark commits as closing or fixing issues in trailers. For example:
+
+```text
+Closes: #1234
+Fixes: #1234
+Replaces: #1234
+Ref: TecharoHQ/yeet#4
+```
+
+## PR Checklist
+
+When you are ready to send your contribution as a pull request, please do the following:
+
+- Add description of changes to the `[Unreleased]` section of `docs/docs/CHANGELOG.md`.
+- Add test cases for bug fixes and behavior changes.
+- Add a [smoke test](./smoke-tests.mdx) if applicable.
+- Run integration tests: `npm run test:integration`.
+- All commits must have [verified (signed) signatures](./signed-commits.md).
diff --git a/docs/docs/developer/_category_.json b/docs/docs/developer/_category_.json
index 0b24e3b..f1843c5 100644
--- a/docs/docs/developer/_category_.json
+++ b/docs/docs/developer/_category_.json
@@ -1,8 +1,4 @@
{
"label": "Developer guides",
- "position": 50,
- "link": {
- "type": "generated-index",
- "description": "Guides and suggestions to make Anubis development go smoothly for everyone."
- }
+ "position": 50
}
diff --git a/docs/docs/developer/ai-coding-policy.md b/docs/docs/developer/ai-coding-policy.md
index b53e559..f644d75 100644
--- a/docs/docs/developer/ai-coding-policy.md
+++ b/docs/docs/developer/ai-coding-policy.md
@@ -1,13 +1,31 @@
# AI Coding Policy
-At some level it would be nice to be able to have the following AI coding policy from an ideological standpoint:
+The Anubis repository has `AGENTS.md` and `CLAUDE.md` files in it. These files are there to point AI agent tools at the [contribution guidelines](./CONTRIBUTING.md) and to add the following text to context windows:
-> Anubis does not accept code made primarily with the use of agentic AI tools such as Claude Code, Gemini CLI, GitHub Copilot, Zed, OpenCode, or any other similar tools. Please do not use them when contributing to this repo.
+## Attribution Requirements
-However, I'd be in violation by doing this because I have knowingly committed minor bits of code to the Anubis repo that were generated by AI tools (mostly things for smoke tests).
+AI agents must disclose what tool and model they are using in the "Assisted-by" commit footer:
-As such, Anubis is taking more of a centrist approach with regards to AI coding tools: regardless of what tool you use to make contributions to Anubis, when you sign off your code, you are taking responsibility for what you commit. You are also expected to understand what you are changing, what the implications are, and all other relevant factors.
+```text
+Assisted-by: [Model Name] via [Tool Name]
+```
-If you use AI coding tools for a majority of your committed work, you MUST disclose it with [the `Assisted-by` footer](https://xeiaso.net/notes/2025/assisted-by-footer/). The Anubis maintainers will be using tooling that looks for these footers and will prioritize scrutiny and level of attention appropriately.
+Example:
-In order to ensure compliance with this policy, language has been placed in `AGENTS.md` and `CLAUDE.md` to entice AI coding tools to add these footers.
+```text
+Assisted-by: GLM 4.6 via Claude Code
+```
+
+This is here intentionally so that low-effort AI agent use is detected. This makes AI agents tattle on themselves.
+
+## Guidelines
+
+If your use of AI agent tools is largely respectful of the fact that maintainers have limited time for review, you will likely not run into issues.
+
+We kindly ask the following:
+
+- Pull requests that contain commits with this metadata attached will have their reviews be deprioritized to make room for human authored work.
+- People that abuse the system with a flood of low-quality contributions ("AI slop") will be banned upon their first infraction.
+- Please understand the actions and implications of every contribution you make, regardless of what tools were used in its creation.
+- Please do not put direct AI agent output in documentation or error messages.
+- If you really are going to submit an AI-authored PR, please make sure that your code has sufficient test coverage. Look into skills such as [go-table-driven-tests](https://www.skills.sh/tigrisdata/skills/go-table-driven-tests).
diff --git a/docs/docs/developer/building-anubis.md b/docs/docs/developer/building-anubis.md
index 63bafa4..7e178c2 100644
--- a/docs/docs/developer/building-anubis.md
+++ b/docs/docs/developer/building-anubis.md
@@ -1,45 +1,55 @@
---
-title: Building Anubis without Docker
+title: Packaging Anubis
---
+Anubis is a web application written in Go with components in JavaScript. Packaging it should be similar to other applications with the same constraints.
+
:::note
-These instructions may work, but for right now they are informative for downstream packagers more than they are ready-made instructions for administrators wanting to run Anubis on their servers. Pre-made binary package support is being tracked in [#156](https://github.com/TecharoHQ/anubis/issues/156).
+Please do not sidestep the build logic shipped by Anubis. We assume that the build logic shipped by Anubis is run. Any deviations from the semantics of this build logic may result in bugs that we will be blamed for. Please make our lives easier by not reinventing the wheel.
:::
## Entirely from source
-If you are doing a build entirely from source, here's what you need to do:
+In order to build a production-ready binary of Anubis, you need the following packages in your environment:
-:::info
+- [Go](https://go.dev) at least version 1.27.3
+- [esbuild](https://esbuild.github.io/)
+- [Rust and Cargo](https://rust-lang.org) at least version 1.80 with the [wasm32-unknown-unknown](https://doc.rust-lang.org/rustc/platform-support/wasm32-unknown-unknown.html) target installed
+- [Node.JS & NPM](https://nodejs.org/en) (latest LTS)
+- `gzip`
+- `zstd`
+- `brotli`
+- Optionally: [Wasmtime](https://wasmtime.dev/) or [binaryen version 130](https://github.com/WebAssembly/binaryen/releases#release-version_130).
-If you maintain a package for Anubis v1.15.x or older, you will need to update your package build. You may want to use one of the half-baked tarballs if your distro/environment of choice makes it difficult to use npm.
+:::note
+
+The binaryen version match must be exact. If it is not met, then Anubis' build system will fall back to a bundled version. If neither Wasmtime or binaryen version 130 are installed, Anubis will fall back to using a bootstrap compiler to run these required tools.
:::
-### Tools needed
+Anubis does not require a C compiler to build, meaning it is fully compatible with cross-compilation.
-In order to build a production-ready binary of Anubis, you need the following packages in your environment:
+:::note
-- [Go](https://go.dev) at least version 1.24 - the programming language that Anubis is written in
-- [esbuild](https://esbuild.github.io/) - the JavaScript bundler Anubis uses for its production JS assets
-- [Node.JS & NPM](https://nodejs.org/en) - manages some build dependencies
-- `gzip` - compresses production JS (part of coreutils)
-- `zstd` - compresses production JS
-- `brotli` - compresses production JS
-
-To upgrade your version of Go without system package manager support, install `golang.org/dl/go1.24.2` (this can be done from any version of Go):
+To upgrade your version of Go without system package manager support, install `golang.org/dl/go1.27.3` (this can be done from any version of Go):
```text
-go install golang.org/dl/go1.24.2@latest
-go1.24.2 download
+go install golang.org/dl/go1.27.3@latest
+go1.27.3 download
```
+Then make a symbolic link from `go1.27.3` to `go` in your `$PATH`.
+
+:::
+
### Install dependencies
```text
-make deps
+npm ci
+go mod download
+cargo fetch
```
This will download Go and NPM dependencies.
@@ -47,7 +57,7 @@ This will download Go and NPM dependencies.
### Building static assets
```text
-make assets
+npm run assets
```
This will build all static assets (CSS, JavaScript) for distribution.
@@ -55,12 +65,10 @@ This will build all static assets (CSS, JavaScript) for distribution.
### Building Anubis to the `./var` folder
```text
-make build
+npm run build
```
-From this point it is up to you to make sure that `./var/anubis` and `./var/robots2policy` end up in
-the right place. You may want to consult the `./run` folder for useful files such as a systemd unit
-and `anubis.env.default` file.
+From this point it is up to you to make sure that `./var/anubis` and `./var/robots2policy` end up in the right place. You may want to consult the `./run` folder for useful files such as a systemd unit and the `anubis.env.default` file. The default configuration file is in `./data/botPolicies.yaml`.
## "Pre-baked" tarball
@@ -77,7 +85,7 @@ When using this tarball, all you need to do is build `./cmd/anubis`:
make prebaked-build
```
-Anubis will be built to `./var/anubis` and the robots2policy tool to `./var/robots2policy`.
+Anubis will be built to `./var/anubis` and the robots2policy tool to `./var/robots2policy`. Install these via your normal packaging process.
## Development dependencies
diff --git a/docs/docs/developer/code-quality.md b/docs/docs/developer/code-quality.md
deleted file mode 100644
index 6dcc44a..0000000
--- a/docs/docs/developer/code-quality.md
+++ /dev/null
@@ -1,31 +0,0 @@
----
-title: Code quality guidelines
----
-
-When submitting code to Anubis, please take the time to consider the fact that this project is security software. If things go bad, bots can pummel sites into oblivion. This is not ideal for uptime.
-
-As such, code reviews will be a bit more strict than you have seen in other projects. This is not people trying to be mean, this is a side effect of taking the problem seriously.
-
-When making code changes, try to do the following:
-
-- If you're submitting a bugfix, add a test case for it
-- If you're changing the JavaScript, make sure the integration tests pass (`npm run test:integration`)
-
-## Commit messages
-
-Anubis follows the Go project's conventions for commit messages. In general, an ideal commit message should read like this:
-
-```text
-path/to/folder: brief description of the change
-
-If the change is subtle, has implementation consequences, or is otherwise
-not entirely self-describing: take the time to spell out why. If things
-are very subtle, please also amend the documentation accordingly
-```
-
-The subject of a commit message should be the second half of the sentence "This commit changes the Anubis project to:". Here's a few examples:
-
-- `disable DroneBL by default`
-- `port the challenge to WebAssembly`
-
-The extended commit message is also your place to give rationale for a new feature. When maintainers are reviewing your code, they will use this to figure out if the burden from feature maintainership is worth the merge.
diff --git a/docs/docs/developer/cspell.md b/docs/docs/developer/cspell.md
new file mode 100644
index 0000000..02f0a89
--- /dev/null
+++ b/docs/docs/developer/cspell.md
@@ -0,0 +1,34 @@
+# Spellchecking
+
+Anubis uses [CSpell](https://cspell.org/) to ensure words are spelled correctly. The project dictionary is at `.vscode/project-words.txt`.
+
+## Manually testing spellchecking
+
+To manually run spellchecking against the files you have modified before commit:
+
+```sh
+npm run test:spelling
+```
+
+## Adding words to the dictionary
+
+To add a word to the project dictionary (eg: `${WORD}`), do the following:
+
+### Append the word to the dictionary
+
+```sh
+echo ${WORD} >> .vscode/project-words.txt
+```
+
+### Sort the dictionary list
+
+```sh
+npm run test:spelling:sort
+```
+
+### Commit the results
+
+```sh
+git add .vscode/project-words.txt
+git commit -sm "chore: spelling"
+```
diff --git a/docs/docs/developer/index.mdx b/docs/docs/developer/index.mdx
new file mode 100644
index 0000000..58ba56b
--- /dev/null
+++ b/docs/docs/developer/index.mdx
@@ -0,0 +1,22 @@
+---
+title: Developer Guides
+---
+
+Thank you for wanting to contribute to Anubis, the Web AI Firewall Utility that protects web applications from abusive scrapers! This guide is your cheat sheet to making sure your contributions meet standards and can be merged as soon as possible.
+
+:::note
+
+This program is mostly written by a single person in a basement in Canada. Sometimes issues and pull requests get missed. Please remember the human on the other end.
+
+:::
+
+## Links
+
+- [AI coding policy](./ai-coding-policy.md)
+- [Code of Conduct](./CODE_OF_CONDUCT.md)
+- [Contribution guidelines](./CONTRIBUTING.md)
+- [Local development](./local-dev.md)
+- [Packaging Anubis](./building-anubis.md)
+- [Signed commits](./signed-commits.md)
+- [Smoke tests](./smoke-tests.mdx)
+- [Spellchecking](./cspell.md)
diff --git a/docs/docs/developer/local-dev.md b/docs/docs/developer/local-dev.md
index aadf2ef..cb1cf6f 100644
--- a/docs/docs/developer/local-dev.md
+++ b/docs/docs/developer/local-dev.md
@@ -17,6 +17,8 @@ Anubis requires the following tools to be installed to do local development:
- [Go](https://go.dev) - the programming language that Anubis is written in
- [esbuild](https://esbuild.github.io/) - the JavaScript bundler Anubis uses for its production JS assets
- [Node.JS & NPM](https://nodejs.org/en) - manages some build dependencies
+- Optionally: [Wasmtime](https://wasmtime.dev/) - used to run the fallback vendored version of binaryen committed to this repository.
+- Optionally: [binaryen version 130](https://github.com/WebAssembly/binaryen/releases/tag/version_130) (exact match) - optimizes and compiles WebAssembly code so that it runs on all browsers Anubis supports.
- `gzip` - compresses production JS (part of coreutils)
- `zstd` - compresses production JS
- `brotli` - compresses production JS
@@ -64,27 +66,20 @@ DOCKER_REPO=registry.host/org/repo DOCKER_METADATA_OUTPUT_TAGS=registry.host/org
For more information, see [Building native packages is complicated](https://xeiaso.net/blog/2025/anubis-packaging/) and [#156: Debian, RPM, and binary tarball packages](https://github.com/TecharoHQ/anubis/issues/156).
-Install `yeet`:
-
-:::note
-
-`yeet` will soon be moved to a dedicated TecharoHQ repository. This is currently done in a hacky way in order to get this ready for user feedback.
-
-:::
-
-```text
-go install within.website/x/cmd/yeet@v1.13.4
-```
-
Install the dependencies for Anubis:
```text
npm ci
-go mod download
```
-Build the packages into `./var`:
+Build the static assets:
```text
-yeet
+npm run assets
+```
+
+Build the packages into `./var/packages`:
+
+```text
+go tool yeet --package-dest-dir ./var/packages
```
diff --git a/docs/docs/developer/smoke-tests.mdx b/docs/docs/developer/smoke-tests.mdx
new file mode 100644
index 0000000..9ec025f
--- /dev/null
+++ b/docs/docs/developer/smoke-tests.mdx
@@ -0,0 +1,112 @@
+# Smoke testing
+
+Anubis has three types of tests:
+
+1. Unit tests in `_test.go` files, which test individual parts of the Anubis code.
+2. Integration tests in package `internal/test`, which tests common scenarios that Anubis is used with.
+3. Smoke tests in `test`, which test server infrastructure commonly used with Anubis.
+
+This guide helps you write a smoke test so you can make sure a given configuration is known to be supported because CI runs it constantly.
+
+## What is a smoke test?
+
+In Anubis, a smoke test is a folder with an executable file named `test.sh`. If the script returns exit code 0 (zero), it passed. If it returns any other exit code, it failed and is retried up to 10 (ten) times.
+
+### Shell script (simple)
+
+Here is an example smoke test that builds Anubis, points it to a simple HTTP endpoint, starts it up, and makes sure `curl` can reach that endpoint:
+
+```sh
+#!/usr/bin/env bash
+# test/example/test.sh
+
+set -euo pipefail
+
+function cleanup() {
+ pkill -P $$
+}
+
+trap cleanup EXIT SIGINT
+
+# Build static assets
+(cd ../.. && npm ci && npm run assets)
+
+go tool anubis --help 2>/dev/null ||:
+
+go run ../cmd/unixhttpd &
+
+go tool anubis \
+ --policy-fname ./anubis.yaml \
+ --use-remote-address \
+ --target=unix://$(pwd)/unixhttpd.sock &
+
+backoff-retry node ./test.mjs
+```
+
+```js
+// test.mjs
+
+async function fetchData() {
+ return fetch("http://localhost:8923/")
+ .then((resp) => {
+ if (resp.status !== 200) {
+ throw new Error(`wanted status 200, got status: ${resp.status}`);
+ }
+ return resp;
+ })
+ .then((resp) => resp.text());
+}
+
+(async () => {
+ const data = await fetchData();
+ if (!data.includes("test.mjs")) {
+ console.log(
+ "HTML response did not include `test.mjs` file, meaning Anubis is blocking this test",
+ );
+ process.exit(1);
+ }
+ console.log(data);
+ console.log("All is well");
+ process.exit(0);
+})();
+```
+
+### Docker compose (complicated)
+
+Some tests may require starting up infrastructure with `docker compose`. If this is the case, create a `docker-compose.yaml` file with the needed infrastructure and build the Anubis Docker image with `build_anubis_ko`:
+
+```sh
+#!/usr/bin/env bash
+# test/example/test.sh
+
+set -eo pipefail
+
+export VERSION=$GITHUB_COMMIT-test
+export KO_DOCKER_REPO=ko.local
+
+set -u
+
+source ../lib/lib.sh
+
+build_anubis_ko
+
+docker compose up -d
+
+backoff-retry node ./test.mjs
+```
+
+## Registering the test in CI
+
+All smoke tests are registered in matrix subjobs in `.github/workflows/smoke-tests.yml`. This allocates and uses a new CI worker per test. This appears slightly wasteful at first glance, however these tests are doing a lot of work that assumes port numbers in fiddly ways. It's easier to have dedicated machines for them than having to worry about sharing port numbers.
+
+To add a test named `linear-search`:
+
+```diff
+ - healthcheck
+ - i18n
+ - lightpanda
++ - linear-search
+ - log-file
+ - nginx
+ - palemoon/amd64
+```
diff --git a/docs/docs/index.mdx b/docs/docs/index.mdx
index 709492f..f13bd2f 100644
--- a/docs/docs/index.mdx
+++ b/docs/docs/index.mdx
@@ -32,11 +32,23 @@ Anubis is brought to you by sponsors and donors like:
+
+
+
+
+
### Gold Tier
-
-
+
+
+
+
+
@@ -74,13 +86,22 @@ Anubis is brought to you by sponsors and donors like:
height="64"
/>
-
+
+
+
+
+
+
+
+
+
+
## Overview
@@ -100,19 +121,19 @@ For live chat, please join the [Patreon](https://patreon.com/cadey) or join [Git
## Star History
-
+
diff --git a/docs/docs/user/frequently-asked-questions.mdx b/docs/docs/user/frequently-asked-questions.mdx
index 3fa8da4..8523435 100644
--- a/docs/docs/user/frequently-asked-questions.mdx
+++ b/docs/docs/user/frequently-asked-questions.mdx
@@ -1,24 +1,45 @@
# Frequently Asked Questions
-## Why can't you just put details about the proof of work challenge into the challenge page so I don't need to run JavaScript?
+## Why are challenge details not embedded into the human-readable part of challenge pages?
-A common question is something along the lines of "why can't you give me a shell script to run the challenge on my laptop so that I don't have to enable JavaScript". Malware has been known to show an interstitial that [asks the user to paste something into their run box on Windows](https://www.malwarebytes.com/blog/news/2025/03/fake-captcha-websites-hijack-your-clipboard-to-install-information-stealers), which will then make that machine a zombie in a botnet.
+Many people have asked why the challenge details are not embedded into challenge pages so they do not have to run JavaScript. There are many instances where malware [asks the user to paste something into their run box on Windows](https://www.malwarebytes.com/blog/news/2025/03/fake-captcha-websites-hijack-your-clipboard-to-install-information-stealers). This malware adds your computer to a botnet, steal information, or encrypt all file contents for a ransom.
-It would be in very bad taste to associate a security product such as Anubis with behavior similar to what malware uses. This would destroy user trust in the product and potentially result in reputational damage for the contributors. When at all possible, we want to avoid this happening.
+In order for Anubis' protection to be effective, Anubis must not give users instructions akin to this kind of malware. Anubis does not require user input and must function automatically via JavaScript. Anubis must not require users to paste code into terminals or run boxes to pass challenges.
-Technically inclined users are easily able to understand how the proof of work check works by either reading the JavaScript on the page or [reading the source code of the JavaScript program](https://github.com/TecharoHQ/anubis/tree/main/web/js). Please note that the format of the challenges and the algorithms used to solve them are liable to change without notice and are not considered part of the public API of Anubis. When such a change occurs, this will break your workarounds.
+Technically inclined users are able to understand how the proof of work challenge works and write their own solver. The format of the challenges and algorithms used are liable to change without notice. Any details about challenges are not part of the public API of Anubis. When such a change occurs, those workarounds will break.
-If [sufficient funding is raised](https://github.com/TecharoHQ/anubis/discussions/278), a browser extension that packages the proof of work checks and looks for Anubis challenge pages to solve them will be created.
+## Why does Anubis use Web Workers?
-## Why does Anubis use [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) to do its proof of work challenge?
+Anubis uses [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) to execute challenge logic for two main reasons:
-Anubis uses [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) to do its proof of work challenge for two main reasons:
+1. Browsers block the main rendering thread when JavaScript executes. The challenge logic comprises many blocking math operations. Executing challenge logic on the main thread can cause browsers to hang and not respond to user input. Running challenge logic in Web Workers fixes this.
+2. Web Workers enable executing JavaScript code across multiple CPU threads. Multithreading enables Anubis challenges to run in parallel across all system cores, making the challenge page complete as fast as possible. Anubis challenges scale horizontally because modern hardware advancements are mostly around parallelism.
-1. The proof of work operation is a lot of serially blocking calls. If you do serially blocking calls in JavaScript, some browsers will hang and not respond to user input. This is bad user experience. Using a Web Worker allows the browser to do this computation in the background so your browser will not hang.
-2. Web Workers allow you to do multithreaded execution of JavaScript code. This lets Anubis run its checks in parallel across all your system cores so that the challenge can complete as fast as possible. In the last decade, most CPU advancements have come from making cores and code extremely parallel. Using Web Workers lets Anubis take advantage of your hardware as much as possible so that the challenge finishes as fast as possible.
-
-If you use a browser extension such as [JShelter](https://jshelter.org/), you will need to [modify your JShelter configuration](./known-broken-extensions.md#jshelter) to allow Anubis' proof of work computation to complete.
+If you use a browser extension such as [JShelter](https://jshelter.org/), you will need to [modify settings](./known-broken-extensions.md#jshelter) to allow challenges to complete.
## Does Anubis mine Bitcoin?
No. Anubis does not mine Bitcoin or any other cryptocurrency.
+
+## I disabled Just-in-time compilation in my browser. Why is Anubis slow?
+
+Anubis challenges run many complicated math operations in a tight loop. [Just-in-time (JIT) compilation](https://en.wikipedia.org/wiki/Just-in-time_compilation) optimizes JavaScript execution by a significant degree. The JIT enables browsers to execute code as if it was natively written for your computer. Anubis' JavaScript challenges benefit from JIT complication, running much faster with the JIT enabled.
+
+Without the JIT enabled, all JavaScript programs run through a slow interpreter. This slow interpreter translates single lines of JavaScript into many dozens of machine instructions instead of JIT-ing down to single machine instructions. It takes longer to emulate the JavaScript environment to add numbers than it does to have the JIT add the numbers directly.
+
+Some users choose to disable the JIT as a security hardening measure. Depending on threat profiles, this may be a reasonable action. Keep in mind that disabling the browser feature that makes Anubis fast makes Anubis slow.
+
+If you have disabled the JIT and find Anubis checks slow, please re-enable the JIT. There is no way for Anubis to work around you choosing to disable the browser feature that makes Anubis fast.
+
+## What versions of browsers does Anubis support?
+
+Anubis supports at least the following:
+
+- Google Chrome/Chromium 75 and later
+- Mozilla Firefox 120 and later
+- Safari 10 and later
+- Pale Moon 33 and later
+
+Anubis may support other browsers, but development prioritizes the above browsers. If you discover compatibility issues, please file a bug report with OS, browser, and hardware model number information.
+
+If you work on a browser that does not work with Anubis and want us to automatically test it, please [submit a functional test](https://github.com/TecharoHQ/anubis/tree/main/test/palemoon/amd64) so that we know of failures instantly.
diff --git a/docs/docs/user/known-broken-extensions.md b/docs/docs/user/known-broken-extensions.md
index 864b5dc..2d23405 100644
--- a/docs/docs/user/known-broken-extensions.md
+++ b/docs/docs/user/known-broken-extensions.md
@@ -2,7 +2,7 @@
title: List of known browser extensions that can break Anubis
---
-This page contains a list of all of the browser extensions that are known to break Anubis' functionality and their associated GitHub issues, along with instructions on how to work around the issue.
+This page outlines browser extensions known to break Anubis' client code and workarounds.
## [JShelter](https://jshelter.org/)
@@ -12,21 +12,22 @@ This page contains a list of all of the browser extensions that are known to bre
| GitHub issue | https://github.com/TecharoHQ/anubis/issues/25 |
| Be aware of | [What are Web Workers, and what are the threats that I face?](https://jshelter.org/faq/#what-are-web-workers-and-what-are-the-threats-that-i-face) |
-### Workaround steps (recommended):
+### Workaround 1
-1. Click on the JShelter badge icon (typically in the toolbar next to your navigation bar; if you cannot locate the icon, see [this question](https://jshelter.org/faq/#can-i-see-a-jshelter-badge-icon-next-to-my-navigation-bar-i-want-to-interact-with-the-extension-easily-and-avoid-going-through-settings)).
+Disable WebWorker protection for the given site.
+
+1. Click on the JShelter badge icon.
2. Expand JavaScript Shield settings by clicking on the `Modify` button.
3. Click on the `Detail tweaks of JS shield for this site` button.
-4. Click and drag the `WebWorker` slider to the left until `Remove` is replaced by the `Unprotected`.
-5. Refresh the page, for example, by clicking on the `Refresh page` button at the top of the JShelter pop up window.
-6. You might want to restore the Worker settings once you go through the challenge.
+4. Click and drag the `WebWorker` slider to the left, showing `Unprotected`.
+5. Refresh the page.
-### Workaround steps (alternative if you do not want to dig in JShelter's pop up):
+### Workaround 2
-1. Click on the JShelter badge icon (typically in the toolbar next to your navigation bar; if you cannot locate the icon, see [this question](https://jshelter.org/faq/#can-i-see-a-jshelter-badge-icon-next-to-my-navigation-bar-i-want-to-interact-with-the-extension-easily-and-avoid-going-through-settings)).
+1. Click on the JShelter badge icon.
2. Expand JavaScript Shield settings by clicking on the `Modify` button.
3. Choose "Turn JavaScript Shield off"
-4. Refresh the page, for example, by clicking on the `Refresh page` button at the top of the JShelter pop up window.
+4. Refresh the page.
:::note
@@ -34,7 +35,7 @@ Taking these actions will remove all protections of JavaScript Shield for all pa
:::
-### Workaround steps (alternative if you do not like JShelter's pop up):
+### Workaround 3
1. Open JShelter extension settings
2. Click on JS Shield details
diff --git a/docs/docs/user/known-instances.md b/docs/docs/user/known-instances.md
index 9b24282..f3c47d5 100644
--- a/docs/docs/user/known-instances.md
+++ b/docs/docs/user/known-instances.md
@@ -38,10 +38,8 @@ This page contains a non-exhaustive list with all websites using Anubis.
- https://squirreljme.cc/
- https://superlove.sayitditto.net/
- https://svnweb.freebsd.org/
-- https://trac.ffmpeg.org/
- https://tumfatig.net/
- https://wiki.archlinux.org/
-- https://wiki.dolphin-emu.org/
- https://wiki.freepascal.org/
- https://wiki.koha-community.org/
- https://www.cfaarchive.org/
@@ -53,6 +51,11 @@ This page contains a non-exhaustive list with all websites using Anubis.
- https://bbs.archlinux32.org/
- https://bugs.archlinux32.org/
+-
+ Dolphin Emulator
+ - https://forums.dolphin-emu.org/
+ - https://wiki.dolphin-emu.org/
+
- Duke University
- https://repository.duke.edu/
@@ -60,6 +63,11 @@ This page contains a non-exhaustive list with all websites using Anubis.
- https://find.library.duke.edu/
- https://nicholas.duke.edu/
+-
+ FFmpeg
+ - https://git.ffmpeg.org/
+ - https://trac.ffmpeg.org/
+
- Forschungszentrum Jülich
- https://juser.fz-juelich.de/
@@ -112,11 +120,9 @@ This page contains a non-exhaustive list with all websites using Anubis.
- https://git.kernel.org/
- https://lore.kernel.org/
--
- The United Nations
- - https://policytoolbox.iiep.unesco.org/
-
- Valve Corporation
- https://developer.valvesoftware.com/wiki/Main_Page
+ - https://wiki.teamfortress.com/wiki/Main_Page
+ - https://gitlab.steamos.cloud/
diff --git a/docs/docs/user/why-see-challenge.md b/docs/docs/user/why-see-challenge.md
index 046fec3..33dfb5e 100644
--- a/docs/docs/user/why-see-challenge.md
+++ b/docs/docs/user/why-see-challenge.md
@@ -2,8 +2,8 @@
title: Why is Anubis showing up on a website?
---
-You are seeing Anubis because the administrator of that website has set up [Anubis](https://github.com/TecharoHQ/anubis) to protect the server against the scourge of [AI companies aggressively scraping websites](https://thelibre.news/foss-infrastructure-is-under-attack-by-ai-companies/). This can and does cause downtime for the websites, which makes their resources inaccessible for everyone.
+Anubis shows up on a website because the administrator set up Anubis to protect their server. There are many abusive scrapers [destroying websites with too many requests](https://thelibre.news/foss-infrastructure-is-under-attack-by-ai-companies/), making servers collapse under the pressure. This causes downtime for the websites, making resources inaccessible for everyone.
-Anubis is a compromise. Anubis uses a [proof-of-work](/docs/design/why-proof-of-work) scheme in the vein of [Hashcash](https://en.wikipedia.org/wiki/Hashcash), a proposed proof-of-work scheme for reducing email spam. The idea is that at individual scales the additional load is ignorable, but at mass scraper levels it adds up and makes scraping much more expensive.
+Anubis is a web application firewall that uses heuristics to discover suspect clients and present them a simple challenge. The idea behind these challenges is that they are easy to solve for individuals, but prohibitively expensive to solve en masse for abusive scraping.
-Ultimately, this is a hack whose real purpose is to give a "good enough" placeholder solution so that more time can be spent on fingerprinting and identifying headless browsers (EG: via how they do font rendering) so that the challenge proof of work page doesn't need to be presented to users that are much more likely to be legitimate.
+Research and development continues such that Anubis shows challenge pages less often. Please keep updated with Anubis' development to learn more about the progress in this matter.
diff --git a/docs/manifest/cfg/anubis/botPolicies.yaml b/docs/manifest/cfg/anubis/botPolicies.yaml
index fbac6cd..d1c8a28 100644
--- a/docs/manifest/cfg/anubis/botPolicies.yaml
+++ b/docs/manifest/cfg/anubis/botPolicies.yaml
@@ -74,6 +74,8 @@ bots:
weight:
adjust: -5
+ - import: (data)/clients/small-internet-browsers/*.yaml
+
# The weight thresholds for when to trigger individual challenges. Any
# CHALLENGE will take precedence over this.
#
@@ -118,8 +120,8 @@ thresholds:
# This challenge proves the client can run a webapp written with Preact.
# The preact webapp simply loads, calculates the SHA-256 checksum of the
# challenge data, and forwards that to the client.
- algorithm: preact
- difficulty: 1
+ algorithm: sha256
+ difficulty: 16
- name: mild-proof-of-work
expression:
all:
@@ -128,19 +130,23 @@ thresholds:
action: CHALLENGE
challenge:
# https://anubis.techaro.lol/docs/admin/configuration/challenges/proof-of-work
- algorithm: fast
- difficulty: 2 # two leading zeros, very fast for most clients
+ algorithm: argon2id
+ difficulty: 4 # two leading zeros, very fast for most clients
# For clients that are browser like and have gained many points from custom rules
- name: extreme-suspicion
expression: weight >= 30
action: CHALLENGE
challenge:
# https://anubis.techaro.lol/docs/admin/configuration/challenges/proof-of-work
- algorithm: fast
- difficulty: 4
+ algorithm: argon2id
+ difficulty: 6
dnsbl: false
+logging:
+ sink: stdio
+ level: "WARN"
+
impressum:
footer: |
This website is hosted by Techaro. If you have any complaints or notes about the service, please contact support@techaro.lol and we will assist you as soon as possible.
@@ -202,3 +208,15 @@ store:
backend: bbolt
parameters:
path: /xe/data/anubis/data.bdb
+
+## Honeypot configuration
+honeypot:
+ ## If not set, Anubis will assume you meant `true`.
+ enabled: true
+ ## Currently the only supported implementation is the naive method.
+ ## See https://anubis.techaro.lol/docs/admin/honeypot/overview#implementation-notes for more information
+ implementation: naive
+ ## Setting ip_log_file makes Anubis log IP addresses that hit honeypot URLs to a file.
+ ## Anubis writes to this file either once per minute or after Anubis records 32
+ ## kilobytes of IP addresses, whichever happens first.
+ #ip_log_file: ./var/honeypot.addrs
diff --git a/docs/static/img/sponsors/ddwrt-logo.webp b/docs/static/img/sponsors/ddwrt-logo.webp
new file mode 100644
index 0000000..dca6fa7
Binary files /dev/null and b/docs/static/img/sponsors/ddwrt-logo.webp differ
diff --git a/docs/static/img/sponsors/distrust-logo.webp b/docs/static/img/sponsors/distrust-logo.webp
deleted file mode 100644
index cda07e8..0000000
Binary files a/docs/static/img/sponsors/distrust-logo.webp and /dev/null differ
diff --git a/docs/static/img/sponsors/felsqualle-logo.webp b/docs/static/img/sponsors/felsqualle-logo.webp
new file mode 100644
index 0000000..522d217
Binary files /dev/null and b/docs/static/img/sponsors/felsqualle-logo.webp differ
diff --git a/docs/static/img/sponsors/qwertiko-logo.webp b/docs/static/img/sponsors/qwertiko-logo.webp
new file mode 100644
index 0000000..1e36ffd
Binary files /dev/null and b/docs/static/img/sponsors/qwertiko-logo.webp differ
diff --git a/docs/static/img/sponsors/spur-logo.webp b/docs/static/img/sponsors/spur-logo.webp
new file mode 100644
index 0000000..0a56303
Binary files /dev/null and b/docs/static/img/sponsors/spur-logo.webp differ
diff --git a/docs/static/img/sponsors/synthient-banner.webp b/docs/static/img/sponsors/synthient-banner.webp
new file mode 100644
index 0000000..0d6db6d
Binary files /dev/null and b/docs/static/img/sponsors/synthient-banner.webp differ
diff --git a/docs/static/img/sponsors/unipromos.webp b/docs/static/img/sponsors/unipromos.webp
new file mode 100644
index 0000000..c0a0213
Binary files /dev/null and b/docs/static/img/sponsors/unipromos.webp differ
diff --git a/docs/static/img/sponsors/uvensys.webp b/docs/static/img/sponsors/uvensys.webp
new file mode 100644
index 0000000..aaa641f
Binary files /dev/null and b/docs/static/img/sponsors/uvensys.webp differ
diff --git a/docs/static/img/sponsors/wenet-logo.webp b/docs/static/img/sponsors/wenet-logo.webp
new file mode 100644
index 0000000..39d35de
Binary files /dev/null and b/docs/static/img/sponsors/wenet-logo.webp differ
diff --git a/go.mod b/go.mod
index ac48abd..073e46e 100644
--- a/go.mod
+++ b/go.mod
@@ -1,83 +1,88 @@
module github.com/TecharoHQ/anubis
-go 1.24.2
+go 1.27.3
require (
- github.com/TecharoHQ/thoth-proto v0.5.0
- github.com/a-h/templ v0.3.960
- github.com/aws/aws-sdk-go-v2 v1.41.0
- github.com/aws/aws-sdk-go-v2/config v1.32.5
- github.com/aws/aws-sdk-go-v2/service/s3 v1.93.2
+ cel.dev/cel-go v0.32.0
+ github.com/a-h/templ v0.3.1070
+ github.com/aws/aws-sdk-go-v2 v1.47.1
+ github.com/aws/aws-sdk-go-v2/config v1.33.6
+ github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0
github.com/cespare/xxhash/v2 v2.3.0
github.com/facebookgo/flagenv v0.0.0-20160425205200-fcd59fca7456
github.com/fahedouch/go-logrotate v0.3.0
- github.com/gaissmai/bart v0.26.0
- github.com/golang-jwt/jwt/v5 v5.3.0
- github.com/google/cel-go v0.26.1
+ github.com/fvbommel/sortorder v1.2.0
+ github.com/gaissmai/bart v0.30.0
+ github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/uuid v1.6.0
- github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0
- github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3
+ github.com/goreleaser/fileglob v1.4.1
github.com/joho/godotenv v1.5.1
github.com/lum8rjack/go-ja4h v0.0.0-20250828030157-fa5266d50650
- github.com/nicksnyder/go-i18n/v2 v2.6.0
+ github.com/maxmind/geoipupdate/v8 v8.0.0
+ github.com/maxmind/mmdbwriter v1.2.0
+ github.com/mxschmitt/playwright-go v0.6201.1
+ github.com/neilotoole/slogt/v2 v2.0.0
+ github.com/nicksnyder/go-i18n/v2 v2.6.1
github.com/nikandfor/spintax v0.0.0-20181023094358-fc346b245bb3
- github.com/playwright-community/playwright-go v0.5200.1
- github.com/prometheus/client_golang v1.23.2
- github.com/redis/go-redis/v9 v9.17.2
+ github.com/oschwald/maxminddb-golang/v2 v2.7.0
+ github.com/prometheus/client_golang v1.24.1
+ github.com/redis/go-redis/v9 v9.22.0
github.com/sebest/xff v0.0.0-20210106013422-671bd2870b3a
- github.com/shirou/gopsutil/v4 v4.25.11
- github.com/testcontainers/testcontainers-go v0.40.0
- go.etcd.io/bbolt v1.4.3
- golang.org/x/net v0.48.0
- golang.org/x/text v0.32.0
- google.golang.org/grpc v1.77.0
+ github.com/shirou/gopsutil/v4 v4.26.9
+ github.com/testcontainers/testcontainers-go v0.44.0
+ github.com/tetratelabs/wazero v1.12.1-0.20260714071631-236c2458ed22
+ go.etcd.io/bbolt v1.5.0
+ golang.org/x/net v0.59.0
+ golang.org/x/sync v0.23.0
+ golang.org/x/sys v0.48.0
+ golang.org/x/text v0.42.0
+ google.golang.org/grpc v1.84.0
gopkg.in/yaml.v3 v3.0.1
- k8s.io/apimachinery v0.34.3
+ k8s.io/apimachinery v0.37.1
sigs.k8s.io/yaml v1.6.0
)
require (
al.essio.dev/pkg/shellescape v1.6.0 // indirect
- buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20251209175733-2a1774d88802.1 // indirect
- cel.dev/expr v0.25.1 // indirect
+ cel.dev/expr v0.25.3 // indirect
dario.cat/mergo v1.0.2 // indirect
github.com/AlekSi/pointer v1.2.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
- github.com/BurntSushi/toml v1.5.0 // indirect
+ github.com/BurntSushi/toml v1.6.0 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.4.0 // indirect
github.com/Masterminds/sprig/v3 v3.3.0 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
- github.com/ProtonMail/go-crypto v1.3.0 // indirect
- github.com/Songmu/gitconfig v0.2.1 // indirect
- github.com/TecharoHQ/yeet v0.6.3 // indirect
+ github.com/ProtonMail/go-crypto v1.4.1 // indirect
+ github.com/Songmu/gitconfig v0.2.2 // indirect
+ github.com/TecharoHQ/yeet v0.13.0 // indirect
+ github.com/Xe/erofs v0.6.1 // indirect
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e // indirect
- github.com/andybalholm/brotli v1.2.0 // indirect
+ github.com/andybalholm/brotli v1.2.6 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
- github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
- github.com/aws/aws-sdk-go-v2/credentials v1.19.5 // indirect
- github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 // indirect
- github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 // indirect
- github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 // indirect
- github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
- github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.16 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.7 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.16 // indirect
- github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 // indirect
- github.com/aws/aws-sdk-go-v2/service/sso v1.30.7 // indirect
- github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 // indirect
- github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 // indirect
- github.com/aws/smithy-go v1.24.0 // indirect
+ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect
+ github.com/aws/aws-sdk-go-v2/credentials v1.20.6 // indirect
+ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect
+ github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 // indirect
+ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 // indirect
+ github.com/aws/smithy-go v1.28.2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb // indirect
github.com/cavaliergopher/cpio v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cli/browser v1.3.0 // indirect
- github.com/cli/go-gh/v2 v2.12.1 // indirect
+ github.com/cli/go-gh/v2 v2.13.0 // indirect
github.com/cli/safeexec v1.0.1 // indirect
- github.com/cloudflare/circl v1.6.1 // indirect
+ github.com/cloudflare/circl v1.6.3 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
@@ -85,121 +90,115 @@ require (
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
github.com/cyphar/filepath-securejoin v0.4.1 // indirect
- github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/deckarep/golang-set/v2 v2.8.0 // indirect
- github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/djherbis/times v1.6.0 // indirect
github.com/dlclark/regexp2 v1.11.5 // indirect
- github.com/docker/docker v28.5.1+incompatible // indirect
- github.com/docker/go-connections v0.6.0 // indirect
+ github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dop251/goja v0.0.0-20250630131328-58d95d85e994 // indirect
- github.com/ebitengine/purego v0.9.1 // indirect
+ github.com/ebitengine/purego v0.11.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51 // indirect
github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect
github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870 // indirect
- github.com/fatih/color v1.18.0 // indirect
- github.com/felixge/httpsnoop v1.0.4 // indirect
- github.com/fsnotify/fsnotify v1.9.0 // indirect
+ github.com/fatih/color v1.19.0 // indirect
+ github.com/felixge/httpsnoop v1.1.0 // indirect
+ github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
- github.com/go-git/go-billy/v5 v5.6.2 // indirect
- github.com/go-git/go-git/v5 v5.16.2 // indirect
- github.com/go-jose/go-jose/v3 v3.0.4 // indirect
+ github.com/go-git/go-billy/v5 v5.7.0 // indirect
+ github.com/go-git/go-git/v5 v5.16.5 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/go-stack/stack v1.8.1 // indirect
github.com/gobwas/glob v0.2.3 // indirect
- github.com/goccy/go-yaml v1.18.0 // indirect
+ github.com/goccy/go-yaml v1.19.2 // indirect
+ github.com/gofrs/flock v0.13.1 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/google/go-github/v70 v70.0.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect
github.com/google/rpmpack v0.7.1 // indirect
- github.com/goreleaser/chglog v0.7.3 // indirect
- github.com/goreleaser/fileglob v1.3.0 // indirect
- github.com/goreleaser/nfpm/v2 v2.43.0 // indirect
+ github.com/goreleaser/chglog v0.7.4 // indirect
+ github.com/goreleaser/nfpm/v2 v2.45.2 // indirect
github.com/hashicorp/go-version v1.7.0 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
- github.com/klauspost/compress v1.18.0 // indirect
+ github.com/klauspost/compress v1.19.1 // indirect
github.com/klauspost/pgzip v1.2.6 // indirect
- github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect
+ github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
github.com/magiconair/properties v1.8.10 // indirect
- github.com/mattn/go-colorable v0.1.14 // indirect
- github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mattn/go-colorable v0.1.15 // indirect
+ github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
- github.com/moby/go-archive v0.1.0 // indirect
- github.com/moby/patternmatcher v0.6.0 // indirect
- github.com/moby/sys/sequential v0.6.0 // indirect
+ github.com/moby/go-archive v0.2.0 // indirect
+ github.com/moby/moby/api v1.55.0 // indirect
+ github.com/moby/moby/client v0.5.0 // indirect
+ github.com/moby/patternmatcher v0.6.1 // indirect
+ github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
- github.com/morikuni/aec v1.0.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/natefinch/atomic v1.0.1 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
+ github.com/pierrec/lz4/v4 v4.1.26 // indirect
github.com/pjbgf/sha1cd v0.4.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
- github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
- github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
- github.com/prometheus/client_model v0.6.2 // indirect
- github.com/prometheus/common v0.67.4 // indirect
- github.com/prometheus/procfs v0.19.2 // indirect
+ github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
+ github.com/prometheus/client_model v0.6.3 // indirect
+ github.com/prometheus/common v0.72.0 // indirect
+ github.com/prometheus/procfs v0.22.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
- github.com/sirupsen/logrus v1.9.3 // indirect
+ github.com/sirupsen/logrus v1.9.4 // indirect
github.com/skeema/knownhosts v1.3.1 // indirect
- github.com/spf13/afero v1.14.0 // indirect
- github.com/spf13/cast v1.9.2 // indirect
- github.com/stoewer/go-strcase v1.3.1 // indirect
- github.com/stretchr/testify v1.11.1 // indirect
+ github.com/spf13/afero v1.15.0 // indirect
+ github.com/spf13/cast v1.10.0 // indirect
+ github.com/stretchr/testify v1.12.1 // indirect
github.com/suzuki-shunsuke/logrus-error v0.1.4 // indirect
github.com/suzuki-shunsuke/pinact v1.6.0 // indirect
github.com/suzuki-shunsuke/urfave-cli-help-all v0.0.4 // indirect
- github.com/tklauser/go-sysconf v0.3.16 // indirect
- github.com/tklauser/numcpus v0.11.0 // indirect
- github.com/ulikunitz/xz v0.5.14 // indirect
+ github.com/tklauser/go-sysconf v0.4.0 // indirect
+ github.com/tklauser/numcpus v0.12.0 // indirect
+ github.com/ulikunitz/xz v0.5.15 // indirect
github.com/urfave/cli/v2 v2.27.7 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
gitlab.com/digitalxero/go-conventional-commit v1.0.7 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
- go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 // indirect
- go.opentelemetry.io/otel v1.38.0 // indirect
- go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 // indirect
- go.opentelemetry.io/otel/metric v1.38.0 // indirect
- go.opentelemetry.io/otel/trace v1.38.0 // indirect
- go.opentelemetry.io/proto/otlp v1.7.0 // indirect
- go.yaml.in/yaml/v2 v2.4.3 // indirect
- go.yaml.in/yaml/v3 v3.0.4 // indirect
- golang.org/x/crypto v0.46.0 // indirect
- golang.org/x/exp v0.0.0-20251209150349-8475f28825e9 // indirect
+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect
+ go.opentelemetry.io/otel v1.44.0 // indirect
+ go.opentelemetry.io/otel/metric v1.44.0 // indirect
+ go.opentelemetry.io/otel/trace v1.44.0 // indirect
+ go.uber.org/atomic v1.12.0 // indirect
+ go.yaml.in/yaml/v2 v2.4.4 // indirect
+ go.yaml.in/yaml/v3 v3.0.5 // indirect
+ go4.org/netipx v0.0.0-20260823151212-3075585bcbeb // indirect
+ golang.org/x/crypto v0.57.0 // indirect
+ golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect
golang.org/x/exp/typeparams v0.0.0-20250718183923-645b1fa84792 // indirect
- golang.org/x/mod v0.31.0 // indirect
- golang.org/x/oauth2 v0.32.0 // indirect
- golang.org/x/sync v0.19.0 // indirect
- golang.org/x/sys v0.39.0 // indirect
- golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc // indirect
- golang.org/x/term v0.38.0 // indirect
- golang.org/x/tools v0.40.0 // indirect
+ golang.org/x/mod v0.41.0 // indirect
+ golang.org/x/oauth2 v0.37.0 // indirect
+ golang.org/x/telemetry v0.0.0-20260924152758-ed294f943157 // indirect
+ golang.org/x/term v0.46.0 // indirect
+ golang.org/x/tools v0.51.0 // indirect
golang.org/x/vuln v1.1.4 // indirect
- google.golang.org/genproto/googleapis/api v0.0.0-20251213004720-97cd9d5aeac2 // indirect
- google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2 // indirect
- google.golang.org/protobuf v1.36.11 // indirect
+ google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
+ google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
- honnef.co/go/tools v0.6.1 // indirect
- mvdan.cc/sh/v3 v3.12.0 // indirect
- sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
+ honnef.co/go/tools v0.8.1 // indirect
+ mvdan.cc/sh/v3 v3.13.0 // indirect
+ sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5 // indirect
)
tool (
diff --git a/go.sum b/go.sum
index e8a4615..aea210b 100644
--- a/go.sum
+++ b/go.sum
@@ -1,9 +1,9 @@
al.essio.dev/pkg/shellescape v1.6.0 h1:NxFcEqzFSEVCGN2yq7Huv/9hyCEGVa/TncnOOBBeXHA=
al.essio.dev/pkg/shellescape v1.6.0/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890=
-buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20251209175733-2a1774d88802.1 h1:j9yeqTWEFrtimt8Nng2MIeRrpoCvQzM9/g25XTvqUGg=
-buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20251209175733-2a1774d88802.1/go.mod h1:tvtbpgaVXZX4g6Pn+AnzFycuRK3MOz5HJfEGeEllXYM=
-cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
-cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
+cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
+cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
+cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
+cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
@@ -12,10 +12,13 @@ github.com/AlekSi/pointer v1.2.0 h1:glcy/gc4h8HnG2Z3ZECSzZ1IX1x2JxRVuDzaJwQE0+w=
github.com/AlekSi/pointer v1.2.0/go.mod h1:gZGfd3dpW4vEc/UlyfKKi1roIqcCgwOIvb0tSNSBle0=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
-github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
-github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
+github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
+github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/DataDog/zstd v1.5.5 h1:oWf5W7GtOLgp6bciQYDmhHHjdhYkALu6S/5Ni9ZgSvQ=
github.com/DataDog/zstd v1.5.5/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw=
+github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
+github.com/MakeNowJust/heredoc/v2 v2.0.1 h1:rlCHh70XXXv7toz95ajQWOWQnN4WNLt0TdpZYIR/J6A=
+github.com/MakeNowJust/heredoc/v2 v2.0.1/go.mod h1:6/2Abh5s+hc3g9nbWLe9ObDIOhaRrqsyY9MWy+4JdRM=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
@@ -25,70 +28,68 @@ github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSC
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
-github.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBiRGFrw=
-github.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE=
+github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
+github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
github.com/ProtonMail/go-mime v0.0.0-20230322103455-7d82a3887f2f h1:tCbYj7/299ekTTXpdwKYF8eBlsYsDVoggDAuAjoK66k=
github.com/ProtonMail/go-mime v0.0.0-20230322103455-7d82a3887f2f/go.mod h1:gcr0kNtGBqin9zDW9GOHcVntrwnjrK+qdJ06mWYBybw=
github.com/ProtonMail/gopenpgp/v2 v2.7.1 h1:Awsg7MPc2gD3I7IFac2qE3Gdls0lZW8SzrFZ3k1oz0s=
github.com/ProtonMail/gopenpgp/v2 v2.7.1/go.mod h1:/BU5gfAVwqyd8EfC3Eu7zmuhwYQpKs+cGD8M//iiaxs=
-github.com/ProtonMail/gopenpgp/v3 v3.3.0 h1:N6rHCH5PWwB6zSRMgRj1EbAMQHUAAHxH3Oo4KibsPwY=
-github.com/ProtonMail/gopenpgp/v3 v3.3.0/go.mod h1:J+iNPt0/5EO9wRt7Eit9dRUlzyu3hiGX3zId6iuaKOk=
-github.com/Songmu/gitconfig v0.2.1 h1:cZsqELfMtxWVI8ovq17gbvsR4qLfoYLAiXy5GwtJWbk=
-github.com/Songmu/gitconfig v0.2.1/go.mod h1:XM4O3SoXFnli9Ql2G7qXK2Fg7LJwf7Hs8GLFEOJlzmM=
-github.com/TecharoHQ/thoth-proto v0.5.0 h1:Fa663s4soYiURSU8MfW9tZ2wF+LsCRSaYmjUSyagfBM=
-github.com/TecharoHQ/thoth-proto v0.5.0/go.mod h1:C/U7FqTxpVn4V/qebC/GcW32I0h9xzsmWehF27KFOJs=
-github.com/TecharoHQ/yeet v0.6.3 h1:Iev6TYt/tpFYU73kbkNIYjCObYTvlihtby+htGF4Us8=
-github.com/TecharoHQ/yeet v0.6.3/go.mod h1:ltt+PWPjnvmQJxEHsdJ5K9u3GoWK83vSLWCCp8XbxqI=
+github.com/ProtonMail/gopenpgp/v3 v3.4.0 h1:WW0VK+mZjbu5SqhWNm58TYKFxyvduiUHTfyIKs60dgY=
+github.com/ProtonMail/gopenpgp/v3 v3.4.0/go.mod h1:bGdV9f6edhmd581wzXsQCTKdH8bXBbyhkgDKPjwPc6U=
+github.com/Songmu/gitconfig v0.2.2 h1:tiQY2KZqgdgjs1C7slWd31EB8NbItN7BOKxCIHSlK4Y=
+github.com/Songmu/gitconfig v0.2.2/go.mod h1:lZ0lKL6K+xvT+QzmmGxHQgOnneiWcbhGAV2DKI6PBpM=
+github.com/TecharoHQ/yeet v0.13.0 h1:D2abkqBfTgSWvgncU1+gpu6lhtT30b5o6WNl0BLGl18=
+github.com/TecharoHQ/yeet v0.13.0/go.mod h1:MTiaBq+wFrINPgpW22p1DZ7B68TfiLfsxsQ8Md5BVS0=
+github.com/Xe/erofs v0.6.1 h1:GnrHZ+dxAQG9+Gy+hI06ANT9X8CA79uDwbaZqNad4bU=
+github.com/Xe/erofs v0.6.1/go.mod h1:GGxvJkCKU4yKfJ+Trap2xC8iN0HGuTUEsD5oz+olLJI=
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e h1:HjVbSQHy+dnlS6C3XajZ69NYAb5jbGNfHanvm1+iYlo=
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ=
-github.com/a-h/templ v0.3.960 h1:trshEpGa8clF5cdI39iY4ZrZG8Z/QixyzEyUnA7feTM=
-github.com/a-h/templ v0.3.960/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
-github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
-github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
+github.com/a-h/templ v0.3.1070 h1:3iCOXHXqFXa99OQzgkUOLJbNzv/QjFGLwKZkBAg+ADA=
+github.com/a-h/templ v0.3.1070/go.mod h1:iIqB3g2RHBe/WlnPwa+Bvhh1TKXHWLRnBD9NWHOLm78=
+github.com/andybalholm/brotli v1.2.6 h1:ftYnfj6usCp+UGV5kSJ3+chpMQgU+gJf/AxsUQ52REI=
+github.com/andybalholm/brotli v1.2.6/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
-github.com/aws/aws-sdk-go-v2 v1.41.0 h1:tNvqh1s+v0vFYdA1xq0aOJH+Y5cRyZ5upu6roPgPKd4=
-github.com/aws/aws-sdk-go-v2 v1.41.0/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
-github.com/aws/aws-sdk-go-v2/config v1.32.5 h1:pz3duhAfUgnxbtVhIK39PGF/AHYyrzGEyRD9Og0QrE8=
-github.com/aws/aws-sdk-go-v2/config v1.32.5/go.mod h1:xmDjzSUs/d0BB7ClzYPAZMmgQdrodNjPPhd6bGASwoE=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.5 h1:xMo63RlqP3ZZydpJDMBsH9uJ10hgHYfQFIk1cHDXrR4=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.5/go.mod h1:hhbH6oRcou+LpXfA/0vPElh/e0M3aFeOblE1sssAAEk=
-github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 h1:80+uETIWS1BqjnN9uJ0dBUaETh+P1XwFy5vwHwK5r9k=
-github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16/go.mod h1:wOOsYuxYuB/7FlnVtzeBYRcjSRtQpAW0hCP7tIULMwo=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 h1:rgGwPzb82iBYSvHMHXc8h9mRoOUBZIGFgKb9qniaZZc=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16/go.mod h1:L/UxsGeKpGoIj6DxfhOWHWQ/kGKcd4I1VncE4++IyKA=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 h1:1jtGzuV7c82xnqOVfx2F0xmJcOw5374L7N6juGW6x6U=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16/go.mod h1:M2E5OQf+XLe+SZGmmpaI2yy+J326aFf6/+54PoxSANc=
-github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
-github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.16 h1:CjMzUs78RDDv4ROu3JnJn/Ig1r6ZD7/T2DXLLRpejic=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.16/go.mod h1:uVW4OLBqbJXSHJYA9svT9BluSvvwbzLQ2Crf6UPzR3c=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.7 h1:DIBqIrJ7hv+e4CmIk2z3pyKT+3B6qVMgRsawHiR3qso=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.7/go.mod h1:vLm00xmBke75UmpNvOcZQ/Q30ZFjbczeLFqGx5urmGo=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 h1:oHjJHeUy0ImIV0bsrX0X91GkV5nJAyv1l1CC9lnO0TI=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16/go.mod h1:iRSNGgOYmiYwSCXxXaKb9HfOEj40+oTKn8pTxMlYkRM=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.16 h1:NSbvS17MlI2lurYgXnCOLvCFX38sBW4eiVER7+kkgsU=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.16/go.mod h1:SwT8Tmqd4sA6G1qaGdzWCJN99bUmPGHfRwwq3G5Qb+A=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.93.2 h1:U3ygWUhCpiSPYSHOrRhb3gOl9T5Y3kB8k5Vjs//57bE=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.93.2/go.mod h1:79S2BdqCJpScXZA2y+cpZuocWsjGjJINyXnOsf5DTz8=
-github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 h1:HpI7aMmJ+mm1wkSHIA2t5EaFFv5EFYXePW30p1EIrbQ=
-github.com/aws/aws-sdk-go-v2/service/signin v1.0.4/go.mod h1:C5RdGMYGlfM0gYq/tifqgn4EbyX99V15P2V3R+VHbQU=
-github.com/aws/aws-sdk-go-v2/service/sso v1.30.7 h1:eYnlt6QxnFINKzwxP5/Ucs1vkG7VT3Iezmvfgc2waUw=
-github.com/aws/aws-sdk-go-v2/service/sso v1.30.7/go.mod h1:+fWt2UHSb4kS7Pu8y+BMBvJF0EWx+4H0hzNwtDNRTrg=
-github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 h1:AHDr0DaHIAo8c9t1emrzAlVDFp+iMMKnPdYy6XO4MCE=
-github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12/go.mod h1:GQ73XawFFiWxyWXMHWfhiomvP3tXtdNar/fi8z18sx0=
-github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 h1:SciGFVNZ4mHdm7gpD1dgZYnCuVdX1s+lFTg4+4DOy70=
-github.com/aws/aws-sdk-go-v2/service/sts v1.41.5/go.mod h1:iW40X4QBmUxdP+fZNOpfmkdMZqsovezbAeO+Ubiv2pk=
-github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=
-github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
+github.com/aws/aws-sdk-go-v2 v1.47.1 h1:uOIZnp4PK3ZhKI0dNrJrhTEsLxbpXHTAJlwoS1pvAtw=
+github.com/aws/aws-sdk-go-v2 v1.47.1/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8=
+github.com/aws/aws-sdk-go-v2/config v1.33.6 h1:MBjkSTLczek/UgiK+EYPIoRTqE7gP8vtW3OFbFo7Nug=
+github.com/aws/aws-sdk-go-v2/config v1.33.6/go.mod h1:grRAFzdAZJrwcbasJRg2MPvIrVjtlfXllHssN6+E1JE=
+github.com/aws/aws-sdk-go-v2/credentials v1.20.6 h1:NpAFXCU7NzXNkdGK3zQTtsRJ+3v9tZQV0xcdRw8uBdw=
+github.com/aws/aws-sdk-go-v2/credentials v1.20.6/go.mod h1:mcZCoiPnyMvP8VMNbygNX5lLqSlkYJIMPODylQMurOk=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 h1:8gALAAmacnIXh+z6VkdDanv4/IkG5APdg4DZLDTmLog=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1/go.mod h1:Z7IJhJU+poOdJjUR2wpyY21ossQ1XS/R3Lk9Msq5kM4=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4=
+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8=
+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek=
+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs=
+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 h1:VMAdYqr4Jn/8ATs9BHC5riwrs0d6m1Z2ohFriSwZwm0=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0/go.mod h1:9APRWGLFITKD+xzWSIyT9V7QV4bNlEuIieWlzXgGFlI=
+github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 h1:DzCCWLzcIRQ77F3DEUljud7bEjTgFOIKXP52NmVRyhU=
+github.com/aws/aws-sdk-go-v2/service/signin v1.10.1/go.mod h1:xpo/geVldu8payT375WekctUzopG/hBU7miiqItMUlw=
+github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 h1:Umtl/0YZhng4xndfW3lKJrYYP7NLEjI6bGXVomwLcs0=
+github.com/aws/aws-sdk-go-v2/service/sso v1.38.1/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/SBzUUymbUQuZbSPImghg=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ=
+github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 h1:0HOqZXRvMytH6bFHVIc0oJX07sZjfhz0zXtjs6gdE8s=
+github.com/aws/aws-sdk-go-v2/service/sts v1.51.1/go.mod h1:26zA0GhDrLo+yiLI2yXWxqB1PdsShfLikoI7GOEgugM=
+github.com/aws/smithy-go v1.28.2 h1:myhcykQcatTul2B/zITjDk203G7t0awUAs1hVry5Bvg=
+github.com/aws/smithy-go v1.28.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb h1:m935MPodAbYS46DG4pJSv7WO+VECIWUQ7OJYSoTrMh4=
@@ -109,12 +110,12 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo=
github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk=
-github.com/cli/go-gh/v2 v2.12.1 h1:SVt1/afj5FRAythyMV3WJKaUfDNsxXTIe7arZbwTWKA=
-github.com/cli/go-gh/v2 v2.12.1/go.mod h1:+5aXmEOJsH9fc9mBHfincDwnS02j2AIA/DsTH0Bk5uw=
+github.com/cli/go-gh/v2 v2.13.0 h1:jEHZu/VPVoIJkciK3pzZd3rbT8J90swsK5Ui4ewH1ys=
+github.com/cli/go-gh/v2 v2.13.0/go.mod h1:Us/NbQ8VNM0fdaILgoXSz6PKkV5PWaEzkJdc9vR2geM=
github.com/cli/safeexec v1.0.1 h1:e/C79PbXF4yYTN/wauC4tviMxEV13BwljGj0N9j+N00=
github.com/cli/safeexec v1.0.1/go.mod h1:Z/D4tTN8Vs5gXYHDCbaM1S/anmEDnJb1iW0+EJ5zx3Q=
-github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=
-github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
+github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
+github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
@@ -137,24 +138,20 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deckarep/golang-set/v2 v2.8.0 h1:swm0rlPCmdWn9mESxKOjWk8hXSqoxOp+ZlfuyaAdFlQ=
github.com/deckarep/golang-set/v2 v2.8.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4=
-github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
-github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
-github.com/docker/docker v28.5.1+incompatible h1:Bm8DchhSD2J6PsFzxC35TZo4TLGR2PdW/E69rU45NhM=
-github.com/docker/docker v28.5.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
-github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94=
-github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
+github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
+github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dop251/goja v0.0.0-20250630131328-58d95d85e994 h1:aQYWswi+hRL2zJqGacdCZx32XjKYV8ApXFGntw79XAM=
github.com/dop251/goja v0.0.0-20250630131328-58d95d85e994/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4=
-github.com/ebitengine/purego v0.9.1 h1:a/k2f2HQU3Pi399RPW1MOaZyhKJL9w/xFpKAg4q1s0A=
-github.com/ebitengine/purego v0.9.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
+github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
+github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
@@ -169,28 +166,28 @@ github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870 h1:E2s37DuLxFhQD
github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0=
github.com/fahedouch/go-logrotate v0.3.0 h1:XP+dHIDgWZ1ckz43mG6gl5ASer3PZDVr755SVMyzaUQ=
github.com/fahedouch/go-logrotate v0.3.0/go.mod h1:X49m0bvPLkk71MHNCQ1yEfVEw8W/u+qvHa/hOnhCYf4=
-github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
-github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
-github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
-github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
+github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
+github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
+github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
+github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
-github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
-github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
-github.com/gaissmai/bart v0.26.0 h1:xOZ57E9hJLBiQaSyeZa9wgWhGuzfGACgqp4BE77OkO0=
-github.com/gaissmai/bart v0.26.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
+github.com/fvbommel/sortorder v1.2.0 h1:TRIiRiGX+djh3Yf4FVxmWmAcYfIr5dH0NbzJWOSAWZk=
+github.com/fvbommel/sortorder v1.2.0/go.mod h1:LbhO04ijZIeUuvz9B9BkI/qYrpZZEn1gWhxv4QjUKVs=
+github.com/gaissmai/bart v0.30.0 h1:K1oTSQ6Nf76bhrgxeTqzZa4hE0M9x4xDfL6n6UG67Sc=
+github.com/gaissmai/bart v0.30.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
-github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
-github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
+github.com/go-git/go-billy/v5 v5.7.0 h1:83lBUJhGWhYp0ngzCMSgllhUSuoHP1iEWYjsPl9nwqM=
+github.com/go-git/go-billy/v5 v5.7.0/go.mod h1:/1IUejTKH8xipsAcdfcSAlUlo2J7lkYV8GTKxAT/L3E=
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
-github.com/go-git/go-git/v5 v5.16.2 h1:fT6ZIOjE5iEnkzKyxTHK1W4HGAsPhqEqiSAssSO77hM=
-github.com/go-git/go-git/v5 v5.16.2/go.mod h1:4Ge4alE/5gPs30F2H1esi2gPd69R0C39lolkucHBOp8=
-github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY=
-github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
+github.com/go-git/go-git/v5 v5.16.5 h1:mdkuqblwr57kVfXri5TTH+nMFLNUxIj9Z7F5ykFbw5s=
+github.com/go-git/go-git/v5 v5.16.5/go.mod h1:QOMLpNf1qxuSY4StA/ArOdfFR2TrKEjJiye2kel2m+M=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
@@ -207,20 +204,19 @@ github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw=
github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
-github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
-github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
-github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
-github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
+github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
+github.com/gofrs/flock v0.13.1 h1:jjREztyBeSKBZYAC+mgc1laB+xsgy4kYMf3FbKF2UBo=
+github.com/gofrs/flock v0.13.1/go.mod h1:sf4BFiHwnvgxa25DlQoDqXQnwRMEOwqxRq37P6MzzmE=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
-github.com/google/cel-go v0.26.1 h1:iPbVVEdkhTX++hpe3lzSk7D3G3QSYqLGoHOcEio+UXQ=
-github.com/google/cel-go v0.26.1/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM=
github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RAtvaGgKxc+8FQIpxHgsF+HBzPyYL2cyVU=
github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
-github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-github/v70 v70.0.0 h1:/tqCp5KPrcvqCc7vIvYyFYTiCGrYvaWoYMGHSQbo55o=
@@ -239,18 +235,12 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g=
github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k=
-github.com/goreleaser/chglog v0.7.3 h1:eCKJrvsDgG+F1F2fhwM6qX+S5yMiZgsQ4VNTPFl9qEM=
-github.com/goreleaser/chglog v0.7.3/go.mod h1:HXPf4avc1kTD00a46LuTEH0i1dZctLq8Xs2BxUfROnY=
-github.com/goreleaser/fileglob v1.3.0 h1:/X6J7U8lbDpQtBvGcwwPS6OpzkNVlVEsFUVRx9+k+7I=
-github.com/goreleaser/fileglob v1.3.0/go.mod h1:Jx6BoXv3mbYkEzwm9THo7xbr5egkAraxkGorbJb4RxU=
-github.com/goreleaser/nfpm/v2 v2.43.0 h1:o5oureuZkhu55RK0M9WSN8JLW7hu6MymtMh7LypInlk=
-github.com/goreleaser/nfpm/v2 v2.43.0/go.mod h1:f//PE8PjNHjaPCbd7Jkok+aPKdLTrzM+fuIWg3PfVRg=
-github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 h1:QGLs/O40yoNK9vmy4rhUGBVyMf1lISBGtXRpsu/Qu/o=
-github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0/go.mod h1:hM2alZsMUni80N33RBe6J0e423LB+odMj7d3EMP9l20=
-github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 h1:B+8ClL/kCQkRiU82d9xajRPKYMrB7E0MbtzWVi1K4ns=
-github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3/go.mod h1:NbCUVmiS4foBGBHOYlCT25+YmGpJ32dZPi75pGEUpj4=
-github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=
-github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=
+github.com/goreleaser/chglog v0.7.4 h1:3pnNt/XCrUcAOq+KC91Azlgp5CRv4GHo1nl8Aws7OzI=
+github.com/goreleaser/chglog v0.7.4/go.mod h1:dTVoZZagTz7hHdWaZ9OshHntKiF44HbWIHWxYJQ/h0Y=
+github.com/goreleaser/fileglob v1.4.1 h1:4/SXlDDzfKCorA28/S3aXd/6D8VHDZjGXGIttVSjxhU=
+github.com/goreleaser/fileglob v1.4.1/go.mod h1:1pbHx7hhmJIxNZvm6fi6WVrnP0tndq6p3ayWdLn1Yf8=
+github.com/goreleaser/nfpm/v2 v2.45.2 h1:sWBXUErMSKHMvT8f1mgtY3yn2jbNBAE2TNBXNXpSDGc=
+github.com/goreleaser/nfpm/v2 v2.45.2/go.mod h1:NxYAJCKAuq8NpL57WvL39xIK39/1jViS9hD6MDwKTgw=
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
@@ -265,8 +255,10 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kjk/lzma v0.0.0-20161016003348-3fd93898850d h1:RnWZeH8N8KXfbwMTex/KKMYMj0FJRCF6tQubUuQ02GM=
github.com/kjk/lzma v0.0.0-20161016003348-3fd93898850d/go.mod h1:phT/jsRPBAEqjAibu1BurrabCBNTYiVI+zbmyCZJY6Q=
-github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
-github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
+github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
+github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
+github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
+github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU=
github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@@ -278,77 +270,85 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
-github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc=
-github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
+github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak=
+github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/lum8rjack/go-ja4h v0.0.0-20250828030157-fa5266d50650 h1:hhx/Mo6+Hk0mAQS5MW311ON1VlSzp0D1cYhY27IcmnI=
github.com/lum8rjack/go-ja4h v0.0.0-20250828030157-fa5266d50650/go.mod h1:bMqyXOakqQIdx82d4vcnk5TIZLptZ2gLqju9xmPrWYA=
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
-github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE=
-github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
-github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
-github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
+github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
+github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
+github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
+github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
+github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
+github.com/maxmind/geoipupdate/v8 v8.0.0 h1:pmn0hUZG5KI9rjV9m0b4QfAjDJWUAsVOfFImIRK0kSE=
+github.com/maxmind/geoipupdate/v8 v8.0.0/go.mod h1:sRxLDTqnJg9Wal4fjWKb/HhIWyt/D9kBodte0xruYL8=
+github.com/maxmind/mmdbwriter v1.2.0 h1:hyvDopImmgvle3aR8AaddxXnT0iQH2KWJX3vNfkwzYM=
+github.com/maxmind/mmdbwriter v1.2.0/go.mod h1:EQmKHhk2y9DRVvyNxwCLKC5FrkXZLx4snc5OlLY5XLE=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
-github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=
-github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
-github.com/moby/go-archive v0.1.0 h1:Kk/5rdW/g+H8NHdJW2gsXyZ7UnzvJNOy6VKJqueWdcQ=
-github.com/moby/go-archive v0.1.0/go.mod h1:G9B+YoujNohJmrIYFBpSd54GTUB4lt9S+xVQvsJyFuo=
-github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk=
-github.com/moby/patternmatcher v0.6.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
-github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw=
-github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs=
-github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=
-github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=
+github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=
+github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=
+github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
+github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
+github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc=
+github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s=
+github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=
+github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
+github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
+github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs=
github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=
github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g=
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
-github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
-github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
+github.com/mxschmitt/playwright-go v0.6201.1 h1:KBBDopE+IIdjAp2FIk6zhLcKCCSSx/T6rGjKZmfo/Bs=
+github.com/mxschmitt/playwright-go v0.6201.1/go.mod h1:vLBP2yVO1gokUlb9ENA+YE3VQaVqf2A9BGxcb7aPjMI=
github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
-github.com/nicksnyder/go-i18n/v2 v2.6.0 h1:C/m2NNWNiTB6SK4Ao8df5EWm3JETSTIGNXBpMJTxzxQ=
-github.com/nicksnyder/go-i18n/v2 v2.6.0/go.mod h1:88sRqr0C6OPyJn0/KRNaEz1uWorjxIKP7rUUcvycecE=
+github.com/neilotoole/slogt/v2 v2.0.0 h1:Kz8VWdkjXZnkVvN1hsGYI1ervWhlcDcIcVizUJbLbH8=
+github.com/neilotoole/slogt/v2 v2.0.0/go.mod h1:M/RN37tAuM3cpb/wD6lCpOSvphLMjuAzA/IV2hqJh3E=
+github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
+github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
github.com/nikandfor/spintax v0.0.0-20181023094358-fc346b245bb3 h1:foZ9X1bz2KmW7b8Yx5V0LAQKhTazdllv5rnGUe6iGTY=
github.com/nikandfor/spintax v0.0.0-20181023094358-fc346b245bb3/go.mod h1:wwDYKfVF3WHdY0rugsAZoIpyQjDA3bn9wEzo/QXPx1Y=
-github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4=
-github.com/onsi/gomega v1.35.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog=
+github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k=
+github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
+github.com/oschwald/maxminddb-golang/v2 v2.7.0 h1:ZcAr3GYc2LYC8aec2mCMX9+QOF0EolH3jDFKRV/Z1+U=
+github.com/oschwald/maxminddb-golang/v2 v2.7.0/go.mod h1:DuKJLbbug6TXC0yJXgs1MWifvXHmudRWzMobMIUu04g=
+github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=
+github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pjbgf/sha1cd v0.4.0 h1:NXzbL1RvjTUi6kgYZCX3fPwwl27Q1LJndxtUDVfJGRY=
github.com/pjbgf/sha1cd v0.4.0/go.mod h1:zQWigSxVmsHEZow5qaLtPYxpcKMMQpa09ixqBxuCS6A=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/playwright-community/playwright-go v0.5200.1 h1:Sm2oOuhqt0M5Y4kUi/Qh9w4cyyi3ZIWTBeGKImc2UVo=
-github.com/playwright-community/playwright-go v0.5200.1/go.mod h1:UnnyQZaqUOO5ywAZu60+N4EiWReUqX1MQBBA3Oofvf8=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
-github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
-github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
-github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
-github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
-github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
-github.com/prometheus/common v0.67.4 h1:yR3NqWO1/UyO1w2PhUvXlGQs/PtFmoveVO0KZ4+Lvsc=
-github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI=
-github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
-github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
-github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
-github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
+github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 h1:XA01Vk/wv9YikCi1V51yRzIHPMT5of9+cMpZoZvDn/M=
+github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
+github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
+github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
+github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
+github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
+github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4=
+github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk=
+github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics=
+github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
+github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
+github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
@@ -359,52 +359,46 @@ github.com/sebest/xff v0.0.0-20210106013422-671bd2870b3a h1:iLcLb5Fwwz7g/DLK89F+
github.com/sebest/xff v0.0.0-20210106013422-671bd2870b3a/go.mod h1:wozgYq9WEBQBaIJe4YZ0qTSFAMxmcwBhQH0fO0R34Z0=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
-github.com/shirou/gopsutil/v4 v4.25.11 h1:X53gB7muL9Gnwwo2evPSE+SfOrltMoR6V3xJAXZILTY=
-github.com/shirou/gopsutil/v4 v4.25.11/go.mod h1:EivAfP5x2EhLp2ovdpKSozecVXn1TmuG7SMzs/Wh4PU=
+github.com/shirou/gopsutil/v4 v4.26.9 h1:CaBo/hBFqvlJoLvAQEKdHdf5GD97/MN2ACfyv63+2Ig=
+github.com/shirou/gopsutil/v4 v4.26.9/go.mod h1:nKH+8wX2zxr/mDbsR+AAy6Qd2z4ZOQ7wfQaEp+yrYmg=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
-github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
-github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY=
github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec=
github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY=
github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60=
-github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
-github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
-github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE=
-github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
-github.com/stoewer/go-strcase v1.3.1 h1:iS0MdW+kVTxgMoE1LAZyMiYJFKlOzLooE4MxjirtkAs=
-github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo=
+github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
+github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
-github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
-github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
-github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
+github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
-github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
-github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
-github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/suzuki-shunsuke/logrus-error v0.1.4 h1:nWo98uba1fANHdZ9Y5pJ2RKs/PpVjrLzRp5m+mRb9KE=
github.com/suzuki-shunsuke/logrus-error v0.1.4/go.mod h1:WsVvvw6SKSt08/fB2qbnsKIMJA4K1MYCUprqsBJbMiM=
github.com/suzuki-shunsuke/pinact v1.6.0 h1:2QvSzREOquwLwKXhF9Hj0AInE/Rl63SZz9dKkHFC6so=
github.com/suzuki-shunsuke/pinact v1.6.0/go.mod h1:FDUMck0mmL0mcnNZ23Vjh/aOR5cIdZhF1IIpGksT4dQ=
github.com/suzuki-shunsuke/urfave-cli-help-all v0.0.4 h1:YGHgrVjGTYHY98II6zijXUHP+OyvrzSCvd8m9iUcaK8=
github.com/suzuki-shunsuke/urfave-cli-help-all v0.0.4/go.mod h1:sSi6xaUaHfaqu32ECLeyE7NTMv+ZM5dW0JikhllaalY=
-github.com/testcontainers/testcontainers-go v0.40.0 h1:pSdJYLOVgLE8YdUY2FHQ1Fxu+aMnb6JfVz1mxk7OeMU=
-github.com/testcontainers/testcontainers-go v0.40.0/go.mod h1:FSXV5KQtX2HAMlm7U3APNyLkkap35zNLxukw9oBi/MY=
-github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=
-github.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=
-github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=
-github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=
-github.com/ulikunitz/xz v0.5.14 h1:uv/0Bq533iFdnMHZdRBTOlaNMdb1+ZxXIlHDZHIHcvg=
-github.com/ulikunitz/xz v0.5.14/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
+github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=
+github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=
+github.com/tetratelabs/wazero v1.12.1-0.20260714071631-236c2458ed22 h1:TnM7no4lj5GodEnEBnB3iR1MHf+BpGH88LPhs2Hhs80=
+github.com/tetratelabs/wazero v1.12.1-0.20260714071631-236c2458ed22/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
+github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
+github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
+github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
+github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
+github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
+github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU=
github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4=
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
@@ -415,69 +409,56 @@ github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 h1:FnBeRrxr7OU4VvAz
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
-github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
+gitlab.alpinelinux.org/alpine/go v0.10.1 h1:QoidnfDyC9yeIMj+CvYVyjlroZD/Kl7JRXGEQBvY5XM=
+gitlab.alpinelinux.org/alpine/go v0.10.1/go.mod h1:zwds+1zTmPDgwf/9lOzzn+oZVBr6jyfVgH3zuwkfkzc=
gitlab.com/digitalxero/go-conventional-commit v1.0.7 h1:8/dO6WWG+98PMhlZowt/YjuiKhqhGlOCwlIV8SqqGh8=
gitlab.com/digitalxero/go-conventional-commit v1.0.7/go.mod h1:05Xc2BFsSyC5tKhK0y+P3bs0AwUtNuTp+mTpbCU/DZ0=
-go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
-go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
+go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
+go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
-go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU=
-go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY=
-go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
-go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 h1:Ahq7pZmv87yiyn3jeFz/LekZmPLLdKejuO3NcK9MssM=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0/go.mod h1:MJTqhM0im3mRLw1i8uGHnCvUEeS7VwRyxlLC78PA18M=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 h1:IeMeyr1aBvBiPVYihXIaeIZba6b8E1bYp7lbdxK8CQg=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0/go.mod h1:oVdCUtjq9MK9BlS7TtucsQwUcXcymNiEDjgDD2jMtZU=
-go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
-go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
-go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
-go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
-go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
-go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
-go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
-go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
-go.opentelemetry.io/proto/otlp v1.7.0 h1:jX1VolD6nHuFzOYso2E73H85i92Mv8JQYk0K9vz09os=
-go.opentelemetry.io/proto/otlp v1.7.0/go.mod h1:fSKjH6YJ7HDlwzltzyMj036AJ3ejJLCgCSHGj4efDDo=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
+go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
+go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
+go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
+go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
+go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
+go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
+go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
+go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
+go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
+go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
+go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
+go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
-go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
-go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
-go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
-go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
-golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
+go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
+go4.org/netipx v0.0.0-20260823151212-3075585bcbeb h1:XBM4hvfwGAttkkiTIFfeigdfcL1xIfdKXqFdgiHGtDs=
+go4.org/netipx v0.0.0-20260823151212-3075585bcbeb/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
-golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
-golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
-golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
-golang.org/x/exp v0.0.0-20251209150349-8475f28825e9 h1:MDfG8Cvcqlt9XXrmEiD4epKn7VJHZO84hejP9Jmp0MM=
-golang.org/x/exp v0.0.0-20251209150349-8475f28825e9/go.mod h1:EPRbTFwzwjXj9NpYyyrvenVh9Y+GFeEvMNh7Xuz7xgU=
+golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
+golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
+golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU=
+golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E=
golang.org/x/exp/typeparams v0.0.0-20250718183923-645b1fa84792 h1:54/e+WfmhvjR2Zuz8Q7dzLGxIBM+s5WZpvo1QfVDGB8=
golang.org/x/exp/typeparams v0.0.0-20250718183923-645b1fa84792/go.mod h1:LKZHyeOpPuZcMgxeHjJp4p5yvxrCX1xDvH10zYHhjjQ=
-golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
-golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
-golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
-golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
-golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
-golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
+golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
-golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
-golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
-golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
-golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
-golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
-golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY=
-golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
-golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
+golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
+golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
+golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
+golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
+golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -486,86 +467,67 @@ golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
-golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
-golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc h1:bH6xUXay0AIFMElXG2rQ4uiE+7ncwtiOdPfYK1NK2XA=
-golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ=
+golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
+golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
+golang.org/x/telemetry v0.0.0-20260924152758-ed294f943157 h1:DftxASHKl6JolFPqoN+2WrFO53JvkHwRXvFqf8gsivA=
+golang.org/x/telemetry v0.0.0-20260924152758-ed294f943157/go.mod h1:i+ivNqjDnTF3WTElsdk5g9V5DTSBYgdNo7xTU9SDwYA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
-golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
-golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
-golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
-golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
-golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
-golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
+golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
-golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
-golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
-golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
-golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
-golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
-golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
-golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
-golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
+golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
+golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
-golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
-golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
-golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
-golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
+golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
+golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
golang.org/x/vuln v1.1.4 h1:Ju8QsuyhX3Hk8ma3CesTbO8vfJD9EvUBgHvkxHBzj0I=
golang.org/x/vuln v1.1.4/go.mod h1:F+45wmU18ym/ca5PLTPLsSzr2KppzswxPP603ldA67s=
-golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
-gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
-gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
-google.golang.org/genproto/googleapis/api v0.0.0-20251213004720-97cd9d5aeac2 h1:7LRqPCEdE4TP4/9psdaB7F2nhZFfBiGJomA5sojLWdU=
-google.golang.org/genproto/googleapis/api v0.0.0-20251213004720-97cd9d5aeac2/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2 h1:2I6GHUeJ/4shcDpoUlLs/2WPnhg7yJwvXtqcMJt9liA=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
-google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM=
-google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig=
-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
+google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc h1:rZHRz0ogq4Pid1IKtA/ivHi8XONVF5tqUQXA2TtgpkE=
+google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:K/n0XLazCJHjD73YuMyNJsN38BPPy1kfFnKxUXaThFU=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
+google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=
+google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=
+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
+gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
-honnef.co/go/tools v0.6.1 h1:R094WgE8K4JirYjBaOpz/AvTyUu/3wbmAoskKN/pxTI=
-honnef.co/go/tools v0.6.1/go.mod h1:3puzxxljPCe8RGJX7BIy1plGbxEOZni5mR2aXe3/uk4=
-k8s.io/apimachinery v0.34.3 h1:/TB+SFEiQvN9HPldtlWOTp0hWbJ+fjU+wkxysf/aQnE=
-k8s.io/apimachinery v0.34.3/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw=
-mvdan.cc/sh/v3 v3.12.0 h1:ejKUR7ONP5bb+UGHGEG/k9V5+pRVIyD+LsZz7o8KHrI=
-mvdan.cc/sh/v3 v3.12.0/go.mod h1:Se6Cj17eYSn+sNooLZiEUnNNmNxg0imoYlTu4CyaGyg=
-pault.ag/go/debian v0.18.0 h1:nr0iiyOU5QlG1VPnhZLNhnCcHx58kukvBJp+dvaM6CQ=
-pault.ag/go/debian v0.18.0/go.mod h1:JFl0XWRCv9hWBrB5MDDZjA5GSEs1X3zcFK/9kCNIUmE=
+honnef.co/go/tools v0.8.1 h1:+JKf3xJ1ni4CwrhVg4/pqsfPGP6vNAXcKbMXJodYx3w=
+honnef.co/go/tools v0.8.1/go.mod h1:XA+OnlRA9EDh/ukGvXMNSZNKGwFQJ+5dER0ioUkOxks=
+k8s.io/apimachinery v0.37.1 h1:hGCYyvKHCwtwMitj2vU4vYx0Z16N9GyZk9BBnz0wDAE=
+k8s.io/apimachinery v0.37.1/go.mod h1:jF84AyUi/IRIXRot5f+lm6MpxoWI+F1XgjaMmwCdTFw=
+mvdan.cc/sh/v3 v3.13.0 h1:dSfq/MVsY4w0Vsi6Lbs0IcQquMVqLdKLESAOZjuHdLg=
+mvdan.cc/sh/v3 v3.13.0/go.mod h1:KV1GByGPc/Ho0X1E6Uz9euhsIQEj4hwyKnodLlFLoDM=
+pault.ag/go/debian v0.19.0 h1:RUxCjScMbnlqFH5I+qsmyjZH8fXXtQ05rlkMJop3tjo=
+pault.ag/go/debian v0.19.0/go.mod h1:1LMojDAazlJ7cA5Ne6H2ZHD4hh3o8NRiW+MpvQRji2o=
pault.ag/go/topsort v0.1.1 h1:L0QnhUly6LmTv0e3DEzbN2q6/FGgAcQvaEw65S53Bg4=
pault.ag/go/topsort v0.1.1/go.mod h1:r1kc/L0/FZ3HhjezBIPaNVhkqv8L0UJ9bxRuHRVZ0q4=
-sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg=
-sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
+pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=
+pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=
+sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5 h1:k9jo7ED/fsfOcz3L1P20P5tjTNtsdQNwMOG2aKzHrl8=
+sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
diff --git a/internal/actorify/actorify.go b/internal/actorify/actorify.go
index 907a2cb..c269a16 100644
--- a/internal/actorify/actorify.go
+++ b/internal/actorify/actorify.go
@@ -29,6 +29,7 @@ type Handler[Input, Output any] func(ctx context.Context, input Input) (Output,
type Actor[Input, Output any] struct {
handler Handler[Input, Output]
inbox chan *message[Input, Output]
+ done chan struct{}
}
type message[Input, Output any] struct {
@@ -48,6 +49,7 @@ func New[Input, Output any](ctx context.Context, handler Handler[Input, Output])
result := &Actor[Input, Output]{
handler: handler,
inbox: make(chan *message[Input, Output], 32),
+ done: make(chan struct{}),
}
go result.handle(ctx)
@@ -56,17 +58,13 @@ func New[Input, Output any](ctx context.Context, handler Handler[Input, Output])
}
func (a *Actor[Input, Output]) handle(ctx context.Context) {
+ defer close(a.done)
for {
select {
case <-ctx.Done():
- close(a.inbox)
return
case msg, ok := <-a.inbox:
if !ok {
- if msg.reply != nil {
- close(msg.reply)
- }
-
return
}
@@ -87,11 +85,18 @@ func (a *Actor[Input, Output]) handle(ctx context.Context) {
// This only works with unary functions by design. If you need to have more inputs, define
// a struct type to use as a container.
func (a *Actor[Input, Output]) Call(ctx context.Context, input Input) (Output, error) {
- replyCh := make(chan reply[Output])
+ replyCh := make(chan reply[Output], 1)
- a.inbox <- &message[Input, Output]{
+ select {
+ case <-ctx.Done():
+ return z[Output](), context.Cause(ctx)
+ case <-a.done:
+ return z[Output](), ErrActorDied
+ case a.inbox <- &message[Input, Output]{
+ ctx: ctx,
arg: input,
reply: replyCh,
+ }:
}
select {
@@ -101,6 +106,8 @@ func (a *Actor[Input, Output]) Call(ctx context.Context, input Input) (Output, e
}
return reply.output, reply.err
+ case <-a.done:
+ return z[Output](), ErrActorDied
case <-ctx.Done():
return z[Output](), context.Cause(ctx)
}
diff --git a/internal/actorify/actorify_test.go b/internal/actorify/actorify_test.go
new file mode 100644
index 0000000..c2c9dca
--- /dev/null
+++ b/internal/actorify/actorify_test.go
@@ -0,0 +1,80 @@
+package actorify
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+func TestCanceledCallDoesNotBlockActor(t *testing.T) {
+ ctx, cancelActor := context.WithCancel(t.Context())
+ defer cancelActor()
+ started := make(chan struct{})
+ release := make(chan struct{})
+ a := New(ctx, func(ctx context.Context, n int) (int, error) {
+ if n == 1 {
+ close(started)
+ <-release
+ }
+ return n, nil
+ })
+ callCtx, cancel := context.WithCancel(ctx)
+ done := make(chan error, 1)
+ go func() { _, err := a.Call(callCtx, 1); done <- err }()
+ <-started
+ cancel()
+ if err := <-done; !errors.Is(err, context.Canceled) {
+ t.Fatalf("err=%v", err)
+ }
+ close(release)
+ nextCtx, cancelNext := context.WithTimeout(ctx, time.Second)
+ defer cancelNext()
+ if n, err := a.Call(nextCtx, 2); err != nil || n != 2 {
+ t.Fatalf("next call=%d err=%v", n, err)
+ }
+}
+
+func TestCallPassesContext(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ a := New(ctx, func(got context.Context, _ int) (bool, error) { return got == ctx, nil })
+ if got, err := a.Call(ctx, 1); err != nil || !got {
+ t.Fatalf("context passed=%v err=%v", got, err)
+ }
+}
+
+func TestCanceledCallWithFullInbox(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ started := make(chan struct{})
+ release := make(chan struct{})
+ defer close(release)
+ a := New(ctx, func(_ context.Context, n int) (int, error) {
+ if n == 1 {
+ close(started)
+ <-release
+ }
+ return 0, nil
+ })
+ a.inbox <- &message[int, int]{ctx: ctx, arg: 1, reply: make(chan reply[int], 1)}
+ <-started
+ for range cap(a.inbox) {
+ a.inbox <- &message[int, int]{ctx: ctx, reply: make(chan reply[int], 1)}
+ }
+ callCtx, cancelCall := context.WithCancel(ctx)
+ cancelCall()
+ if _, err := a.Call(callCtx, 1); !errors.Is(err, context.Canceled) {
+ t.Fatalf("err=%v", err)
+ }
+}
+
+func TestCallAfterActorStops(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ a := New(ctx, func(context.Context, int) (int, error) { return 0, nil })
+ cancel()
+ <-a.done
+ if _, err := a.Call(t.Context(), 1); !errors.Is(err, ErrActorDied) {
+ t.Fatalf("err=%v", err)
+ }
+}
diff --git a/internal/basicauth.go b/internal/basicauth.go
new file mode 100644
index 0000000..86111c2
--- /dev/null
+++ b/internal/basicauth.go
@@ -0,0 +1,56 @@
+package internal
+
+import (
+ "crypto/sha256"
+ "crypto/subtle"
+ "fmt"
+ "log/slog"
+ "net/http"
+)
+
+// BasicAuth wraps next in HTTP Basic authentication using the provided
+// credentials. If both credentials are empty, next is returned unchanged.
+// Partial credentials reject all requests.
+//
+// Credentials are compared in constant time to avoid leaking information
+// through timing side channels.
+func BasicAuth(realm, username, password string, next http.Handler) http.Handler {
+ if username == "" && password == "" {
+ slog.Debug("skipping middleware, basic auth credentials are empty")
+ return next
+ }
+
+ expectedUser := sha256.Sum256([]byte(username))
+ expectedPass := sha256.Sum256([]byte(password))
+ challenge := fmt.Sprintf("Basic realm=%q, charset=\"UTF-8\"", realm)
+
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if username == "" || password == "" {
+ unauthorized(w, challenge)
+ return
+ }
+ user, pass, ok := r.BasicAuth()
+ if !ok {
+ unauthorized(w, challenge)
+ return
+ }
+
+ gotUser := sha256.Sum256([]byte(user))
+ gotPass := sha256.Sum256([]byte(pass))
+
+ userMatch := subtle.ConstantTimeCompare(gotUser[:], expectedUser[:])
+ passMatch := subtle.ConstantTimeCompare(gotPass[:], expectedPass[:])
+
+ if userMatch&passMatch != 1 {
+ unauthorized(w, challenge)
+ return
+ }
+
+ next.ServeHTTP(w, r)
+ })
+}
+
+func unauthorized(w http.ResponseWriter, challenge string) {
+ w.Header().Set("WWW-Authenticate", challenge)
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
+}
diff --git a/internal/basicauth_test.go b/internal/basicauth_test.go
new file mode 100644
index 0000000..b15b2e4
--- /dev/null
+++ b/internal/basicauth_test.go
@@ -0,0 +1,152 @@
+package internal
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func okHandler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("ok"))
+ })
+}
+
+func TestBasicAuth(t *testing.T) {
+ t.Parallel()
+
+ const (
+ realm = "test-realm"
+ username = "admin"
+ password = "hunter2"
+ )
+
+ for _, tt := range []struct {
+ name string
+ setAuth bool
+ user string
+ pass string
+ wantStatus int
+ wantBody string
+ wantChall bool
+ }{
+ {
+ name: "valid credentials",
+ setAuth: true,
+ user: username,
+ pass: password,
+ wantStatus: http.StatusOK,
+ wantBody: "ok",
+ },
+ {
+ name: "missing credentials",
+ setAuth: false,
+ wantStatus: http.StatusUnauthorized,
+ wantChall: true,
+ },
+ {
+ name: "wrong username",
+ setAuth: true,
+ user: "nobody",
+ pass: password,
+ wantStatus: http.StatusUnauthorized,
+ wantChall: true,
+ },
+ {
+ name: "wrong password",
+ setAuth: true,
+ user: username,
+ pass: "wrong",
+ wantStatus: http.StatusUnauthorized,
+ wantChall: true,
+ },
+ {
+ name: "empty supplied credentials",
+ setAuth: true,
+ user: "",
+ pass: "",
+ wantStatus: http.StatusUnauthorized,
+ wantChall: true,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ h := BasicAuth(realm, username, password, okHandler())
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ if tt.setAuth {
+ req.SetBasicAuth(tt.user, tt.pass)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+
+ if rec.Code != tt.wantStatus {
+ t.Errorf("status = %d, want %d", rec.Code, tt.wantStatus)
+ }
+
+ if tt.wantBody != "" && rec.Body.String() != tt.wantBody {
+ t.Errorf("body = %q, want %q", rec.Body.String(), tt.wantBody)
+ }
+
+ chall := rec.Header().Get("WWW-Authenticate")
+ if tt.wantChall {
+ if chall == "" {
+ t.Error("WWW-Authenticate header missing on 401")
+ }
+ if !strings.Contains(chall, realm) {
+ t.Errorf("WWW-Authenticate = %q, want realm %q", chall, realm)
+ }
+ } else if chall != "" {
+ t.Errorf("unexpected WWW-Authenticate header: %q", chall)
+ }
+ })
+ }
+}
+
+func TestBasicAuthPassthrough(t *testing.T) {
+ t.Parallel()
+
+ for _, tt := range []struct {
+ name string
+ username string
+ password string
+ }{
+ {name: "both empty", username: "", password: ""},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ h := BasicAuth("realm", tt.username, tt.password, okHandler())
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Errorf("status = %d, want %d (passthrough expected)", rec.Code, http.StatusOK)
+ }
+ if rec.Body.String() != "ok" {
+ t.Errorf("body = %q, want %q", rec.Body.String(), "ok")
+ }
+ })
+ }
+}
+
+func TestBasicAuthPartialCredentialsFailClosed(t *testing.T) {
+ for _, tc := range []struct{ user, pass string }{{"admin", ""}, {"", "secret"}} {
+ t.Run(tc.user+tc.pass, func(t *testing.T) {
+ called := false
+ h := BasicAuth("test", tc.user, tc.pass, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }))
+ r := httptest.NewRequest("GET", "/", nil)
+ r.SetBasicAuth(tc.user, tc.pass)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if called || w.Code != http.StatusUnauthorized {
+ t.Fatalf("called=%v status=%d", called, w.Code)
+ }
+ })
+ }
+}
diff --git a/internal/bundler/bundler.go b/internal/bundler/bundler.go
new file mode 100644
index 0000000..29a049c
--- /dev/null
+++ b/internal/bundler/bundler.go
@@ -0,0 +1,407 @@
+// Copyright 2016 Google LLC.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package bundler supports bundling (batching) of items. Bundling amortizes an
+// action with fixed costs over multiple items. For example, if an API provides
+// an RPC that accepts a list of items as input, but clients would prefer
+// adding items one at a time, then a Bundler can accept individual items from
+// the client and bundle many of them into a single RPC.
+//
+// This package is experimental and subject to change without notice.
+package bundler
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "time"
+
+ "golang.org/x/sync/semaphore"
+)
+
+type mode int
+
+const (
+ DefaultDelayThreshold = time.Second
+ DefaultBundleHandlerDeadline = time.Minute
+ DefaultBundleCountThreshold = 10
+ DefaultBundleByteThreshold = 1e6 // 1M
+ DefaultBufferedByteLimit = 1e9 // 1G
+)
+
+const (
+ none mode = iota
+ add
+ addWait
+)
+
+var (
+ // ErrOverflow indicates that Bundler's stored bytes exceeds its BufferedByteLimit.
+ ErrOverflow = errors.New("bundler: reached buffered byte limit")
+
+ // ErrOversizedItem indicates that an item's size exceeds the maximum bundle size.
+ ErrOversizedItem = errors.New("bundler: item size exceeds bundle byte limit")
+
+ // errMixedMethods indicates that mutually exclusive methods has been
+ // called subsequently.
+ errMixedMethods = errors.New("bundler: calls to Add and AddWait cannot be mixed")
+)
+
+// A Bundler collects items added to it into a bundle until the bundle
+// exceeds a given size, then calls a user-provided function to handle the
+// bundle.
+//
+// The exported fields are only safe to modify prior to the first call to Add
+// or AddWait.
+type Bundler[T any] struct {
+ // Starting from the time that the first message is added to a bundle, once
+ // this delay has passed, handle the bundle. The default is DefaultDelayThreshold.
+ DelayThreshold time.Duration
+
+ // Once a bundle has this many items, handle the bundle. Since only one
+ // item at a time is added to a bundle, no bundle will exceed this
+ // threshold, so it also serves as a limit. The default is
+ // DefaultBundleCountThreshold.
+ BundleCountThreshold int
+
+ // Once the number of bytes in current bundle reaches this threshold, handle
+ // the bundle. The default is DefaultBundleByteThreshold. This triggers handling,
+ // but does not cap the total size of a bundle.
+ BundleByteThreshold int
+
+ // The maximum size of a bundle, in bytes. Zero means unlimited.
+ BundleByteLimit int
+
+ // The maximum number of bytes that the Bundler will keep in memory before
+ // returning ErrOverflow. The default is DefaultBufferedByteLimit.
+ BufferedByteLimit int
+
+ // The maximum number of handler invocations that can be running at once.
+ // The default is 1.
+ HandlerLimit int
+
+ // ContextDeadline is the deadline for the context attached to bundle handling.
+ ContextDeadline time.Duration
+
+ handler func(context.Context, []T) // called to handle a bundle
+
+ mu sync.Mutex // guards access to fields below
+ flushTimer *time.Timer // implements DelayThreshold
+ handlerCount int // # of bundles currently being handled (i.e. handler is invoked on them)
+ sem *semaphore.Weighted // enforces BufferedByteLimit
+ semOnce sync.Once // guards semaphore initialization
+ // The current bundle we're adding items to. Not yet in the queue.
+ // Appended to the queue once the flushTimer fires or the bundle
+ // thresholds/limits are reached. If curBundle is nil and tail is
+ // not, we first try to add items to tail. Once tail is full or handled,
+ // we create a new curBundle for the incoming item.
+ curBundle *bundle[T]
+ // The next bundle in the queue to be handled. Nil if the queue is
+ // empty.
+ head *bundle[T]
+ // The last bundle in the queue to be handled. Nil if the queue is
+ // empty. If curBundle is nil and tail isn't, we attempt to add new
+ // items to the tail until if becomes full or has been passed to the
+ // handler.
+ tail *bundle[T]
+ curFlush *sync.WaitGroup // counts outstanding bundles since last flush
+ prevFlush chan bool // signal used to wait for prior flush
+
+ // The first call to Add or AddWait, mode will be add or addWait respectively.
+ // If there wasn't call yet then mode is none.
+ mode mode
+ // TODO: consider alternative queue implementation for head/tail bundle. see:
+ // https://code-review.googlesource.com/c/google-api-go-client/+/47991/4/support/bundler/bundler.go#74
+}
+
+// A bundle is a group of items that were added individually and will be passed
+// to a handler as a slice.
+type bundle[T any] struct {
+ items []T // slice of T
+ size int // size in bytes of all items
+ next *bundle[T] // bundles are handled in order as a linked list queue
+ flush *sync.WaitGroup // the counter that tracks flush completion
+}
+
+// add appends item to this bundle and increments the total size. It requires
+// that b.mu is locked.
+func (bu *bundle[T]) add(item T, size int) {
+ bu.items = append(bu.items, item)
+ bu.size += size
+}
+
+// New creates a new Bundler.
+//
+// handler is a function that will be called on each bundle. If itemExample is
+// of type T, the argument to handler is of type []T. handler is always called
+// sequentially for each bundle, and never in parallel.
+//
+// Configure the Bundler by setting its thresholds and limits before calling
+// any of its methods.
+func New[T any](handler func(context.Context, []T)) *Bundler[T] {
+ b := &Bundler[T]{
+ DelayThreshold: DefaultDelayThreshold,
+ BundleCountThreshold: DefaultBundleCountThreshold,
+ BundleByteThreshold: DefaultBundleByteThreshold,
+ BufferedByteLimit: DefaultBufferedByteLimit,
+ HandlerLimit: 1,
+
+ handler: handler,
+ curFlush: &sync.WaitGroup{},
+ }
+ return b
+}
+
+func (b *Bundler[T]) initSemaphores() {
+ // Create the semaphores lazily, because the user may set limits
+ // after NewBundler.
+ b.semOnce.Do(func() {
+ b.sem = semaphore.NewWeighted(int64(b.BufferedByteLimit))
+ })
+}
+
+// enqueueCurBundle moves curBundle to the end of the queue. The bundle may be
+// handled immediately if we are below HandlerLimit. It requires that b.mu is
+// locked.
+func (b *Bundler[T]) enqueueCurBundle() {
+ // We don't require callers to check if there is a pending bundle. It
+ // may have already been appended to the queue. If so, return early.
+ if b.curBundle == nil {
+ return
+ }
+ // If we are below the HandlerLimit, the queue must be empty. Handle
+ // immediately with a new goroutine.
+ if b.handlerCount < b.HandlerLimit {
+ b.handlerCount++
+ go b.handle(b.curBundle)
+ } else if b.tail != nil {
+ // There are bundles on the queue, so append to the end
+ b.tail.next = b.curBundle
+ b.tail = b.curBundle
+ } else {
+ // The queue is empty, so initialize the queue
+ b.head = b.curBundle
+ b.tail = b.curBundle
+ }
+ b.curBundle = nil
+ if b.flushTimer != nil {
+ b.flushTimer.Stop()
+ b.flushTimer = nil
+ }
+}
+
+// setMode sets the state of Bundler's mode. If mode was defined before
+// and passed state is different from it then return an error.
+func (b *Bundler[T]) setMode(m mode) error {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.mode == m || b.mode == none {
+ b.mode = m
+ return nil
+ }
+ return errMixedMethods
+}
+
+// canFit returns true if bu can fit an additional item of size bytes based
+// on the limits of Bundler b.
+func (b *Bundler[T]) canFit(bu *bundle[T], size int) bool {
+ return (b.BundleByteLimit <= 0 || bu.size+size <= b.BundleByteLimit) &&
+ (b.BundleCountThreshold <= 0 || len(bu.items) < b.BundleCountThreshold)
+}
+
+// Add adds item to the current bundle. It marks the bundle for handling and
+// starts a new one if any of the thresholds or limits are exceeded.
+// The type of item must be assignable to the itemExample parameter of the NewBundler
+// method, otherwise there will be a panic.
+//
+// If the item's size exceeds the maximum bundle size (Bundler.BundleByteLimit), then
+// the item can never be handled. Add returns ErrOversizedItem in this case.
+//
+// If adding the item would exceed the maximum memory allowed
+// (Bundler.BufferedByteLimit) or an AddWait call is blocked waiting for
+// memory, Add returns ErrOverflow.
+//
+// Add never blocks.
+func (b *Bundler[T]) Add(item T, size int) error {
+ if err := b.setMode(add); err != nil {
+ return err
+ }
+ // If this item exceeds the maximum size of a bundle,
+ // we can never send it.
+ if b.BundleByteLimit > 0 && size > b.BundleByteLimit {
+ return ErrOversizedItem
+ }
+
+ // If adding this item would exceed our allotted memory
+ // footprint, we can't accept it.
+ // (TryAcquire also returns false if anything is waiting on the semaphore,
+ // so calls to Add and AddWait shouldn't be mixed.)
+ b.initSemaphores()
+ if !b.sem.TryAcquire(int64(size)) {
+ return ErrOverflow
+ }
+
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.add(item, size)
+}
+
+// add adds item to the tail of the bundle queue or curBundle depending on space
+// and nil-ness (see inline comments). It marks curBundle for handling (by
+// appending it to the queue) if any of the thresholds or limits are exceeded.
+// curBundle is lazily initialized. It requires that b.mu is locked.
+func (b *Bundler[T]) add(item T, size int) error {
+ // If we don't have a curBundle, see if we can add to the queue tail.
+ if b.tail != nil && b.curBundle == nil && b.canFit(b.tail, size) {
+ b.tail.add(item, size)
+ return nil
+ }
+
+ // If we can't fit in the existing curBundle, move it onto the queue.
+ if b.curBundle != nil && !b.canFit(b.curBundle, size) {
+ b.enqueueCurBundle()
+ }
+
+ // Create a curBundle if we don't have one.
+ if b.curBundle == nil {
+ b.curFlush.Add(1)
+ b.curBundle = &bundle[T]{
+ items: []T{},
+ flush: b.curFlush,
+ }
+ }
+
+ // Add the item.
+ b.curBundle.add(item, size)
+
+ // If curBundle is ready for handling, move it to the queue.
+ if b.curBundle.size >= b.BundleByteThreshold ||
+ len(b.curBundle.items) == b.BundleCountThreshold {
+ b.enqueueCurBundle()
+ }
+
+ // If we created a new bundle and it wasn't immediately handled, set a timer
+ if b.curBundle != nil && b.flushTimer == nil {
+ b.flushTimer = time.AfterFunc(b.DelayThreshold, b.tryHandleBundles)
+ }
+
+ return nil
+}
+
+// tryHandleBundles is the timer callback that handles or queues any current
+// bundle after DelayThreshold time, even if the bundle isn't completely full.
+func (b *Bundler[T]) tryHandleBundles() {
+ b.mu.Lock()
+ b.enqueueCurBundle()
+ b.mu.Unlock()
+}
+
+// next returns the next bundle that is ready for handling and removes it from
+// the internal queue. It requires that b.mu is locked.
+func (b *Bundler[T]) next() *bundle[T] {
+ if b.head == nil {
+ return nil
+ }
+ out := b.head
+ b.head = b.head.next
+ if b.head == nil {
+ b.tail = nil
+ }
+ out.next = nil
+ return out
+}
+
+// handle calls the user-specified handler on the given bundle. handle is
+// intended to be run as a goroutine. After the handler returns, we update the
+// byte total. handle continues processing additional bundles that are ready.
+// If no more bundles are ready, the handler count is decremented and the
+// goroutine ends.
+func (b *Bundler[T]) handle(bu *bundle[T]) {
+ for bu != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), b.ContextDeadline)
+ b.handler(ctx, bu.items)
+ cancel()
+ bu = b.postHandle(bu)
+ }
+}
+
+func (b *Bundler[T]) postHandle(bu *bundle[T]) *bundle[T] {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ b.sem.Release(int64(bu.size))
+ bu.flush.Done()
+
+ bu = b.next()
+ if bu == nil {
+ b.handlerCount--
+ }
+ return bu
+}
+
+// AddWait adds item to the current bundle. It marks the bundle for handling and
+// starts a new one if any of the thresholds or limits are exceeded.
+//
+// If the item's size exceeds the maximum bundle size (Bundler.BundleByteLimit), then
+// the item can never be handled. AddWait returns ErrOversizedItem in this case.
+//
+// If adding the item would exceed the maximum memory allowed (Bundler.BufferedByteLimit),
+// AddWait blocks until space is available or ctx is done.
+//
+// Calls to Add and AddWait should not be mixed on the same Bundler.
+func (b *Bundler[T]) AddWait(ctx context.Context, item T, size int) error {
+ if err := b.setMode(addWait); err != nil {
+ return err
+ }
+ // If this item exceeds the maximum size of a bundle,
+ // we can never send it.
+ if b.BundleByteLimit > 0 && size > b.BundleByteLimit {
+ return ErrOversizedItem
+ }
+ // If adding this item would exceed our allotted memory footprint, block
+ // until space is available. The semaphore is FIFO, so there will be no
+ // starvation.
+ b.initSemaphores()
+ if err := b.sem.Acquire(ctx, int64(size)); err != nil {
+ return err
+ }
+
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.add(item, size)
+}
+
+// Flush invokes the handler for all remaining items in the Bundler and waits
+// for it to return.
+func (b *Bundler[T]) Flush() {
+ b.mu.Lock()
+
+ // If a curBundle is pending, move it to the queue.
+ b.enqueueCurBundle()
+
+ // Store a pointer to the WaitGroup that counts outstanding bundles
+ // in the current flush and create a new one to track the next flush.
+ wg := b.curFlush
+ b.curFlush = &sync.WaitGroup{}
+
+ // Flush must wait for all prior, outstanding flushes to complete.
+ // We use a channel to communicate completion between each flush in
+ // the sequence.
+ prev := b.prevFlush
+ next := make(chan bool)
+ b.prevFlush = next
+
+ b.mu.Unlock()
+
+ // Wait until the previous flush is finished.
+ if prev != nil {
+ <-prev
+ }
+
+ // Wait until this flush is finished.
+ wg.Wait()
+
+ // Allow the next flush to finish.
+ close(next)
+}
diff --git a/internal/bundler/bundler_test.go b/internal/bundler/bundler_test.go
new file mode 100644
index 0000000..0085237
--- /dev/null
+++ b/internal/bundler/bundler_test.go
@@ -0,0 +1,39 @@
+package bundler
+
+import (
+ "context"
+ "testing"
+)
+
+func TestBundler(t *testing.T) {
+ input := []int{1, 2, 3, 4}
+ done := false
+ b := New[int](func(_ context.Context, data []int) {
+ if len(data) != 4 {
+ t.Errorf("Wanted len(data) == %d, got: %d", len(input), len(data))
+ }
+
+ sum := 0
+ const wantSum = 10
+ for _, i := range data {
+ sum += i
+ }
+
+ if sum != wantSum {
+ t.Errorf("wanted sum of inputs to be %d, got: %d", wantSum, sum)
+ }
+ done = true
+ })
+
+ for _, i := range input {
+ if err := b.Add(i, 1); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ b.Flush()
+
+ if !done {
+ t.Fatal("function wasn't called")
+ }
+}
diff --git a/internal/clampip_test.go b/internal/clampip_test.go
index ffdb53a..d83f143 100644
--- a/internal/clampip_test.go
+++ b/internal/clampip_test.go
@@ -271,4 +271,4 @@ func BenchmarkClampIP(b *testing.B) {
ClampIP(ipv4mapped)
}
})
-}
\ No newline at end of file
+}
diff --git a/internal/cmd/mkmsi/README.md b/internal/cmd/mkmsi/README.md
new file mode 100644
index 0000000..dd58c16
--- /dev/null
+++ b/internal/cmd/mkmsi/README.md
@@ -0,0 +1,31 @@
+# mkmsi
+
+Converts a yeet-generated .zip file to an MSI using [msitools](https://gitlab.gnome.org/GNOME/msitools).
+
+It needs `wixl`, `wixl-heat`, `msibuild` and `msiinfo` from msitools 0.106 or
+later on PATH. Use Homebrew (`brew install msitools`) on both macOS and Linux.
+
+Distribution packages are usually too old. Debian and Ubuntu also split the
+tools across two packages -- `msibuild` and `msiinfo` in `msitools`, `wixl` and
+`wixl-heat` in `wixl` -- and Ubuntu 24.04 ships 0.103, which aborts with
+`unhandled child Component node Condition` on the `` element in
+`run/windows/anubis.wxs`.
+
+> [!NOTE]
+> This code was generated using Claude Opus 5 as a correctness fuzzer to ensure that this output is valid, works on Windows systems, and generally behaves like a well-behaved Windows installer. Due to facts and circumstances beyond my control with how these tools and the MSI format works, it is not currently possible to make these MSI builds reproducible.
+>
+> I tried.
+
+This is intended to be run by `yeet` at package build time:
+
+```js
+// Build MSI installers from the Windows zips that were just built.
+packages
+ .flat()
+ .filter((pkg) => pkg.includes("windows"))
+ .filter((pkg) => pkg.endsWith(".zip"))
+ .forEach((zip) => {
+ const msiPath = zip.replace(/\.zip$/, ".msi");
+ $`go run ./internal/cmd/mkmsi --zip ${zip} --out ${msiPath}`;
+ });
+```
diff --git a/internal/cmd/mkmsi/build.go b/internal/cmd/mkmsi/build.go
new file mode 100644
index 0000000..6c1a2e8
--- /dev/null
+++ b/internal/cmd/mkmsi/build.go
@@ -0,0 +1,201 @@
+package main
+
+import (
+ "archive/zip"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+)
+
+// ErrWixlDroppedAttribute reports that wixl did not understand part of the wxs.
+//
+// wixl writes a warning to stderr and then exits 0 with an installer that is
+// missing whatever it did not understand, so its exit status cannot be trusted
+// on its own.
+var ErrWixlDroppedAttribute = errors.New("mkmsi: wixl rejected part of the wxs")
+
+// zipNameRe pulls the version and architecture out of a yeet zip name such as
+// anubis-1.26.2-1-gec3cce8a-dev-windows-amd64.zip.
+var zipNameRe = regexp.MustCompile(`^anubis-(.+)-windows-(amd64|arm64)\.zip$`)
+
+// versionFromZipName extracts the Anubis version from a zip file's name.
+func versionFromZipName(name string) (string, error) {
+ m := zipNameRe.FindStringSubmatch(filepath.Base(name))
+ if m == nil {
+ return "", fmt.Errorf("%w: %q is not an Anubis Windows zip", ErrBadVersion, name)
+ }
+
+ return m[1], nil
+}
+
+// archFromZipName extracts the Go architecture from a zip file's name.
+func archFromZipName(name string) (string, error) {
+ m := zipNameRe.FindStringSubmatch(filepath.Base(name))
+ if m == nil {
+ return "", fmt.Errorf("%w: %q is not an Anubis Windows zip", ErrBadVersion, name)
+ }
+
+ return m[2], nil
+}
+
+// checkWixlOutput fails when wixl reported that it could not handle something.
+func checkWixlOutput(stderr string) error {
+ for line := range strings.SplitSeq(stderr, "\n") {
+ if strings.Contains(line, "CRITICAL") {
+ return fmt.Errorf("%w: %s", ErrWixlDroppedAttribute, strings.TrimSpace(line))
+ }
+ }
+
+ return nil
+}
+
+// unzip extracts src into dest, stripping the single top level directory that
+// yeet puts in its archives. It returns the list of extracted file paths,
+// relative to dest and sorted, so downstream steps are reproducible, along
+// with the single modification time yeet stamped every entry with.
+//
+// That shared mtime is handed back rather than rediscovered so files this
+// program generates itself after unzipping -- the config templates
+// stageConfigTemplates writes -- can be stamped with it too. Without that,
+// only files that came straight out of the zip would have a reproducible
+// mtime, and the CAB archive wixl builds embeds every file's mtime
+// regardless of where it came from.
+func unzip(src, dest string) ([]string, time.Time, error) {
+ r, err := zip.OpenReader(src)
+ if err != nil {
+ return nil, time.Time{}, fmt.Errorf("mkmsi: cannot open %s: %w", src, err)
+ }
+ defer func() { _ = r.Close() }()
+
+ if len(r.File) == 0 {
+ return nil, time.Time{}, fmt.Errorf("mkmsi: %s has no entries", src)
+ }
+
+ // yeet stamps every entry in the zip with the same mtime; verified
+ // empirically across a real build's 151 entries. Any entry's mtime is
+ // therefore as good as any other's.
+ srcMTime := r.File[0].Modified
+
+ var names []string
+
+ for _, f := range r.File {
+ // yeet wraps everything in one directory named after the package.
+ rel := f.Name
+ if i := strings.IndexByte(rel, '/'); i >= 0 {
+ rel = rel[i+1:]
+ }
+
+ if rel == "" {
+ continue
+ }
+
+ // Reject traversal before touching the filesystem: the zip is built
+ // locally, but this program also runs over files from CI artifacts.
+ out := filepath.Join(dest, filepath.FromSlash(rel))
+ if !strings.HasPrefix(out, filepath.Clean(dest)+string(os.PathSeparator)) {
+ return nil, time.Time{}, fmt.Errorf("mkmsi: refusing path %q outside %s", f.Name, dest)
+ }
+
+ if f.FileInfo().IsDir() {
+ if err := os.MkdirAll(out, 0o755); err != nil {
+ return nil, time.Time{}, fmt.Errorf("mkmsi: cannot create %s: %w", out, err)
+ }
+ continue
+ }
+
+ if err := extractOne(f, out); err != nil {
+ return nil, time.Time{}, err
+ }
+
+ names = append(names, rel)
+ }
+
+ slices.Sort(names)
+
+ return names, srcMTime, nil
+}
+
+// extractOne writes a single zip entry to disk.
+func extractOne(f *zip.File, out string) error {
+ if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil {
+ return fmt.Errorf("mkmsi: cannot create %s: %w", filepath.Dir(out), err)
+ }
+
+ rc, err := f.Open()
+ if err != nil {
+ return fmt.Errorf("mkmsi: cannot read %s from zip: %w", f.Name, err)
+ }
+ defer func() { _ = rc.Close() }()
+
+ w, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode().Perm()|0o200)
+ if err != nil {
+ return fmt.Errorf("mkmsi: cannot create %s: %w", out, err)
+ }
+
+ if _, err := io.Copy(w, rc); err != nil {
+ _ = w.Close()
+ return fmt.Errorf("mkmsi: cannot write %s: %w", out, err)
+ }
+
+ if err := w.Close(); err != nil {
+ return fmt.Errorf("mkmsi: cannot close %s: %w", out, err)
+ }
+
+ // yeet pins every zip entry's modification time to a fixed epoch so its
+ // zips are byte-identical across builds. os.OpenFile above stamps the
+ // file with the current wall clock instead, and the CAB archive wixl
+ // builds embeds each file's mtime -- so without restoring it here, the
+ // CAB stream (and therefore the MSI) differs on every build even when
+ // the input zip is identical. This must run after w.Close(), not
+ // before: closing a file does not touch its mtime, but running before
+ // the copy finishes would use the file's creation time instead.
+ if err := os.Chtimes(out, f.Modified, f.Modified); err != nil {
+ return fmt.Errorf("mkmsi: cannot set mtime on %s: %w", out, err)
+ }
+
+ return nil
+}
+
+// concatFiles writes the contents of srcs, in order, to dest, then stamps it
+// with mtime.
+//
+// The stamp matters for the same reason extractOne restores one on every
+// file it extracts from the zip: dest is a File the MSI installs, so its
+// mtime is embedded in the CAB archive wixl builds. Left at the wall clock
+// os.WriteFile would otherwise use, it would make the CAB -- and therefore
+// the MSI -- differ on every build even when every other input is identical.
+// mtime is srcMTime, the single mtime yeet stamped every entry in the source
+// zip with (see unzip), so these generated files end up sharing it rather
+// than inventing a separate fixed point in time of their own.
+func concatFiles(dest string, mtime time.Time, srcs ...string) error {
+ var buf []byte
+
+ for _, src := range srcs {
+ data, err := os.ReadFile(src)
+ if err != nil {
+ return fmt.Errorf("mkmsi: cannot read %s: %w", src, err)
+ }
+
+ buf = append(buf, data...)
+ }
+
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return fmt.Errorf("mkmsi: cannot create %s: %w", filepath.Dir(dest), err)
+ }
+
+ if err := os.WriteFile(dest, buf, 0o644); err != nil {
+ return fmt.Errorf("mkmsi: cannot write %s: %w", dest, err)
+ }
+
+ if err := os.Chtimes(dest, mtime, mtime); err != nil {
+ return fmt.Errorf("mkmsi: cannot set mtime on %s: %w", dest, err)
+ }
+
+ return nil
+}
diff --git a/internal/cmd/mkmsi/build_test.go b/internal/cmd/mkmsi/build_test.go
new file mode 100644
index 0000000..9b81eab
--- /dev/null
+++ b/internal/cmd/mkmsi/build_test.go
@@ -0,0 +1,92 @@
+package main
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestVersionFromZipName(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ in string
+ want string
+ wantErr error
+ }{
+ {
+ name: "dev build with path",
+ in: "var/win/anubis-1.26.2-1-gec3cce8a-dev-windows-amd64.zip",
+ want: "1.26.2-1-gec3cce8a-dev",
+ },
+ {
+ name: "tagged release",
+ in: "anubis-1.26.2-windows-amd64.zip",
+ want: "1.26.2",
+ },
+ {
+ name: "arm64",
+ in: "anubis-1.26.2-windows-arm64.zip",
+ want: "1.26.2",
+ },
+ {name: "not an anubis zip", in: "something-else.zip", wantErr: ErrBadVersion},
+ {name: "no platform suffix", in: "anubis-1.26.2.zip", wantErr: ErrBadVersion},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := versionFromZipName(tt.in)
+
+ if tt.wantErr != nil {
+ if !errors.Is(err, tt.wantErr) {
+ t.Fatalf("versionFromZipName(%q): got error %v, want %v", tt.in, err, tt.wantErr)
+ }
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("versionFromZipName(%q): unexpected error: %v", tt.in, err)
+ }
+
+ if got != tt.want {
+ t.Errorf("versionFromZipName(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestCheckWixlOutput(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ in string
+ wantErr error
+ }{
+ {name: "clean", in: ""},
+ {name: "harmless chatter", in: "building anubis.msi\n"},
+ {
+ name: "dropped attribute",
+ in: "(wixl:1234): GLib-GObject-CRITICAL **: object class 'WixlWixFile' has no property named 'NeverOverwrite'\n",
+ wantErr: ErrWixlDroppedAttribute,
+ },
+ {
+ name: "critical among other lines",
+ in: "fine\n** (wixl:1): CRITICAL **: assertion failed\nalso fine\n",
+ wantErr: ErrWixlDroppedAttribute,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ // checkWixlOutput is a pure string-matching function over
+ // captured sample wixl stderr; it never shells out to wixl
+ // itself, so unlike msi_test.go's tests this one needs no
+ // requireTool gate and must always run.
+ err := checkWixlOutput(tt.in)
+
+ if tt.wantErr == nil {
+ if err != nil {
+ t.Fatalf("checkWixlOutput(%q): unexpected error: %v", tt.in, err)
+ }
+ return
+ }
+
+ if !errors.Is(err, tt.wantErr) {
+ t.Errorf("checkWixlOutput(%q): got %v, want %v", tt.in, err, tt.wantErr)
+ }
+ })
+ }
+}
diff --git a/internal/cmd/mkmsi/docfragment.go b/internal/cmd/mkmsi/docfragment.go
new file mode 100644
index 0000000..f8f3e6e
--- /dev/null
+++ b/internal/cmd/mkmsi/docfragment.go
@@ -0,0 +1,146 @@
+package main
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/xml"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// rewriteDirectoryIDs replaces wixl-heat's randomized dir directory IDs
+// in a generated fragment with IDs derived deterministically from each
+// directory's path, so the fragment -- and therefore the MSI wixl builds
+// from it -- is reproducible across builds.
+//
+// wixl-heat's cmp and fil IDs are already stable, derived from
+// each component's and file's relative path. Only its dir IDs are
+// random: running wixl-heat twice over an identical tree produces two
+// completely disjoint sets of directory IDs (verified empirically). Each
+// dir ID appears exactly once in the fragment, as a Directory
+// element's own Id attribute -- nothing else in the document references it
+// -- which is what makes a single rewrite pass safe.
+//
+// This walks the document with encoding/xml rather than a regex: a Name
+// attribute or a doc file's path could otherwise contain something that
+// looks like an id, and a regex over the raw text would have no way to tell
+// that apart from a real dir attribute.
+func rewriteDirectoryIDs(doc []byte) ([]byte, error) {
+ dec := xml.NewDecoder(bytes.NewReader(doc))
+
+ var out bytes.Buffer
+ enc := xml.NewEncoder(&out)
+
+ // dirNames accumulates the Name attributes of open Directory elements,
+ // in nesting order, so each directory's deterministic ID is derived
+ // from its full relative path rather than just its own Name -- two
+ // directories with the same leaf name under different parents (e.g. two
+ // "haproxy" directories in the Anubis docs tree) must not collide.
+ var dirNames []string
+
+ for {
+ tok, err := dec.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, fmt.Errorf("mkmsi: cannot parse doc fragment: %w", err)
+ }
+
+ switch t := tok.(type) {
+ case xml.StartElement:
+ // encoding/xml's Encoder writes an xmlns declaration for every
+ // element with a resolved namespace, regardless of whether an
+ // ancestor already declared it. Left alone, the xmlns attribute
+ // this document's root already carries in Attr collides with
+ // that auto-generated one and produces a duplicate attribute --
+ // invalid XML that libxml2 (and therefore wixl) rejects. Every
+ // element's namespace is preserved via Name.Space either way,
+ // so dropping the explicit declarations here is lossless.
+ t.Attr = dropXMLNSAttrs(t.Attr)
+
+ if t.Name.Local == "Directory" {
+ dirNames = append(dirNames, attrValue(t.Attr, "Name"))
+
+ id := directoryID(directoryPath(dirNames))
+ for i := range t.Attr {
+ if t.Attr[i].Name.Local == "Id" {
+ t.Attr[i].Value = id
+ }
+ }
+ }
+
+ tok = t
+ case xml.EndElement:
+ if t.Name.Local == "Directory" {
+ dirNames = dirNames[:len(dirNames)-1]
+ }
+ }
+
+ if err := enc.EncodeToken(tok); err != nil {
+ return nil, fmt.Errorf("mkmsi: cannot rewrite doc fragment: %w", err)
+ }
+ }
+
+ if err := enc.Flush(); err != nil {
+ return nil, fmt.Errorf("mkmsi: cannot rewrite doc fragment: %w", err)
+ }
+
+ return out.Bytes(), nil
+}
+
+// dropXMLNSAttrs removes default and prefixed xmlns declarations from an
+// attribute list, keeping everything else in order.
+func dropXMLNSAttrs(attrs []xml.Attr) []xml.Attr {
+ kept := attrs[:0]
+ for _, a := range attrs {
+ if a.Name.Space == "xmlns" || (a.Name.Space == "" && a.Name.Local == "xmlns") {
+ continue
+ }
+ kept = append(kept, a)
+ }
+ return kept
+}
+
+// attrValue returns the value of the first attribute named local, or "" if
+// there is none.
+func attrValue(attrs []xml.Attr, local string) string {
+ for _, a := range attrs {
+ if a.Name.Local == local {
+ return a.Value
+ }
+ }
+ return ""
+}
+
+// directoryPath joins accumulated Directory Name attributes into a relative
+// path. wixl-heat's own root directory is named ".", which is dropped so
+// the path starts clean instead of carrying a leading "./".
+func directoryPath(names []string) string {
+ var parts []string
+ for _, n := range names {
+ if n == "." {
+ continue
+ }
+ parts = append(parts, n)
+ }
+ return strings.Join(parts, "/")
+}
+
+// directoryID derives a deterministic Directory Id from a relative path, in
+// the same dir shape wixl-heat itself uses for cmp and fil: a
+// fixed three-letter prefix plus a 32-character uppercase hex digest. This
+// is an identifier, not a security boundary, so the first 16 bytes of a
+// SHA-256 digest are used rather than MD5, purely to keep the digest the
+// same length wixl-heat's own IDs use.
+//
+// It is path-derived rather than sequential on purpose: a sequential
+// numbering scheme would renumber every directory whenever a doc file is
+// added or removed anywhere in the tree, while a path-derived one only
+// changes for a directory that itself moved.
+func directoryID(path string) string {
+ sum := sha256.Sum256([]byte(path))
+ return "dir" + strings.ToUpper(hex.EncodeToString(sum[:16]))
+}
diff --git a/internal/cmd/mkmsi/main.go b/internal/cmd/mkmsi/main.go
new file mode 100644
index 0000000..302a7da
--- /dev/null
+++ b/internal/cmd/mkmsi/main.go
@@ -0,0 +1,735 @@
+// Command mkmsi turns the Windows zip that yeet builds into an MSI installer.
+//
+// It needs wixl, wixl-heat, msibuild and msiinfo from msitools on PATH.
+package main
+
+import (
+ "bytes"
+ "flag"
+ "fmt"
+ "log"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ zipPath = flag.String("zip", "", "path to the Windows zip built by yeet")
+ outPath = flag.String("out", "", "path to write the MSI to")
+ packagingDir = flag.String("packaging-dir", filepath.Join("run", "windows"), "directory holding anubis.wxs and the config templates")
+ stagingDir = flag.String("staging-dir", filepath.Join("var", "mkmsi"), "directory to stage the MSI build in; an subdirectory is used and its previous contents are removed first")
+)
+
+// The installer is 64-bit only. anubis.wxs installs into ProgramFiles64Folder
+// and marks its components Win64, so there is no meaningful 32-bit build to
+// select. An --arch flag here would only let a caller produce an MSI that
+// claims to be 32-bit while installing 64-bit components.
+const (
+ msiArch = "x64"
+ msiWin64 = "yes"
+
+ // msiInstallerVersionAmd64 declares the Windows Installer engine version
+ // the package requires. 200 is the long-standing baseline and is what
+ // amd64 has always shipped.
+ msiInstallerVersionAmd64 = "200"
+ // msiInstallerVersionArm64 must be 500: the Arm64 package template (see
+ // setArm64Template) was only introduced in Windows Installer 5.0. An MSI
+ // declaring a lower InstallerVersion alongside an Arm64 template risks
+ // being rejected on the target as "not supported by this processor
+ // type" instead of failing at build time.
+ msiInstallerVersionArm64 = "500"
+)
+
+func main() {
+ flag.Parse()
+
+ if *zipPath == "" || *outPath == "" {
+ log.Fatal("both --zip and --out are required")
+ }
+
+ if err := build(); err != nil {
+ log.Fatalf("%v", err)
+ }
+
+ fmt.Println(*outPath)
+}
+
+func build() error {
+ version, err := versionFromZipName(*zipPath)
+ if err != nil {
+ return err
+ }
+
+ arch, err := archFromZipName(*zipPath)
+ if err != nil {
+ return err
+ }
+
+ msiVer, err := msiVersion(version)
+ if err != nil {
+ return err
+ }
+
+ code, err := productCode(version, arch)
+ if err != nil {
+ return err
+ }
+
+ // Computed here, from the raw version string, rather than inside
+ // runWixl/patchSummaryInfo: those only ever see msiVer, the already-
+ // converted numeric x.y.z.w form, which msiVersion (and therefore
+ // packageCode) cannot parse back.
+ pkgCode, err := packageCode(version, arch)
+ if err != nil {
+ return err
+ }
+
+ // Staged per architecture so an amd64 and an arm64 build running one
+ // after the other -- as both branches of buildTestMSI do -- cannot
+ // contaminate each other's tree.
+ staging := filepath.Join(*stagingDir, arch)
+
+ // Wipe any previous run's contents before staging fresh ones. A leftover
+ // file from an earlier build would otherwise still be sitting in
+ // staging and silently end up in this MSI. The tree is intentionally
+ // left in place after a successful build (no deferred cleanup) so it
+ // can be inspected -- var/mkmsi already only lives under a gitignored
+ // directory, and being able to diff two builds' staging trees directly
+ // is worth more than tidying up after every run.
+ if err := os.RemoveAll(staging); err != nil {
+ return fmt.Errorf("mkmsi: cannot clear staging directory %s: %w", staging, err)
+ }
+ if err := os.MkdirAll(staging, 0o755); err != nil {
+ return fmt.Errorf("mkmsi: cannot create staging directory %s: %w", staging, err)
+ }
+
+ _, srcMTime, err := unzip(*zipPath, staging)
+ if err != nil {
+ return err
+ }
+
+ if err := stageConfigTemplates(staging, srcMTime); err != nil {
+ return err
+ }
+
+ docWxs := filepath.Join(staging, "doc-files.wxs")
+ if err := generateDocFragment(staging, docWxs); err != nil {
+ return err
+ }
+
+ return runWixl(staging, docWxs, msiVer, code, pkgCode, arch)
+}
+
+// stageConfigTemplates builds the etc directory the installer ships: the env
+// file as written, and the default policy with the Windows logging block
+// appended. mtime is stamped on both, so they carry the same reproducible
+// mtime as everything unzip extracted from the source zip; see concatFiles.
+func stageConfigTemplates(staging string, mtime time.Time) error {
+ etc := filepath.Join(staging, "etc")
+
+ if err := concatFiles(filepath.Join(etc, "anubis.env"), mtime, filepath.Join(*packagingDir, "anubis.env")); err != nil {
+ return err
+ }
+
+ policy := filepath.Join(staging, "doc", "botPolicies.yaml")
+ if err := concatFiles(filepath.Join(etc, "anubis.yaml"), mtime, policy, filepath.Join(*packagingDir, "logging.yaml")); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// generateDocFragment runs wixl-heat over the documentation tree. The file
+// list is sorted so the fragment, and therefore the MSI, is reproducible.
+func generateDocFragment(staging, out string) error {
+ docDir := filepath.Join(staging, "doc")
+
+ var files []string
+ err := filepath.WalkDir(docDir, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if !d.IsDir() {
+ files = append(files, path)
+ }
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("mkmsi: cannot walk %s: %w", docDir, err)
+ }
+
+ slices.Sort(files)
+
+ // Root the fragment at DOCDIR, which anubis.wxs already declares, and give
+ // it its own source variable. Pointing wixl-heat at INSTALLDIR instead
+ // would make it emit a second "doc" directory alongside the declared one.
+ cmd := exec.Command("wixl-heat",
+ "--prefix", docDir+string(os.PathSeparator),
+ "--directory-ref", "DOCDIR",
+ "--component-group", "DocFiles",
+ "--var", "var.DocSourceDir",
+ "--win64",
+ )
+ cmd.Stdin = strings.NewReader(strings.Join(files, "\n") + "\n")
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ runErr := cmd.Run()
+
+ // Check stderr before the exit status, exactly as runWixl does. wixl
+ // reports a dropped attribute this way and then exits 0, so the exit
+ // status alone cannot be trusted, and a non-zero exit accompanied by a
+ // dropped attribute must still surface as ErrWixlDroppedAttribute.
+ if err := checkWixlOutput(stderr.String()); err != nil {
+ return err
+ }
+
+ if runErr != nil {
+ return fmt.Errorf("mkmsi: wixl-heat failed: %w: %s", runErr, stderr.String())
+ }
+
+ // wixl-heat randomizes its Directory IDs on every invocation, even over
+ // an identical tree; see rewriteDirectoryIDs for the details and why
+ // that alone breaks build reproducibility.
+ fragment, err := rewriteDirectoryIDs(stdout.Bytes())
+ if err != nil {
+ return err
+ }
+
+ if err := os.WriteFile(out, fragment, 0o644); err != nil {
+ return fmt.Errorf("mkmsi: cannot write %s: %w", out, err)
+ }
+
+ return nil
+}
+
+// runWixl compiles the wxs sources into the output MSI. version and code are
+// the MSI ProductVersion and ProductCode (msiVersion/productCode's output);
+// pkgCode is the PackageCode patched in afterward (packageCode's output,
+// still the raw UUID, not yet braced/uppercased).
+func runWixl(staging, docWxs, version, code, pkgCode, arch string) error {
+ if err := os.MkdirAll(filepath.Dir(*outPath), 0o755); err != nil {
+ return fmt.Errorf("mkmsi: cannot create %s: %w", filepath.Dir(*outPath), err)
+ }
+
+ installerVersion := msiInstallerVersionAmd64
+ if arch == "arm64" {
+ installerVersion = msiInstallerVersionArm64
+ }
+
+ cmd := exec.Command("wixl",
+ "-a", msiArch,
+ "--ext", "ui",
+ "-D", "SourceDir="+staging,
+ "-D", "DocSourceDir="+filepath.Join(staging, "doc"),
+ "-D", "Win64="+msiWin64,
+ "-D", "Version="+version,
+ "-D", "ProductCode="+code,
+ "-D", "InstallerVersion="+installerVersion,
+ "-o", *outPath,
+ filepath.Join(*packagingDir, "anubis.wxs"),
+ docWxs,
+ )
+
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ cmd.Stdout = os.Stdout
+
+ runErr := cmd.Run()
+
+ // Check stderr first: wixl reports a dropped attribute this way and then
+ // exits 0, which would otherwise look like success.
+ if err := checkWixlOutput(stderr.String()); err != nil {
+ return err
+ }
+
+ if runErr != nil {
+ return fmt.Errorf("mkmsi: wixl failed: %w: %s", runErr, stderr.String())
+ }
+
+ if err := secureInstallDir(*outPath); err != nil {
+ return err
+ }
+
+ if err := patchInstallerImages(*outPath); err != nil {
+ return err
+ }
+
+ if err := patchSummaryInfo(*outPath, pkgCode, arch); err != nil {
+ return err
+ }
+
+ if err := patchEnvironmentID(*outPath); err != nil {
+ return err
+ }
+
+ if err := patchCustomActionSequence(*outPath); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// installerImage pairs one wixl UI extension Binary stream with the image in
+// *packagingDir that replaces it.
+type installerImage struct {
+ stream string
+ file string
+}
+
+// installerImages lists the streams patchInstallerImages replaces.
+// WixUI_Bmp_Banner is the strip shown across the top of every wizard page;
+// WixUI_Bmp_Dialog is the full-height image on the welcome and exit pages.
+//
+// This is a slice, not a map, so the msibuild arguments below are built in a
+// fixed order: build outputs should be reproducible, and map iteration order
+// is not.
+var installerImages = []installerImage{
+ {"Binary.WixUI_Bmp_Banner", "banner.bmp"},
+ {"Binary.WixUI_Bmp_Dialog", "dialog.bmp"},
+}
+
+// patchInstallerImages replaces wixl's stock WiX banner and dialog artwork
+// with Anubis's own, for both architectures.
+//
+// There is no declarative way to do this: ,
+// how real WiX overrides these, is not supported by wixl. The alternative --
+// pointing --extdir at a local copy of wixl's ext/ui tree so the Binary
+// SourceFile paths can be edited -- would mean vendoring ~18 MS-RL licensed
+// .wxs files into this MIT-licensed repo, so this patches the built MSI's
+// Binary streams directly instead, the same way secureInstallDir and
+// setArm64Template patch other parts of the file after wixl runs.
+func patchInstallerImages(msiPath string) error {
+ args := []string{msiPath}
+ for _, img := range installerImages {
+ args = append(args, "-a", img.stream, filepath.Join(*packagingDir, img.file))
+ }
+
+ cmd := exec.Command("msibuild", args...)
+
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ cmd.Stdout = os.Stdout
+
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("mkmsi: msibuild failed to patch installer images: %w: %s", err, stderr.String())
+ }
+
+ // msibuild's exit status is not proof either stream actually changed --
+ // see secureInstallDir and setArm64Template for why that trust has
+ // already twice proven misplaced in this file. Extract each stream back
+ // and compare its length against the source image rather than assume
+ // the write landed.
+ for _, img := range installerImages {
+ source := filepath.Join(*packagingDir, img.file)
+
+ wantInfo, err := os.Stat(source)
+ if err != nil {
+ return fmt.Errorf("mkmsi: cannot stat %s: %w", source, err)
+ }
+
+ got, err := exec.Command("msiinfo", "extract", msiPath, img.stream).Output()
+ if err != nil {
+ return fmt.Errorf("mkmsi: msiinfo extract %s %s failed: %w", msiPath, img.stream, err)
+ }
+
+ if int64(len(got)) != wantInfo.Size() {
+ return fmt.Errorf("mkmsi: msibuild did not patch %s on %s: stream is %d bytes, %s is %d bytes",
+ img.stream, msiPath, len(got), source, wantInfo.Size())
+ }
+ }
+
+ return nil
+}
+
+// secureInstallDir marks INSTALLDIR as a secure custom property, so that a
+// command-line `msiexec /i anubis.msi INSTALLDIR=...` override survives
+// elevation into the deferred, system-context part of the install. Without
+// it, the override is silently ignored and Anubis installs to the default
+// location anyway.
+//
+// This can't be done declaratively in anubis.wxs. Both obvious forms fail
+// under wixl 0.106:
+//
+// - Property/@Secure="yes" is silently dropped; no SecureCustomProperties
+// row results at all.
+// - A hand-authored collides with
+// the row wixl generates automatically for MajorUpgrade (populated with
+// WIX_UPGRADE_DETECTED and WIX_DOWNGRADE_DETECTED) and aborts the wixl
+// build outright with a bare "libmsi_query_execute" and no further
+// explanation.
+//
+// So, the same way setArm64Template patches the summary Template after the
+// fact, this patches the SecureCustomProperties row after wixl has built it.
+func secureInstallDir(msiPath string) error {
+ existing, err := readProperty(msiPath, "SecureCustomProperties")
+ if err != nil {
+ return err
+ }
+
+ if slices.Contains(strings.Split(existing, ";"), "INSTALLDIR") {
+ return nil
+ }
+
+ want := "INSTALLDIR"
+ if existing != "" {
+ want += ";" + existing
+ }
+
+ // This assumes the SecureCustomProperties row already exists, which
+ // MajorUpgrade above guarantees today. If that ever stops being true,
+ // this UPDATE silently affects zero rows -- but the read-back below
+ // still catches it and fails loudly rather than shipping an MSI where
+ // INSTALLDIR= quietly does nothing.
+ cmd := exec.Command("msibuild", msiPath, "-q",
+ fmt.Sprintf("UPDATE Property SET Value='%s' WHERE Property='SecureCustomProperties'", want))
+
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ cmd.Stdout = os.Stdout
+
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("mkmsi: msibuild failed to secure INSTALLDIR: %w: %s", err, stderr.String())
+ }
+
+ got, err := readProperty(msiPath, "SecureCustomProperties")
+ if err != nil {
+ return err
+ }
+
+ if !slices.Contains(strings.Split(got, ";"), "INSTALLDIR") {
+ return fmt.Errorf("mkmsi: msibuild did not add INSTALLDIR to SecureCustomProperties on %s: got %q", msiPath, got)
+ }
+
+ return nil
+}
+
+// readProperty returns one row's value from an MSI's Property table, as
+// reported by `msiinfo export`, or "" if the property has no row.
+func readProperty(msiPath, name string) (string, error) {
+ out, err := exec.Command("msiinfo", "export", msiPath, "Property").Output()
+ if err != nil {
+ return "", fmt.Errorf("mkmsi: msiinfo export %s Property failed: %w", msiPath, err)
+ }
+
+ for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
+ if prop, value, ok := strings.Cut(line, "\t"); ok && prop == name {
+ return value, nil
+ }
+ }
+
+ return "", nil
+}
+
+// patchSummaryInfo rewrites the summary information stream after wixl has
+// built the MSI: the Template field, and the PackageCode (the summary's
+// "Revision number (UUID)" field).
+//
+// Both go through one msibuild -s call site on purpose. msibuild -s
+// overwrites Subject, Template and PackageCode together every time it is
+// called -- there is no way to set one without restating the other two --
+// so a second call site (there used to be one here, setting only Template
+// for arm64) would silently clobber whatever this one had just written, or
+// vice versa depending on call order. One call site that always states all
+// three is the only way they cannot fight.
+//
+// wixl 0.106 has no arm64 target ā it accepts only intel, intel64 and ia64 ā
+// so an arm64 package is built as x64 and its Template corrected here. Only
+// the declared architecture is wrong; the component bitness and the
+// ProgramFiles64Folder install location are already right for arm64.
+//
+// PackageCode is set to a deterministic UUIDv5 (see packageCode) instead of
+// the random value wixl assigns on every build; see packageCode's doc
+// comment for why turning off that randomness is correct once the rest of
+// the build is already reproducible. pkgCode is packageCode's raw output,
+// formatted here to match the braced, uppercase shape wixl itself writes
+// ProductCode and UpgradeCode in.
+func patchSummaryInfo(msiPath, pkgCode, arch string) error {
+ template := "x64;1033"
+ if arch == "arm64" {
+ template = "Arm64;1033"
+ }
+
+ wantCode := "{" + strings.ToUpper(pkgCode) + "}"
+
+ cmd := exec.Command("msibuild", msiPath,
+ "-s", "Anubis Web AI Firewall Utility", "Techaro", template, wantCode,
+ )
+
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ cmd.Stdout = os.Stdout
+
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("mkmsi: msibuild failed to set summary information: %w: %s", err, stderr.String())
+ }
+
+ // msibuild's exit status alone is not proof either field was actually
+ // changed: this project has already learned wixl exits 0 while silently
+ // dropping data, and msibuild deserves no more trust. Read both back and
+ // fail loudly rather than shipping an MSI with the wrong Template, or a
+ // PackageCode nobody can reproduce.
+ gotTemplate, err := readSummaryTemplate(msiPath)
+ if err != nil {
+ return err
+ }
+ if gotTemplate != template {
+ return fmt.Errorf("mkmsi: msibuild did not set the summary template on %s: got %q, want %q", msiPath, gotTemplate, template)
+ }
+
+ gotCode, err := readSummaryPackageCode(msiPath)
+ if err != nil {
+ return err
+ }
+ if gotCode != wantCode {
+ return fmt.Errorf("mkmsi: msibuild did not set the PackageCode on %s: got %q, want %q", msiPath, gotCode, wantCode)
+ }
+
+ return nil
+}
+
+// readSummaryTemplate returns the Template field from an MSI's summary
+// information stream, as reported by `msiinfo suminfo`.
+func readSummaryTemplate(msiPath string) (string, error) {
+ out, err := exec.Command("msiinfo", "suminfo", msiPath).Output()
+ if err != nil {
+ return "", fmt.Errorf("mkmsi: msiinfo suminfo %s failed: %w", msiPath, err)
+ }
+
+ for _, line := range strings.Split(string(out), "\n") {
+ if rest, ok := strings.CutPrefix(line, "Template:"); ok {
+ return strings.TrimSpace(rest), nil
+ }
+ }
+
+ return "", fmt.Errorf("mkmsi: msiinfo suminfo %s has no Template line", msiPath)
+}
+
+// readSummaryPackageCode returns the "Revision number (UUID)" field -- the
+// PackageCode -- from an MSI's summary information stream, as reported by
+// `msiinfo suminfo`.
+func readSummaryPackageCode(msiPath string) (string, error) {
+ out, err := exec.Command("msiinfo", "suminfo", msiPath).Output()
+ if err != nil {
+ return "", fmt.Errorf("mkmsi: msiinfo suminfo %s failed: %w", msiPath, err)
+ }
+
+ for _, line := range strings.Split(string(out), "\n") {
+ if rest, ok := strings.CutPrefix(line, "Revision number (UUID):"); ok {
+ return strings.TrimSpace(rest), nil
+ }
+ }
+
+ return "", fmt.Errorf("mkmsi: msiinfo suminfo %s has no Revision number (UUID) line", msiPath)
+}
+
+// patchEnvironmentID overwrites the Environment table's primary key for the
+// PATH row with a fixed value.
+//
+// wixl 0.106 ignores the Id="env_path" declared in anubis.wxs for this row
+// and assigns a random GUID to the Environment table's primary key column
+// instead, so the row's key differs on every otherwise-identical build.
+//
+// This can't reuse secureInstallDir's UPDATE approach: Environment is the
+// primary key of this table, and the Windows Installer SQL dialect
+// (verified empirically -- msibuild reports "failed to execute query" and
+// libmsi logs a CRITICAL on the attempt) refuses to UPDATE a primary key
+// column. Deleting the row and re-inserting it with the same Name and Value
+// but a fixed key is the documented way around that.
+func patchEnvironmentID(msiPath string) error {
+ const (
+ component = "cmp_path"
+ want = "env_path"
+ )
+
+ name, value, err := readEnvironmentRow(msiPath, component)
+ if err != nil {
+ return err
+ }
+
+ cmd := exec.Command("msibuild", msiPath, "-q",
+ fmt.Sprintf("DELETE FROM Environment WHERE Component_='%s'", sqlEscape(component)),
+ "-q",
+ fmt.Sprintf("INSERT INTO Environment (Environment, Name, Value, Component_) VALUES ('%s', '%s', '%s', '%s')",
+ sqlEscape(want), sqlEscape(name), sqlEscape(value), sqlEscape(component)),
+ )
+
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ cmd.Stdout = os.Stdout
+
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("mkmsi: msibuild failed to patch the Environment table: %w: %s", err, stderr.String())
+ }
+
+ gotID, gotName, gotValue, err := readEnvironmentRowByID(msiPath, want)
+ if err != nil {
+ return err
+ }
+
+ if gotID != want || gotName != name || gotValue != value {
+ return fmt.Errorf("mkmsi: msibuild did not replace the Environment row for %s on %s correctly: got (%q, %q, %q), want (%q, %q, %q)",
+ component, msiPath, gotID, gotName, gotValue, want, name, value)
+ }
+
+ return nil
+}
+
+// sqlEscape doubles single quotes so a value can be embedded in an MSI SQL
+// string literal. None of the values this program passes through it are
+// expected to contain one -- Name and Value come from anubis.wxs, which
+// this project controls -- but the values still flow through here rather
+// than straight into a query string, the same discipline this being
+// security-sensitive software calls for anywhere user- or file-sourced text
+// reaches a query.
+func sqlEscape(s string) string {
+ return strings.ReplaceAll(s, "'", "''")
+}
+
+// readEnvironmentRow returns the Name and Value columns of the Environment
+// table's row for component, as reported by `msiinfo export`.
+func readEnvironmentRow(msiPath, component string) (name, value string, err error) {
+ out, err := exec.Command("msiinfo", "export", msiPath, "Environment").Output()
+ if err != nil {
+ return "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment failed: %w", msiPath, err)
+ }
+
+ for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
+ // Environment Name Value Component_
+ fields := strings.Split(line, "\t")
+ if len(fields) == 4 && fields[3] == component {
+ return fields[1], fields[2], nil
+ }
+ }
+
+ return "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment has no row for component %s", msiPath, component)
+}
+
+// readEnvironmentRowByID returns the Name and Value columns of the
+// Environment table's row keyed by id, as reported by `msiinfo export`.
+func readEnvironmentRowByID(msiPath, id string) (gotID, name, value string, err error) {
+ out, err := exec.Command("msiinfo", "export", msiPath, "Environment").Output()
+ if err != nil {
+ return "", "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment failed: %w", msiPath, err)
+ }
+
+ for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
+ // Environment Name Value Component_
+ fields := strings.Split(line, "\t")
+ if len(fields) == 4 && fields[0] == id {
+ return fields[0], fields[1], fields[2], nil
+ }
+ }
+
+ return "", "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment has no row with key %s", msiPath, id)
+}
+
+// patchCustomActionSequence pins the InstallExecuteSequence Sequence values
+// of SetAnubisExePath and BootstrapConfig -- the two custom actions
+// anubis.wxs schedules only relative to each other and to InstallFiles
+// ("Before BootstrapConfig" and "After InstallFiles" respectively), never to
+// an absolute Sequence number of their own.
+//
+// This is not one of the five sources of drift this file was written to
+// fix; it was found while verifying them. wixl resolves relative
+// Before/After hints into absolute Sequence numbers itself, and that
+// resolution is not deterministic: across repeated builds of
+// byte-identical staged input, it has been observed (empirically, running
+// the same build eight times in a row) to place SetAnubisExePath at either
+// 1402 (immediately after RemoveExistingProducts) or 4001 (immediately
+// after InstallFiles, immediately before BootstrapConfig), with
+// BootstrapConfig following one step behind either way. Both placements
+// satisfy the wxs's own constraints, so wixl's exit status gives no signal
+// anything is wrong.
+//
+// The tightly-packed placement is the one this pins to, because it is the
+// only one actually implied by the wxs text: nothing in anubis.wxs
+// schedules SetAnubisExePath relative to RemoveExistingProducts, so pinning
+// to that position would invent an ordering guarantee the wxs never asked
+// for. InstallFiles's own Sequence is read back rather than hardcoded, so
+// this keeps working if its position ever changes.
+//
+// This corrects the value only, not the table's on-disk row order, which
+// was tried and abandoned: deleting a row and reinserting it under the same
+// Action was observed, empirically, to always land the row back in its
+// original physical slot regardless of when or in what order the insert
+// ran -- slot placement in this MSI table format appears to be a function
+// of the Action string alone, immutable from outside once wixl first
+// writes the row, and not reachable through msibuild's SQL interface. Since
+// Windows Installer executes actions in Sequence order regardless of
+// on-disk row order, that residual is cosmetic -- but it does mean two
+// otherwise byte-identical MSIs can still differ in exactly where this
+// table's rows for SetAnubisExePath and BootstrapConfig physically sit, in
+// addition to the summary information timestamps. TestMSIReproducibleBuild
+// tolerates both.
+func patchCustomActionSequence(msiPath string) error {
+ installFiles, err := readSequenceNumber(msiPath, "InstallFiles")
+ if err != nil {
+ return err
+ }
+
+ // Applied in this fixed order, not map iteration, so the msibuild
+ // invocations themselves are reproducible.
+ type pin struct {
+ action string
+ want int
+ }
+ pins := []pin{
+ {"SetAnubisExePath", installFiles + 1},
+ {"BootstrapConfig", installFiles + 2},
+ }
+
+ for _, p := range pins {
+ cmd := exec.Command("msibuild", msiPath, "-q",
+ fmt.Sprintf("UPDATE InstallExecuteSequence SET Sequence=%d WHERE Action='%s'", p.want, sqlEscape(p.action)))
+
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ cmd.Stdout = os.Stdout
+
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("mkmsi: msibuild failed to pin the sequence for %s: %w: %s", p.action, err, stderr.String())
+ }
+ }
+
+ for _, p := range pins {
+ got, err := readSequenceNumber(msiPath, p.action)
+ if err != nil {
+ return err
+ }
+ if got != p.want {
+ return fmt.Errorf("mkmsi: msibuild did not pin the sequence for %s on %s: got %d, want %d", p.action, msiPath, got, p.want)
+ }
+ }
+
+ return nil
+}
+
+// readSequenceNumber returns the Sequence column for one Action row of the
+// InstallExecuteSequence table, as reported by `msiinfo export`.
+func readSequenceNumber(msiPath, action string) (int, error) {
+ out, err := exec.Command("msiinfo", "export", msiPath, "InstallExecuteSequence").Output()
+ if err != nil {
+ return 0, fmt.Errorf("mkmsi: msiinfo export %s InstallExecuteSequence failed: %w", msiPath, err)
+ }
+
+ for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
+ // Action Condition Sequence
+ fields := strings.Split(line, "\t")
+ if len(fields) == 3 && fields[0] == action {
+ seq, err := strconv.Atoi(fields[2])
+ if err != nil {
+ return 0, fmt.Errorf("mkmsi: InstallExecuteSequence row for %s in %s has a non-numeric Sequence %q: %w", action, msiPath, fields[2], err)
+ }
+ return seq, nil
+ }
+ }
+
+ return 0, fmt.Errorf("mkmsi: msiinfo export %s InstallExecuteSequence has no row for action %s", msiPath, action)
+}
diff --git a/internal/cmd/mkmsi/msi_test.go b/internal/cmd/mkmsi/msi_test.go
new file mode 100644
index 0000000..1666807
--- /dev/null
+++ b/internal/cmd/mkmsi/msi_test.go
@@ -0,0 +1,805 @@
+package main
+
+import (
+ "bytes"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// mkmsiRequireVerifyEnv is the opt-in environment variable that turns a skip
+// into a failure. It must only be set by workflow jobs that actually install
+// msitools and build the zips these tests inspect -- currently
+// package-builds-stable.yml and package-builds-unstable.yml's "Verify MSI
+// contents" step. Gating on CI alone was tried and failed: GitHub Actions
+// sets CI=true on every job, including go.yml, which never installs msitools
+// or runs `go tool yeet`, so that made the main Go workflow fail on every PR.
+const mkmsiRequireVerifyEnv = "MKMSI_REQUIRE_VERIFY"
+
+// skipOrFail skips the test locally but fails it when mkmsiRequireVerifyEnv
+// is set.
+//
+// These tests are the only automated verification that the MSI's tables
+// survived wixl, which silently drops attributes it does not understand. A
+// skip and a pass are both exit 0, so a skip in a job that claims to verify
+// this would show a green check while checking nothing. Everywhere else --
+// including a contributor's laptop and the main Go workflow, neither of
+// which installs msitools -- skipping is right.
+func skipOrFail(t *testing.T, format string, args ...any) {
+ t.Helper()
+
+ if os.Getenv(mkmsiRequireVerifyEnv) == "true" {
+ t.Fatalf("refusing to skip with "+mkmsiRequireVerifyEnv+"=true: "+format, args...)
+ }
+
+ t.Skipf(format, args...)
+}
+
+// requireTool skips the test when a required external program is missing, so
+// contributors without msitools installed are not blocked.
+func requireTool(t *testing.T, name string) {
+ t.Helper()
+
+ if _, err := exec.LookPath(name); err != nil {
+ skipOrFail(t, "%s is not installed, skipping: %v", name, err)
+ }
+}
+
+// findZip returns the Windows zip yeet has built for arch, skipping the test
+// if there is none.
+//
+// It checks both var/ directly and one level of subdirectory: yeet's default
+// destination is var/, but the human partner routinely builds with something
+// like --package-dest-dir ./var/win.
+//
+// No zip at all is always a skip, including with mkmsiRequireVerifyEnv set.
+// There is nothing to verify without a build, and a checkout that never ran
+// `go tool yeet` must not be reported as a broken MSI.
+//
+// Several candidates for the same architecture are normal on a working
+// checkout: var/ accumulates the zips of every release the human partner has
+// built. The one that matters is always the newest, so this picks the
+// candidate with the latest modification time instead of making the
+// contributor delete their own build output to get a green run. Ties break on
+// path order, which only happens when two copies were written in the same
+// filesystem timestamp tick.
+func findZip(t *testing.T, arch string) string {
+ t.Helper()
+
+ pattern := "anubis-*-windows-" + arch + ".zip"
+
+ var matches []string
+ for _, glob := range []string{
+ filepath.Join("..", "..", "..", "var", pattern),
+ filepath.Join("..", "..", "..", "var", "*", pattern),
+ } {
+ found, err := filepath.Glob(glob)
+ if err != nil {
+ t.Fatalf("Glob: %v", err)
+ }
+ matches = append(matches, found...)
+ }
+ sort.Strings(matches)
+
+ switch len(matches) {
+ case 0:
+ t.Skipf("no Windows %s zip in var or var/*, run `go tool yeet` first", arch)
+ case 1:
+ return matches[0]
+ }
+
+ newest := matches[0]
+ newestMod, err := modTime(newest)
+ if err != nil {
+ t.Fatalf("stat %s: %v", newest, err)
+ }
+
+ for _, m := range matches[1:] {
+ mod, err := modTime(m)
+ if err != nil {
+ t.Fatalf("stat %s: %v", m, err)
+ }
+
+ if mod.After(newestMod) {
+ newest, newestMod = m, mod
+ }
+ }
+
+ t.Logf("found %d Windows %s zips under var, using the newest: %s (modified %s)", len(matches), arch, newest, newestMod.Format(time.RFC3339))
+
+ return newest
+}
+
+// modTime returns the modification time of a file.
+func modTime(path string) (time.Time, error) {
+ st, err := os.Stat(path)
+ if err != nil {
+ return time.Time{}, err
+ }
+
+ return st.ModTime(), nil
+}
+
+// buildTestMSI builds an MSI for arch from the newest zip and returns its
+// path.
+func buildTestMSI(t *testing.T, arch string) string {
+ t.Helper()
+
+ requireTool(t, "wixl")
+ requireTool(t, "wixl-heat")
+ requireTool(t, "msiinfo")
+ // Every arch shells out to msibuild now, to patch SecureCustomProperties
+ // after wixl builds the package (see secureInstallDir); arm64 additionally
+ // uses it to patch the summary Template.
+ requireTool(t, "msibuild")
+
+ out := filepath.Join(t.TempDir(), "anubis-"+arch+".msi")
+
+ cmd := exec.Command("go", "run", ".",
+ "--zip", findZip(t, arch),
+ "--out", out,
+ "--packaging-dir", filepath.Join("..", "..", "..", "run", "windows"),
+ "--staging-dir", filepath.Join("..", "..", "..", "var", "mkmsi"),
+ )
+ cmd.Stderr = os.Stderr
+
+ if err := cmd.Run(); err != nil {
+ t.Fatalf("mkmsi failed: %v", err)
+ }
+
+ return out
+}
+
+// exportTable returns one MSI table as text.
+//
+// msiinfo export writes CRLF line endings. Left alone, the trailing \r rides
+// along on whichever column is last in each row -- silently, since it prints
+// invisibly and only breaks exact-match comparisons against that column.
+// Normalizing here means every caller that splits on "\n" and "\t" gets clean
+// fields.
+func exportTable(t *testing.T, msi, table string) string {
+ t.Helper()
+
+ out, err := exec.Command("msiinfo", "export", msi, table).Output()
+ if err != nil {
+ t.Fatalf("msiinfo export %s: %v", table, err)
+ }
+
+ return strings.ReplaceAll(string(out), "\r\n", "\n")
+}
+
+// suminfo returns the value of one field from `msiinfo suminfo`, such as
+// "Template" or "Version", with the "Field:" prefix and surrounding
+// whitespace stripped.
+func suminfo(t *testing.T, msi, field string) string {
+ t.Helper()
+
+ out, err := exec.Command("msiinfo", "suminfo", msi).Output()
+ if err != nil {
+ t.Fatalf("msiinfo suminfo %s: %v", msi, err)
+ }
+
+ prefix := field + ":"
+ for _, line := range strings.Split(string(out), "\n") {
+ if rest, ok := strings.CutPrefix(line, prefix); ok {
+ return strings.TrimSpace(rest)
+ }
+ }
+
+ t.Fatalf("msiinfo suminfo %s has no %q line:\n%s", msi, field, out)
+ return ""
+}
+
+// suminfoVersion returns the numeric InstallerVersion from `msiinfo
+// suminfo`'s Version line, which msitools renders as "200 (c8)".
+func suminfoVersion(t *testing.T, msi string) string {
+ t.Helper()
+
+ v := suminfo(t, msi, "Version")
+ if i := strings.IndexByte(v, ' '); i >= 0 {
+ v = v[:i]
+ }
+
+ return v
+}
+
+// property returns one row's value from the MSI's Property table.
+func property(t *testing.T, msi, name string) string {
+ t.Helper()
+
+ for _, line := range strings.Split(exportTable(t, msi, "Property"), "\n") {
+ fields := strings.SplitN(line, "\t", 2)
+ if len(fields) == 2 && fields[0] == name {
+ return fields[1]
+ }
+ }
+
+ t.Fatalf("property %s not found in %s", name, msi)
+ return ""
+}
+
+// lastTableRow returns the last line of an exported table, which is its
+// final data row when the table has exactly one.
+func lastTableRow(t *testing.T, msi, table string) string {
+ t.Helper()
+
+ lines := strings.Split(strings.TrimRight(exportTable(t, msi, table), "\n"), "\n")
+ if len(lines) == 0 || lines[0] == "" {
+ t.Fatalf("table %s in %s is empty", table, msi)
+ }
+
+ return lines[len(lines)-1]
+}
+
+// componentConditions maps every Component in the MSI to its Condition
+// column, which is empty for components that always install.
+func componentConditions(t *testing.T, msi string) map[string]string {
+ t.Helper()
+
+ conditions := make(map[string]string)
+
+ for _, line := range strings.Split(exportTable(t, msi, "Component"), "\n") {
+ // Component ComponentId Directory_ Attributes Condition KeyPath
+ fields := strings.Split(line, "\t")
+ if len(fields) < 5 {
+ continue
+ }
+
+ // Attributes is a required integer column; the two header rows
+ // (column names, column types) do not parse as one, so this is a
+ // clean way to skip them without hardcoding the header text.
+ if _, err := strconv.Atoi(fields[3]); err != nil {
+ continue
+ }
+
+ conditions[fields[0]] = fields[4]
+ }
+
+ return conditions
+}
+
+func TestMSIContents(t *testing.T) {
+ if runtime.GOOS == "darwin" {
+ t.Skip("skipping on development machines")
+ }
+
+ msi := buildTestMSI(t, "amd64")
+
+ for _, tt := range []struct {
+ name string
+ table string
+ // want are substrings that must all appear in the exported table.
+ want []string
+ }{
+ {
+ name: "service is registered as manual start under its virtual account",
+ table: "ServiceInstall",
+ // Columns: ServiceInstall, Name, DisplayName, ServiceType(16 =
+ // own process), StartType(3 = manual), ErrorControl(1 = normal).
+ //
+ // StartName is the NT SERVICE virtual account the service control
+ // manager creates alongside the service. It has to be the fully
+ // qualified name: a bare "Anubis" or "LocalService" gets looked up
+ // as a local user account and the install fails.
+ want: []string{"svc_anubis\tAnubis\tAnubis\t16\t3\t1", `NT SERVICE\Anubis`},
+ },
+ {
+ name: "service is stopped and deleted on uninstall",
+ table: "ServiceControl",
+ // Event 162 = stop on install, stop and delete on uninstall.
+ want: []string{"Anubis\t162"},
+ },
+ {
+ name: "bin directory is added to the system PATH",
+ table: "Environment",
+ want: []string{"=*PATH", "[BINDIR]"},
+ },
+ {
+ name: "bootstrap custom action is present and deferred",
+ table: "CustomAction",
+ // 3122 = exe named by a property, deferred, no impersonation.
+ want: []string{"SetAnubisExePath\t51", "BootstrapConfig\t3122", "--windows-bootstrap-config"},
+ },
+ {
+ name: "major upgrades are configured",
+ table: "Upgrade",
+ want: []string{"{92F5FC1F-F6F2-4BD1-BBEF-79B8A46C665F}"},
+ },
+ {
+ name: "both binaries and both config templates are installed",
+ table: "File",
+ want: []string{
+ "anubis.exe",
+ "anubis-robots2policy.exe",
+ "fil_tmpl_env",
+ "fil_tmpl_yaml",
+ },
+ },
+ {
+ name: "the documentation tree is installed",
+ table: "File",
+ want: []string{"CHANGELOG.md", "installation.mdx"},
+ },
+ {
+ // Proof the WixUI_Minimal dialog set actually landed in the
+ // MSI rather than being silently dropped: wixl has crashed
+ // internally on hand-authored dialogs before now and emitted
+ // an MSI with no Dialog table at all.
+ name: "the WixUI_Minimal dialog set is present",
+ table: "Dialog",
+ want: []string{"WelcomeEulaDlg", "VerifyReadyDlg", "ProgressDlg", "ExitDialog"},
+ },
+ {
+ // secureInstallDir patches this row in after wixl builds the
+ // MSI (see its doc comment for why it cannot be done
+ // declaratively in anubis.wxs). Without it, a command-line
+ // INSTALLDIR= would not survive elevation into the deferred
+ // part of the install.
+ name: "INSTALLDIR is a secure custom property",
+ table: "Property",
+ want: []string{"SecureCustomProperties\tINSTALLDIR"},
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got := exportTable(t, msi, tt.table)
+
+ for _, want := range tt.want {
+ if !strings.Contains(got, want) {
+ t.Errorf("table %s does not contain %q\ngot:\n%s", tt.table, want, got)
+ }
+ }
+ })
+ }
+}
+
+// TestMSIStartsServiceOnlyOnUpgrade verifies the fix for an upgrade silently
+// leaving Anubis stopped: RemoveExistingProducts sequences before
+// InstallServices, so the outgoing product's ServiceControl (Event=162)
+// stops and deletes the service, and the incoming ServiceInstall recreates it
+// with StartType=demand. Without an explicit start request an upgrade always
+// reports success while leaving the site unprotected.
+//
+// Every ServiceControl row that requests a start (Event bit 0 set) must
+// belong to a Component conditioned on WIX_UPGRADE_DETECTED -- the property
+// MajorUpgrade sets only when an earlier version of Anubis is already
+// installed -- so a fresh install, which has a placeholder target and no
+// signing key, never starts the service.
+func TestMSIStartsServiceOnlyOnUpgrade(t *testing.T) {
+ if runtime.GOOS == "darwin" {
+ t.Skip("skipping on development machines")
+ }
+
+ msi := buildTestMSI(t, "amd64")
+
+ conditions := componentConditions(t, msi)
+
+ var sawStartRow bool
+
+ for _, line := range strings.Split(exportTable(t, msi, "ServiceControl"), "\n") {
+ fields := strings.Split(line, "\t")
+ if len(fields) < 6 || fields[1] != "Anubis" {
+ continue
+ }
+
+ event, err := strconv.Atoi(fields[2])
+ if err != nil {
+ // Header rows carry column names and types, not numbers.
+ continue
+ }
+
+ if event&1 == 0 {
+ continue
+ }
+
+ sawStartRow = true
+
+ component := fields[5]
+ if cond := conditions[component]; cond != "WIX_UPGRADE_DETECTED" {
+ t.Errorf("ServiceControl row %q requests a start (event %d) via component %q, whose condition is %q, want %q",
+ fields[0], event, component, cond, "WIX_UPGRADE_DETECTED")
+ }
+ }
+
+ if !sawStartRow {
+ t.Error("no ServiceControl row for the anubis service requests a start; the upgrade fix appears to be missing")
+ }
+}
+
+func TestMSIArm64(t *testing.T) {
+ if runtime.GOOS == "darwin" {
+ t.Skip("skipping on development machines")
+ }
+
+ amd64 := buildTestMSI(t, "amd64")
+ arm64 := buildTestMSI(t, "arm64")
+
+ t.Run("summary Template names each architecture", func(t *testing.T) {
+ if got, want := suminfo(t, amd64, "Template"), "x64;1033"; got != want {
+ t.Errorf("amd64 Template = %q, want %q", got, want)
+ }
+ if got, want := suminfo(t, arm64, "Template"), "Arm64;1033"; got != want {
+ t.Errorf("arm64 Template = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("InstallerVersion is 500 on arm64, 200 on amd64", func(t *testing.T) {
+ // Arm64 package templates require Windows Installer 5.0; declaring a
+ // lower InstallerVersion risks the MSI being rejected on the target
+ // as "not supported by this processor type".
+ if got, want := suminfoVersion(t, amd64), "200"; got != want {
+ t.Errorf("amd64 Version = %q, want %q", got, want)
+ }
+ if got, want := suminfoVersion(t, arm64), "500"; got != want {
+ t.Errorf("arm64 Version = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("ProductCode differs between architectures", func(t *testing.T) {
+ amdCode := property(t, amd64, "ProductCode")
+ armCode := property(t, arm64, "ProductCode")
+
+ if amdCode == armCode {
+ t.Errorf("amd64 and arm64 MSIs share ProductCode %q; Windows would treat installing one as uninstalling the other", amdCode)
+ }
+ })
+
+ t.Run("ServiceInstall is identical across architectures", func(t *testing.T) {
+ amdSvc := lastTableRow(t, amd64, "ServiceInstall")
+ armSvc := lastTableRow(t, arm64, "ServiceInstall")
+
+ if amdSvc != armSvc {
+ t.Errorf("ServiceInstall row differs between architectures:\namd64: %s\narm64: %s", amdSvc, armSvc)
+ }
+ })
+}
+
+// extractStream returns the raw bytes of one binary stream from an MSI, as
+// reported by `msiinfo extract`.
+func extractStream(t *testing.T, msi, stream string) []byte {
+ t.Helper()
+
+ out, err := exec.Command("msiinfo", "extract", msi, stream).Output()
+ if err != nil {
+ t.Fatalf("msiinfo extract %s %s: %v", msi, stream, err)
+ }
+
+ return out
+}
+
+// TestMSIInstallerImages verifies patchInstallerImages actually replaced
+// wixl's stock WiX banner and dialog artwork with run/windows/banner.bmp and
+// run/windows/dialog.bmp, rather than the msibuild -a calls silently no-oping
+// the way Property/@Secure="yes" did earlier in this file's history. Byte
+// length is a cheap, robust stand-in for a full comparison: it is exactly
+// what changes if someone swaps in a real image and the patch stops running,
+// since the stock artwork's size is fixed and different from Anubis's.
+func TestMSIInstallerImages(t *testing.T) {
+ if runtime.GOOS == "darwin" {
+ t.Skip("skipping on development machines")
+ }
+
+ msi := buildTestMSI(t, "amd64")
+
+ for _, img := range installerImages {
+ t.Run(img.stream, func(t *testing.T) {
+ source := filepath.Join("..", "..", "..", "run", "windows", img.file)
+
+ wantInfo, err := os.Stat(source)
+ if err != nil {
+ t.Fatalf("stat %s: %v", source, err)
+ }
+
+ got := extractStream(t, msi, img.stream)
+
+ if int64(len(got)) != wantInfo.Size() {
+ t.Errorf("stream %s is %d bytes, %s is %d bytes -- patchInstallerImages may not have run",
+ img.stream, len(got), source, wantInfo.Size())
+ }
+ })
+ }
+}
+
+// rtfControlWord matches one RTF control word, with its optional numeric
+// parameter and the single trailing space that terminates it, such as
+// `\ansicpg1252 ` or `\par`.
+var rtfControlWord = regexp.MustCompile(`\\[a-zA-Z]+-?[0-9]*[ ]?`)
+
+// stripRTF reduces an RTF document to plain text: control words (\rtf1,
+// \par, \f0, ...) and group braces are removed, and the rest -- including
+// stray literal text from groups like the font table, which this does not
+// try to identify -- is collapsed to single-spaced words.
+//
+// This is deliberately crude rather than a real RTF parser. It only needs to
+// let TestMSILicenseRTFMatchesLicense find the license wording inside
+// License.rtf; a byte-exact comparison would make that test brittle for no
+// benefit.
+func stripRTF(s string) string {
+ s = rtfControlWord.ReplaceAllString(s, " ")
+ s = strings.NewReplacer("{", " ", "}", " ").Replace(s)
+ return strings.Join(strings.Fields(s), " ")
+}
+
+// TestMSILicenseRTFMatchesLicense fails if run/windows/License.rtf, which
+// WixUI_Minimal's EULA dialog displays, has fallen out of sync with the
+// repo's LICENSE. Someone editing LICENSE has no other reason to think about
+// the installer, so nothing else catches this.
+func TestMSILicenseRTFMatchesLicense(t *testing.T) {
+ license, err := os.ReadFile(filepath.Join("..", "..", "..", "LICENSE"))
+ if err != nil {
+ t.Fatalf("reading LICENSE: %v", err)
+ }
+
+ rtf, err := os.ReadFile(filepath.Join("..", "..", "..", "run", "windows", "License.rtf"))
+ if err != nil {
+ t.Fatalf("reading run/windows/License.rtf: %v", err)
+ }
+
+ if !bytes.HasPrefix(rtf, []byte(`{\rtf1`)) {
+ t.Fatalf("run/windows/License.rtf does not start with %q, is it valid RTF?", `{\rtf1`)
+ }
+
+ rtfText := stripRTF(string(rtf))
+
+ for _, para := range strings.Split(string(license), "\n\n") {
+ // LICENSE hard-wraps its paragraphs; License.rtf does not, so compare
+ // each paragraph as one line.
+ para = strings.Join(strings.Fields(para), " ")
+ if para == "" {
+ continue
+ }
+
+ if !strings.Contains(rtfText, para) {
+ t.Errorf("run/windows/License.rtf is missing text from LICENSE, or has fallen out of sync with it\nmissing paragraph: %q", para)
+ }
+ }
+}
+
+// msiTables returns the sorted list of table names in an MSI, as reported by
+// `msiinfo tables`.
+func msiTables(t *testing.T, msi string) []string {
+ t.Helper()
+
+ out, err := exec.Command("msiinfo", "tables", msi).Output()
+ if err != nil {
+ t.Fatalf("msiinfo tables %s: %v", msi, err)
+ }
+
+ var tables []string
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ if line != "" {
+ tables = append(tables, line)
+ }
+ }
+ sort.Strings(tables)
+
+ return tables
+}
+
+// msiStreams returns the sorted list of stream names in an MSI, as reported
+// by `msiinfo streams`.
+func msiStreams(t *testing.T, msi string) []string {
+ t.Helper()
+
+ out, err := exec.Command("msiinfo", "streams", msi).Output()
+ if err != nil {
+ t.Fatalf("msiinfo streams %s: %v", msi, err)
+ }
+
+ var streams []string
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ if line != "" {
+ streams = append(streams, line)
+ }
+ }
+ sort.Strings(streams)
+
+ return streams
+}
+
+// sortedLines splits s on newlines and sorts the result, so two exports of
+// the same table can be compared as sets when row order is not guaranteed
+// to match.
+func sortedLines(s string) []string {
+ if strings.TrimSpace(s) == "" {
+ return nil
+ }
+ lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
+ sort.Strings(lines)
+ return lines
+}
+
+// diffByteCount returns how many bytes differ between a and b at the same
+// offset, plus any length mismatch, for a more informative log message than
+// a bare "not equal" when two builds turn out not to be byte-identical.
+func diffByteCount(a, b []byte) int {
+ n := 0
+ for i := 0; i < len(a) && i < len(b); i++ {
+ if a[i] != b[i] {
+ n++
+ }
+ }
+ if len(a) > len(b) {
+ n += len(a) - len(b)
+ } else {
+ n += len(b) - len(a)
+ }
+ return n
+}
+
+// requireSuminfoMatchesExceptTimestamps fails the test if two MSIs' summary
+// information differs anywhere other than the Created and Last saved
+// fields. wixl stamps both from the wall clock when it builds the package,
+// and msibuild's -s -- the only tool available to rewrite summary
+// information -- has no argument for either one; see
+// TestMSIReproducibleBuild's doc comment.
+func requireSuminfoMatchesExceptTimestamps(t *testing.T, msi1, msi2 string) {
+ t.Helper()
+
+ out1, err := exec.Command("msiinfo", "suminfo", msi1).Output()
+ if err != nil {
+ t.Fatalf("msiinfo suminfo %s: %v", msi1, err)
+ }
+ out2, err := exec.Command("msiinfo", "suminfo", msi2).Output()
+ if err != nil {
+ t.Fatalf("msiinfo suminfo %s: %v", msi2, err)
+ }
+
+ lines1 := strings.Split(strings.TrimRight(string(out1), "\n"), "\n")
+ lines2 := strings.Split(strings.TrimRight(string(out2), "\n"), "\n")
+
+ if len(lines1) != len(lines2) {
+ t.Fatalf("suminfo line count differs between %s (%d) and %s (%d):\n%s\nvs\n%s",
+ msi1, len(lines1), msi2, len(lines2), out1, out2)
+ }
+
+ for i := range lines1 {
+ if lines1[i] == lines2[i] {
+ continue
+ }
+ if strings.HasPrefix(lines1[i], "Created:") || strings.HasPrefix(lines1[i], "Last saved:") {
+ continue
+ }
+ t.Errorf("summary information differs beyond the known-unfixable Created/Last saved timestamps:\n%q\nvs\n%q", lines1[i], lines2[i])
+ }
+}
+
+// TestMSIReproducibleBuild builds the same zip into two separate MSIs and
+// asserts the results match, aside from two residuals that could not be
+// removed with the tools available (msitools' wixl, wixl-heat and
+// msibuild):
+//
+// - The summary information's Created and Last saved timestamps: wixl
+// stamps both from the wall clock when it builds the package, and
+// msibuild's -s -- the only available way to rewrite summary
+// information -- has no argument for either one.
+// - The InstallExecuteSequence table's on-disk row order for
+// SetAnubisExePath and BootstrapConfig. patchCustomActionSequence pins
+// their Sequence *values* deterministically, but not their physical
+// storage position: deleting a row and reinserting it under the same
+// Action was observed, empirically, to always land the row back in its
+// original slot, so nothing reachable through msibuild's SQL interface
+// can move it. Windows Installer executes actions in Sequence order
+// regardless of on-disk row order, so this has no effect on how the
+// installer behaves -- see patchCustomActionSequence's doc comment for
+// the full account.
+//
+// Everything else -- every other table, and every stream including the CAB
+// archive -- is required to be exactly byte-identical.
+func TestMSIReproducibleBuild(t *testing.T) {
+ if runtime.GOOS == "darwin" {
+ t.Skip("skipping on development machines")
+ }
+
+ requireTool(t, "wixl")
+ requireTool(t, "wixl-heat")
+ requireTool(t, "msiinfo")
+ requireTool(t, "msibuild")
+
+ zip := findZip(t, "amd64")
+
+ build := func(out string) {
+ t.Helper()
+
+ cmd := exec.Command("go", "run", ".",
+ "--zip", zip,
+ "--out", out,
+ "--packaging-dir", filepath.Join("..", "..", "..", "run", "windows"),
+ "--staging-dir", filepath.Join("..", "..", "..", "var", "mkmsi"),
+ )
+ cmd.Stderr = os.Stderr
+
+ if err := cmd.Run(); err != nil {
+ t.Fatalf("mkmsi failed building %s: %v", out, err)
+ }
+ }
+
+ out1 := filepath.Join(t.TempDir(), "build1.msi")
+ out2 := filepath.Join(t.TempDir(), "build2.msi")
+ build(out1)
+ build(out2)
+
+ data1, err := os.ReadFile(out1)
+ if err != nil {
+ t.Fatalf("reading %s: %v", out1, err)
+ }
+ data2, err := os.ReadFile(out2)
+ if err != nil {
+ t.Fatalf("reading %s: %v", out2, err)
+ }
+
+ if bytes.Equal(data1, data2) {
+ // Byte-identical: every check below would necessarily pass too.
+ return
+ }
+
+ t.Logf("%s and %s are not byte-identical (%d of %d bytes differ); checking whether the difference is limited to the known residuals",
+ out1, out2, diffByteCount(data1, data2), max(len(data1), len(data2)))
+
+ requireSuminfoMatchesExceptTimestamps(t, out1, out2)
+
+ tables1 := msiTables(t, out1)
+ tables2 := msiTables(t, out2)
+ if !slices.Equal(tables1, tables2) {
+ t.Fatalf("table lists differ:\nbuild1: %v\nbuild2: %v", tables1, tables2)
+ }
+
+ for _, table := range tables1 {
+ switch table {
+ case "_SummaryInformation":
+ // Already checked, field by field, via `msiinfo suminfo`
+ // above -- more precisely than a raw property-stream export
+ // could, since it can name exactly which field differs.
+ continue
+
+ case "InstallExecuteSequence":
+ // Row order in this one table is a known residual; compare it
+ // as a set of rows instead of as ordered text. If the values
+ // themselves differ, that is a real bug in
+ // patchCustomActionSequence, not a tolerated residual.
+ rows1 := sortedLines(exportTable(t, out1, table))
+ rows2 := sortedLines(exportTable(t, out2, table))
+ if !slices.Equal(rows1, rows2) {
+ t.Errorf("table %s differs even as a set of rows (this would mean the Sequence *values* differ, not just row order):\nbuild1: %v\nbuild2: %v",
+ table, rows1, rows2)
+ }
+ continue
+ }
+
+ if got, want := exportTable(t, out1, table), exportTable(t, out2, table); got != want {
+ t.Errorf("table %s differs:\n--- %s ---\n%s\n--- %s ---\n%s", table, out1, got, out2, want)
+ }
+ }
+
+ streams1 := msiStreams(t, out1)
+ streams2 := msiStreams(t, out2)
+ if !slices.Equal(streams1, streams2) {
+ t.Fatalf("stream lists differ:\nbuild1: %v\nbuild2: %v", streams1, streams2)
+ }
+
+ for _, stream := range streams1 {
+ // OLE marks a property-set stream by prefixing its name with 0x05;
+ // `msiinfo streams` prints that literally, so this is
+ // "\x05SummaryInformation", not "SummaryInformation".
+ if strings.HasSuffix(stream, "SummaryInformation") {
+ // The raw property-set stream backing both the
+ // _SummaryInformation table and `msiinfo suminfo` -- already
+ // checked field by field, with the Created/Last saved
+ // exception, by requireSuminfoMatchesExceptTimestamps above.
+ continue
+ }
+
+ a := extractStream(t, out1, stream)
+ b := extractStream(t, out2, stream)
+ if !bytes.Equal(a, b) {
+ t.Errorf("stream %s differs: %d bytes in build1, %d bytes in build2", stream, len(a), len(b))
+ }
+ }
+}
diff --git a/internal/cmd/mkmsi/version.go b/internal/cmd/mkmsi/version.go
new file mode 100644
index 0000000..0c03d0e
--- /dev/null
+++ b/internal/cmd/mkmsi/version.go
@@ -0,0 +1,151 @@
+package main
+
+import (
+ "errors"
+ "fmt"
+ "regexp"
+ "strconv"
+
+ "github.com/google/uuid"
+)
+
+var (
+ ErrBadVersion = errors.New("mkmsi: cannot parse version")
+ ErrVersionOutOfRange = errors.New("mkmsi: version component out of range")
+)
+
+// upgradeCode is the fixed MSI UpgradeCode for Anubis. Windows uses it to
+// relate one installed version to another. It must never change: changing it
+// makes every future installer fail to upgrade existing installs.
+const upgradeCode = "92f5fc1f-f6f2-4bd1-bbef-79b8a46c665f"
+
+// versionRe matches the versions yeet produces, such as "1.26.2" for a tagged
+// release, "1.27.0-pre1" for a tagged prerelease, and
+// "1.26.2-1-gec3cce8a-dev" for a build off a later commit.
+//
+// It is anchored at both ends on purpose. Without the trailing anchor a string
+// like "1.26.2.4" matches its prefix and silently becomes 1.26.2.0, turning a
+// version this code does not understand into a plausible wrong answer instead
+// of a build failure.
+var versionRe = regexp.MustCompile(`^v?(?P\d+)\.(?P\d+)\.(?P\d+)(?:-pre(?P
\d+))?(?:-(?P\d+)-g[0-9a-fA-F]+)?(?:-dev)?$`)
+
+// versionFields maps the numeric fields of an MSI ProductVersion onto the
+// capture groups of versionRe, in the order they appear in the output, along
+// with the maximum value MSI allows in each.
+//
+// The prerelease number has no field of its own: MSI compares only
+// major.minor.build when deciding whether one package upgrades another, and
+// there is no way to express "1.27.0-pre1 sorts below 1.27.0" in three
+// unsigned numbers. It therefore reaches the installer only through the
+// ProductCode, which hashes the raw version string, so a prerelease and its
+// release are distinct products that share a ProductVersion. The wxs sets
+// AllowSameVersionUpgrades for exactly this reason, so installing 1.27.0 over
+// 1.27.0-pre1 still removes the prerelease instead of leaving both registered.
+var versionFields = []struct {
+ name string
+ group string
+ limit int
+}{
+ {name: "major", group: "major", limit: 255},
+ {name: "minor", group: "minor", limit: 255},
+ {name: "build", group: "patch", limit: 65535},
+ {name: "revision", group: "commits", limit: 65535},
+}
+
+// msiVersion converts a yeet version string into an MSI ProductVersion.
+//
+// MSI requires a numeric major.minor.build.revision, where major and minor are
+// at most 255 and build and revision are at most 65535. The commit count from a
+// dev build becomes the revision; a tagged release gets revision 0.
+//
+// Note that Windows ignores the revision field when deciding whether one
+// package upgrades another, so a dev build and its base release look identical
+// to the installer.
+func msiVersion(in string) (string, error) {
+ m := versionRe.FindStringSubmatch(in)
+ if m == nil {
+ return "", fmt.Errorf("%w: %q", ErrBadVersion, in)
+ }
+
+ parts := make([]int, len(versionFields))
+
+ for i, f := range versionFields {
+ raw := m[versionRe.SubexpIndex(f.group)]
+ if raw == "" {
+ continue
+ }
+
+ n, err := strconv.Atoi(raw)
+ if err != nil {
+ // A digit string too long for an int is semantically out of
+ // range, not malformed. Callers distinguish the two.
+ if errors.Is(err, strconv.ErrRange) {
+ return "", fmt.Errorf("%w: %s %q does not fit in an int", ErrVersionOutOfRange, f.name, raw)
+ }
+ return "", fmt.Errorf("%w: %s %q: %w", ErrBadVersion, f.name, raw, err)
+ }
+
+ if n > f.limit {
+ return "", fmt.Errorf("%w: %s is %d, maximum is %d", ErrVersionOutOfRange, f.name, n, f.limit)
+ }
+
+ parts[i] = n
+ }
+
+ return fmt.Sprintf("%d.%d.%d.%d", parts[0], parts[1], parts[2], parts[3]), nil
+}
+
+// productCode derives the MSI ProductCode for a version and architecture.
+// Every distinct version needs a distinct ProductCode, and rebuilding the
+// same commit must produce the same one, so it is a UUIDv5 of the version and
+// architecture in the UpgradeCode's namespace rather than a random UUID.
+//
+// The architecture is part of the hash input because it, like the version,
+// must vary the ProductCode: two packages built for different architectures
+// still install to the same UpgradeCode family, so if they shared a
+// ProductCode too, Windows would treat them as the same product and
+// installing one would silently uninstall the other.
+func productCode(version, arch string) (string, error) {
+ if _, err := msiVersion(version); err != nil {
+ return "", err
+ }
+
+ ns, err := uuid.Parse(upgradeCode)
+ if err != nil {
+ return "", fmt.Errorf("mkmsi: cannot parse upgrade code %q: %w", upgradeCode, err)
+ }
+
+ return uuid.NewSHA1(ns, []byte(version+"/"+arch)).String(), nil
+}
+
+// packageCode derives the MSI PackageCode -- the summary information's
+// "Revision number (UUID)" field -- for a version and architecture, the
+// same way productCode derives the Product Id: a UUIDv5 in the
+// UpgradeCode's namespace, so rebuilding the same commit reproduces the same
+// value instead of getting whatever wixl randomizes it to.
+//
+// This is a deliberate departure from MSI convention, which calls for a
+// unique PackageCode per built package file -- PackageCode exists to
+// distinguish physical .msi files even when they install the same product,
+// and normally two builds of identical bits still deserve two different
+// PackageCodes because nothing guarantees the bits stayed identical. Making
+// it deterministic is correct here specifically because the rest of this
+// build has been made reproducible: once identical inputs are guaranteed to
+// produce byte-identical output, a PackageCode that still changed on every
+// rebuild would be actively misleading, not conservative.
+//
+// The hash input is distinguished from productCode's ("packagecode/" vs no
+// prefix) so the two never collide: Windows must never see ProductCode and
+// PackageCode take on the same GUID.
+func packageCode(version, arch string) (string, error) {
+ if _, err := msiVersion(version); err != nil {
+ return "", err
+ }
+
+ ns, err := uuid.Parse(upgradeCode)
+ if err != nil {
+ return "", fmt.Errorf("mkmsi: cannot parse upgrade code %q: %w", upgradeCode, err)
+ }
+
+ return uuid.NewSHA1(ns, []byte("packagecode/"+version+"/"+arch)).String(), nil
+}
diff --git a/internal/cmd/mkmsi/version_test.go b/internal/cmd/mkmsi/version_test.go
new file mode 100644
index 0000000..716b8d7
--- /dev/null
+++ b/internal/cmd/mkmsi/version_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestMSIVersion(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ in string
+ want string
+ wantErr error
+ }{
+ {name: "plain release", in: "1.26.2", want: "1.26.2.0"},
+ {name: "v prefix", in: "v1.26.2", want: "1.26.2.0"},
+ {name: "dev build", in: "1.26.2-1-gec3cce8a-dev", want: "1.26.2.1"},
+ {name: "dev build many commits", in: "1.26.2-137-gdeadbee", want: "1.26.2.137"},
+ // Prereleases share a ProductVersion with their release; only the
+ // ProductCode tells them apart. See versionFields.
+ {name: "prerelease", in: "1.27.0-pre1", want: "1.27.0.0"},
+ {name: "prerelease with v prefix", in: "v1.27.0-pre2", want: "1.27.0.0"},
+ {name: "dev build off a prerelease", in: "1.27.0-pre1-4-gec3cce8a-dev", want: "1.27.0.4"},
+ {name: "prerelease number is not a version component", in: "1.27.0-pre256", want: "1.27.0.0"},
+ {name: "major too big", in: "256.0.0", wantErr: ErrVersionOutOfRange},
+ {name: "minor too big", in: "1.256.0", wantErr: ErrVersionOutOfRange},
+ {name: "patch too big", in: "1.0.65536", wantErr: ErrVersionOutOfRange},
+ {name: "revision too big", in: "1.0.0-65536-gdeadbee", wantErr: ErrVersionOutOfRange},
+ {name: "empty", in: "", wantErr: ErrBadVersion},
+ {name: "not a version", in: "devel", wantErr: ErrBadVersion},
+ {name: "two components", in: "1.26", wantErr: ErrBadVersion},
+ {name: "four components", in: "1.26.2.4", wantErr: ErrBadVersion},
+ {name: "trailing garbage", in: "1.26.2extra", wantErr: ErrBadVersion},
+ {name: "garbage after commit hash", in: "1.26.2-1-gdead-devXXX", wantErr: ErrBadVersion},
+ {name: "prerelease without a number", in: "1.27.0-pre", wantErr: ErrBadVersion},
+ {name: "unknown prerelease flavour", in: "1.27.0-rc1", wantErr: ErrBadVersion},
+ {name: "prerelease after commit count", in: "1.27.0-4-gdeadbee-pre1", wantErr: ErrBadVersion},
+ {name: "overflows an int", in: "99999999999999999999.0.0", wantErr: ErrVersionOutOfRange},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := msiVersion(tt.in)
+
+ if tt.wantErr != nil {
+ if !errors.Is(err, tt.wantErr) {
+ t.Fatalf("msiVersion(%q): got error %v, want %v", tt.in, err, tt.wantErr)
+ }
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("msiVersion(%q): unexpected error: %v", tt.in, err)
+ }
+
+ if got != tt.want {
+ t.Errorf("msiVersion(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestProductCodeIsDeterministic(t *testing.T) {
+ const version = "1.26.2-1-gec3cce8a-dev"
+
+ first, err := productCode(version, "amd64")
+ if err != nil {
+ t.Fatalf("productCode(%q): %v", version, err)
+ }
+
+ second, err := productCode(version, "amd64")
+ if err != nil {
+ t.Fatalf("productCode(%q): %v", version, err)
+ }
+
+ if first != second {
+ t.Errorf("productCode is not deterministic: %q != %q", first, second)
+ }
+}
+
+func TestProductCodeVariesByVersion(t *testing.T) {
+ a, err := productCode("1.26.2", "amd64")
+ if err != nil {
+ t.Fatalf("productCode: %v", err)
+ }
+
+ b, err := productCode("1.26.3", "amd64")
+ if err != nil {
+ t.Fatalf("productCode: %v", err)
+ }
+
+ if a == b {
+ t.Errorf("different versions produced the same ProductCode %q", a)
+ }
+}
+
+func TestProductCodeVariesByPrerelease(t *testing.T) {
+ pre, err := productCode("1.27.0-pre1", "amd64")
+ if err != nil {
+ t.Fatalf("productCode: %v", err)
+ }
+
+ release, err := productCode("1.27.0", "amd64")
+ if err != nil {
+ t.Fatalf("productCode: %v", err)
+ }
+
+ // A prerelease and its release compare equal as MSI ProductVersions, so
+ // the ProductCode is the only thing that keeps them from looking like the
+ // same installed package to Windows.
+ if pre == release {
+ t.Errorf("1.27.0-pre1 and 1.27.0 produced the same ProductCode %q", pre)
+ }
+}
+
+func TestProductCodeVariesByArch(t *testing.T) {
+ const version = "1.26.2"
+
+ amd64, err := productCode(version, "amd64")
+ if err != nil {
+ t.Fatalf("productCode: %v", err)
+ }
+
+ arm64, err := productCode(version, "arm64")
+ if err != nil {
+ t.Fatalf("productCode: %v", err)
+ }
+
+ // Sharing a ProductCode across architectures makes Windows treat the two
+ // packages as one product, so installing either one uninstalls the other.
+ if amd64 == arm64 {
+ t.Errorf("amd64 and arm64 produced the same ProductCode %q", amd64)
+ }
+}
+
+func TestProductCodeRejectsBadVersion(t *testing.T) {
+ if _, err := productCode("devel", "amd64"); !errors.Is(err, ErrBadVersion) {
+ t.Errorf("productCode(\"devel\"): got %v, want %v", err, ErrBadVersion)
+ }
+}
diff --git a/internal/dns/cache.go b/internal/dns/cache.go
index aaac1b9..7d05e3c 100644
--- a/internal/dns/cache.go
+++ b/internal/dns/cache.go
@@ -59,12 +59,12 @@ func (d *Dns) forwardCachePut(host string, entries []string) {
if d.cache == nil {
return
}
- d.cache.forward.Set(d.ctx, host, entries, d.cache.forwardTTL)
+ _ = d.cache.forward.Set(d.ctx, host, entries, d.cache.forwardTTL)
}
func (d *Dns) reverseCachePut(addr string, entries []string) {
if d.cache == nil {
return
}
- d.cache.reverse.Set(d.ctx, addr, entries, d.cache.reverseTTL)
+ _ = d.cache.reverse.Set(d.ctx, addr, entries, d.cache.reverseTTL)
}
diff --git a/internal/dns/dns.go b/internal/dns/dns.go
index ca1950c..0863a3d 100644
--- a/internal/dns/dns.go
+++ b/internal/dns/dns.go
@@ -18,12 +18,14 @@ var (
)
type Dns struct {
+ lg *slog.Logger
cache *DnsCache
ctx context.Context
}
-func New(ctx context.Context, cache *DnsCache) *Dns {
+func New(ctx context.Context, cache *DnsCache, lg *slog.Logger) *Dns {
return &Dns{
+ lg: lg,
cache: cache,
ctx: ctx,
}
@@ -31,7 +33,8 @@ func New(ctx context.Context, cache *DnsCache) *Dns {
// ReverseDNS performs a reverse DNS lookup for the given IP address and trims the trailing dot from the results.
func (d *Dns) ReverseDNS(addr string) ([]string, error) {
- slog.Debug("DNS: performing reverse lookup", "addr", addr)
+ lg := d.lg.With()
+ lg.Debug("DNS: performing reverse lookup", "addr", addr)
if cached, ok := d.getCachedReverse(addr); ok {
return cached, nil
@@ -40,14 +43,14 @@ func (d *Dns) ReverseDNS(addr string) ([]string, error) {
names, err := DNSLookupAddr(addr)
if err != nil {
if dnsErr, ok := err.(*net.DNSError); ok && dnsErr.IsNotFound {
- slog.Debug("DNS: no PTR record found", "addr", addr)
+ lg.Debug("DNS: no PTR record found", "addr", addr)
return []string{}, nil
}
- slog.Error("DNS: reverse lookup failed", "addr", addr, "err", err)
+ lg.Error("DNS: reverse lookup failed", "addr", addr, "err", err)
return nil, err
}
- slog.Debug("DNS: reverse lookup successful", "addr", addr, "names", names)
+ lg.Debug("DNS: reverse lookup successful", "addr", addr, "names", names)
trimmedNames := make([]string, len(names))
for i, name := range names {
@@ -60,7 +63,8 @@ func (d *Dns) ReverseDNS(addr string) ([]string, error) {
// LookupHost performs a forward DNS lookup for the given hostname.
func (d *Dns) LookupHost(host string) ([]string, error) {
- slog.Debug("DNS: performing forward lookup", "host", host)
+ lg := d.lg.With()
+ lg.Debug("DNS: performing forward lookup", "host", host)
if cached, ok := d.getCachedForward(host); ok {
return cached, nil
@@ -69,14 +73,14 @@ func (d *Dns) LookupHost(host string) ([]string, error) {
addrs, err := DNSLookupHost(host)
if err != nil {
if dnsErr, ok := err.(*net.DNSError); ok && dnsErr.IsNotFound {
- slog.Debug("DNS: no A/AAAA record found", "host", host)
+ lg.Debug("DNS: no A/AAAA record found", "host", host)
return []string{}, nil
}
- slog.Error("DNS: forward lookup failed", "host", host, "err", err)
+ lg.Error("DNS: forward lookup failed", "host", host, "err", err)
return nil, err
}
- slog.Debug("DNS: forward lookup successful", "host", host, "addrs", addrs)
+ lg.Debug("DNS: forward lookup successful", "host", host, "addrs", addrs)
d.forwardCachePut(host, addrs)
return addrs, nil
}
@@ -84,28 +88,30 @@ func (d *Dns) LookupHost(host string) ([]string, error) {
// verifyFCrDNSInternal performs the second half of the FCrDNS check, using a
// pre-fetched list of names to perform the forward lookups.
func (d *Dns) verifyFCrDNSInternal(addr string, names []string) bool {
+ lg := d.lg.With()
for _, name := range names {
if cached, err := d.LookupHost(name); err == nil {
if slices.Contains(cached, addr) {
- slog.Info("DNS: forward lookup confirmed original IP", "name", name, "addr", addr)
+ lg.Info("DNS: forward lookup confirmed original IP", "name", name, "addr", addr)
return true
}
continue
}
}
- slog.Info("DNS: could not confirm original IP in forward lookups", "addr", addr)
+ lg.Info("DNS: could not confirm original IP in forward lookups", "addr", addr)
return false
}
// VerifyFCrDNS performs a forward-confirmed reverse DNS (FCrDNS) lookup for the given IP address,
// optionally matching against a provided pattern.
func (d *Dns) VerifyFCrDNS(addr string, pattern *string) bool {
+ lg := d.lg.With()
var patternVal string
if pattern != nil {
patternVal = *pattern
}
- slog.Debug("DNS: performing FCrDNS lookup", "addr", addr, "pattern", patternVal)
+ lg.Debug("DNS: performing FCrDNS lookup", "addr", addr, "pattern", patternVal)
names, err := d.ReverseDNS(addr)
if err != nil {
@@ -117,24 +123,24 @@ func (d *Dns) VerifyFCrDNS(addr string, pattern *string) bool {
// If a pattern is provided, check for a match.
if pattern != nil {
- anyNameMatched := false
+ re, err := regexp.Compile(*pattern)
+ if err != nil {
+ lg.Error("DNS: verifyFCrDNS invalid regex pattern", "err", err)
+ return false
+ }
+
+ var matchedNames []string
for _, name := range names {
- matched, err := regexp.MatchString(*pattern, name)
- if err != nil {
- slog.Error("DNS: verifyFCrDNS invalid regex pattern", "err", err)
- return false // Invalid pattern is a failure.
- }
- if matched {
- anyNameMatched = true
- break
+ if re.MatchString(name) {
+ matchedNames = append(matchedNames, name)
}
}
- if !anyNameMatched {
- slog.Debug("DNS: FCrDNS no PTR matches the pattern", "addr", addr, "pattern", *pattern)
+ if len(matchedNames) == 0 {
return false
}
- slog.Debug("DNS: FCrDNS PTR matched pattern, proceeding with forward check", "addr", addr, "pattern", *pattern)
+
+ names = matchedNames
}
// If we're here, either there was no pattern, or the pattern matched.
diff --git a/internal/dns/dns_test.go b/internal/dns/dns_test.go
index 9cbcb0a..2218012 100644
--- a/internal/dns/dns_test.go
+++ b/internal/dns/dns_test.go
@@ -1,7 +1,6 @@
package dns
import (
- "context"
"errors"
"net"
"reflect"
@@ -9,14 +8,15 @@ import (
"time"
"github.com/TecharoHQ/anubis/lib/store/memory"
+ "github.com/neilotoole/slogt/v2"
)
// newTestDNS is a helper function to create a new Dns object with an in-memory cache for testing.
-func newTestDNS(forwardTTL int, reverseTTL int) *Dns {
- ctx := context.Background()
- memStore := memory.New(ctx)
+func newTestDNS(t *testing.T, forwardTTL int, reverseTTL int) *Dns {
+ t.Helper()
+ memStore := memory.New(t.Context())
cache := NewDNSCache(forwardTTL, reverseTTL, memStore)
- return New(ctx, cache)
+ return New(t.Context(), cache, slogt.New(t))
}
// mockLookupAddr is a mock implementation of the net.LookupAddr function.
@@ -75,7 +75,7 @@ func TestMain(m *testing.M) {
}
func TestDns_ArpaReverseIP(t *testing.T) {
- d := newTestDNS(0, 0)
+ d := newTestDNS(t, 0, 0)
tests := []struct {
name string
ip string
@@ -102,7 +102,7 @@ func TestDns_ArpaReverseIP(t *testing.T) {
}
func TestDns_ReverseDNS(t *testing.T) {
- d := newTestDNS(1, 1) // short TTL for testing cache
+ d := newTestDNS(t, 1, 1) // short TTL for testing cache
// First call - cache miss
t.Run("cache miss", func(t *testing.T) {
@@ -173,7 +173,7 @@ func TestDns_ReverseDNS(t *testing.T) {
}
func TestDns_LookupHost(t *testing.T) {
- d := newTestDNS(1, 1)
+ d := newTestDNS(t, 1, 1)
t.Run("cache miss", func(t *testing.T) {
got, err := d.LookupHost("dns.google")
@@ -236,7 +236,7 @@ func TestDns_LookupHost(t *testing.T) {
}
func TestDns_VerifyFCrDNS(t *testing.T) {
- d := newTestDNS(1, 1)
+ d := newTestDNS(t, 1, 1)
// Helper to convert string to *string
p := func(s string) *string {
diff --git a/internal/dns/ghsa_5gwm_367w_7fgj_test.go b/internal/dns/ghsa_5gwm_367w_7fgj_test.go
new file mode 100644
index 0000000..3e43613
--- /dev/null
+++ b/internal/dns/ghsa_5gwm_367w_7fgj_test.go
@@ -0,0 +1,82 @@
+package dns
+
+import (
+ "context"
+ "net"
+ "testing"
+
+ "github.com/neilotoole/slogt/v2"
+)
+
+// TestGHSA_5gwm_367w_7fgj requires the same PTR hostname to match the
+// policy pattern and forward-resolve to the original IP address.
+func TestGHSA_5gwm_367w_7fgj(t *testing.T) {
+ const addr = "192.0.2.42"
+ pattern := `^.*\.yandex\.(ru|com|net)$`
+
+ tests := []struct {
+ name string
+ names []string
+ forward map[string][]string
+ want bool
+ }{
+ {
+ name: "matching PTR does not resolve",
+ names: []string{"fake.yandex.com.", "owned.example."},
+ forward: map[string][]string{"owned.example": {addr}},
+ },
+ {
+ name: "nonmatching PTR comes first",
+ names: []string{"owned.example.", "fake.yandex.com."},
+ forward: map[string][]string{"owned.example": {addr}},
+ },
+ {
+ name: "matching PTR resolves to another IP",
+ names: []string{"fake.yandex.com.", "owned.example."},
+ forward: map[string][]string{
+ "fake.yandex.com": {"192.0.2.99"},
+ "owned.example": {addr},
+ },
+ },
+ {
+ name: "forward confirmed hostname does not match",
+ names: []string{"owned.example."},
+ forward: map[string][]string{"owned.example": {addr}},
+ },
+ {
+ name: "matching hostname is forward confirmed",
+ names: []string{"real.yandex.com."},
+ forward: map[string][]string{"real.yandex.com": {addr}},
+ want: true,
+ },
+ {
+ name: "later matching hostname is forward confirmed",
+ names: []string{"fake.yandex.com.", "real.yandex.com."},
+ forward: map[string][]string{"real.yandex.com": {addr}},
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ originalAddr, originalHost := DNSLookupAddr, DNSLookupHost
+ t.Cleanup(func() {
+ DNSLookupAddr, DNSLookupHost = originalAddr, originalHost
+ })
+ DNSLookupAddr = func(string) ([]string, error) {
+ return tt.names, nil
+ }
+ DNSLookupHost = func(host string) ([]string, error) {
+ if addrs, ok := tt.forward[host]; ok {
+ return addrs, nil
+ }
+ return nil, &net.DNSError{Name: host, IsNotFound: true}
+ }
+
+ d := New(context.Background(), nil, slogt.New(t))
+ if got := d.VerifyFCrDNS(addr, &pattern); got != tt.want {
+ t.Errorf("VerifyFCrDNS(%q, %q) with PTRs %v = %v, want %v", addr, pattern, tt.names, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/dnsbl/answer_test.go b/internal/dnsbl/answer_test.go
new file mode 100644
index 0000000..fa7fce4
--- /dev/null
+++ b/internal/dnsbl/answer_test.go
@@ -0,0 +1,24 @@
+package dnsbl
+
+import (
+ "net"
+ "testing"
+)
+
+func TestNonIPv4Answers(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ ips []net.IP
+ want DroneBLResponse
+ }{
+ {"ipv6 only", []net.IP{net.ParseIP("::1")}, UnknownSpambotOrDrone},
+ {"mixed", []net.IP{net.ParseIP("::1"), net.ParseIP("127.0.0.9")}, HTTPProxy},
+ {"ipv4", []net.IP{net.ParseIP("127.0.0.3")}, IRCDrone},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := responseFromIPs(tc.ips); got != tc.want {
+ t.Fatalf("got=%v want=%v", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/dnsbl/dnsbl.go b/internal/dnsbl/dnsbl.go
index 60edd5c..497f340 100644
--- a/internal/dnsbl/dnsbl.go
+++ b/internal/dnsbl/dnsbl.go
@@ -59,7 +59,7 @@ func reverse6(ip net.IP) string {
lowNibble := ipBytes[i] & 0x0F
// Append the nibbles in reversed order
- sb.WriteString(fmt.Sprintf("%x.%x.", lowNibble, highNibble))
+ fmt.Fprintf(&sb, "%x.%x.", lowNibble, highNibble)
}
return sb.String()[:len(sb.String())-1]
@@ -85,11 +85,17 @@ func Lookup(ipStr string) (DroneBLResponse, error) {
return Unknown, err
}
+ return responseFromIPs(ips), nil
+}
+
+func responseFromIPs(ips []net.IP) DroneBLResponse {
if len(ips) != 0 {
for _, ip := range ips {
- return DroneBLResponse(ip.To4()[3]), nil
+ if v4 := ip.To4(); v4 != nil {
+ return DroneBLResponse(v4[3])
+ }
}
}
- return UnknownSpambotOrDrone, nil
+ return UnknownSpambotOrDrone
}
diff --git a/internal/glob/glob.go b/internal/glob/glob.go
index 44c1a67..e2e640d 100644
--- a/internal/glob/glob.go
+++ b/internal/glob/glob.go
@@ -36,7 +36,7 @@ func Glob(pattern, subj string) bool {
end := len(parts) - 1
// Go over the leading parts and ensure they match.
- for i := 0; i < end; i++ {
+ for i := range end {
idx := strings.Index(subj, parts[i])
switch i {
diff --git a/internal/gzip.go b/internal/gzip.go
index c83a0ed..06446e6 100644
--- a/internal/gzip.go
+++ b/internal/gzip.go
@@ -2,11 +2,48 @@ package internal
import (
"compress/gzip"
+ "fmt"
+ "io"
"net/http"
"strings"
+ "sync"
)
+// gzipWriterPools holds one *sync.Pool of *gzip.Writer per compression level.
+//
+// The pools are process-global on purpose. GzipMiddleware is constructed
+// per-request at its RenderIndex call site (the wrapped handler embeds the
+// request-specific challenge page), so a closure-local pool would be created
+// empty, used once, and garbage collected on every challenge render; never
+// actually reusing a writer. Keeping the pools here lets the ~1.18 MiB deflate
+// buffers inside each *gzip.Writer survive across requests regardless of how
+// often the middleware is rebuilt.
+var gzipWriterPools sync.Map // map[int]*sync.Pool
+
+func gzipWriterPool(level int) *sync.Pool {
+ if p, ok := gzipWriterPools.Load(level); ok {
+ return p.(*sync.Pool)
+ }
+ p := &sync.Pool{
+ New: func() any {
+ gz, _ := gzip.NewWriterLevel(io.Discard, level)
+ return gz
+ },
+ }
+ actual, _ := gzipWriterPools.LoadOrStore(level, p)
+ return actual.(*sync.Pool)
+}
+
func GzipMiddleware(level int, next http.Handler) http.Handler {
+ // Validate the level with the same range check gzip.NewWriterLevel uses,
+ // but without allocating a throwaway ~1.18 MiB writer on every (per-request)
+ // middleware construction. gzip only rejects out-of-range levels.
+ if level < gzip.HuffmanOnly || level > gzip.BestCompression {
+ panic(fmt.Sprintf("gzip: invalid compression level: %d", level))
+ }
+
+ pool := gzipWriterPool(level)
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
@@ -14,11 +51,13 @@ func GzipMiddleware(level int, next http.Handler) http.Handler {
}
w.Header().Set("Content-Encoding", "gzip")
- gz, err := gzip.NewWriterLevel(w, level)
- if err != nil {
- panic(err)
- }
- defer gz.Close()
+ gz := pool.Get().(*gzip.Writer)
+ gz.Reset(w)
+ defer func() {
+ _ = gz.Close()
+ gz.Reset(io.Discard)
+ pool.Put(gz)
+ }()
grw := gzipResponseWriter{ResponseWriter: w, sink: gz}
next.ServeHTTP(grw, r)
diff --git a/internal/gzip_test.go b/internal/gzip_test.go
new file mode 100644
index 0000000..dc9d36a
--- /dev/null
+++ b/internal/gzip_test.go
@@ -0,0 +1,146 @@
+package internal
+
+import (
+ "bytes"
+ "compress/gzip"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// gzipTestPayload returns a deterministic, compressible body so the gzip
+// middleware tests and benchmark are comparable across runs.
+func gzipTestPayload() []byte {
+ payload := make([]byte, 4096)
+ for i := range payload {
+ payload[i] = byte(i)
+ }
+ return payload
+}
+
+func TestGzipMiddleware(t *testing.T) {
+ payload := gzipTestPayload()
+ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write(payload)
+ })
+
+ t.Run("compresses when client accepts gzip", func(t *testing.T) {
+ h := GzipMiddleware(gzip.BestSpeed, inner)
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ rec := httptest.NewRecorder()
+
+ h.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "gzip" {
+ t.Fatalf("Content-Encoding = %q, want %q", got, "gzip")
+ }
+
+ gz, err := gzip.NewReader(rec.Body)
+ if err != nil {
+ t.Fatalf("response body is not valid gzip: %v", err)
+ }
+ got, err := io.ReadAll(gz)
+ if err != nil {
+ t.Fatalf("can't read gzip body: %v", err)
+ }
+ if !bytes.Equal(got, payload) {
+ t.Fatalf("decompressed body does not match original (got %d bytes, want %d)", len(got), len(payload))
+ }
+ })
+
+ t.Run("passes through when client does not accept gzip", func(t *testing.T) {
+ h := GzipMiddleware(gzip.BestSpeed, inner)
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ rec := httptest.NewRecorder()
+
+ h.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty", got)
+ }
+ if !bytes.Equal(rec.Body.Bytes(), payload) {
+ t.Fatal("body was modified despite client not accepting gzip")
+ }
+ })
+}
+
+// TestGzipMiddlewareInvalidLevel covers the construction-time range check:
+// an out-of-range compression level must panic up front rather than mid-request.
+func TestGzipMiddlewareInvalidLevel(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ level int
+ }{
+ {"below-huffman-only", gzip.HuffmanOnly - 1},
+ {"above-best-compression", gzip.BestCompression + 1},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Fatalf("GzipMiddleware(%d, ...) did not panic on invalid level", tt.level)
+ }
+ }()
+ GzipMiddleware(tt.level, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ })
+ }
+}
+
+// GzipMiddleware is rebuilt on every request at its production
+// call site (RenderIndex wraps the request-specific challenge page), so the
+// *gzip.Writer pool must outlive any single middleware instance. If the pool is
+// ever moved back inside the closure, each request reallocates a ~1.18 MiB
+// deflate writer and the per-request allocation count jumps from the mid-teens
+// into the high thirties. Assert it stays low.
+func TestGzipMiddlewarePoolSurvivesReconstruction(t *testing.T) {
+ payload := gzipTestPayload()
+ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write(payload)
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+
+ serve := func() {
+ // Construct the middleware per call, exactly like RenderIndex does.
+ h := GzipMiddleware(gzip.BestSpeed, inner)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ _, _ = io.Copy(io.Discard, rec.Body)
+ }
+
+ const maxAllocs = 25 // healthy steady state is ~14; a defeated pool is ~37
+ got := testing.AllocsPerRun(50, serve)
+ t.Logf("allocations per (construct + serve): %.0f", got)
+ if got > maxAllocs {
+ t.Fatalf("GzipMiddleware allocates %.0f times per request; want <= %d. "+
+ "The *gzip.Writer pool is likely no longer shared across middleware "+
+ "reconstructions (see gzipWriterPools).", got, maxAllocs)
+ }
+}
+
+// BenchmarkGzipMiddleware exercises the production pattern where the middleware
+// is constructed inside the per-request handler. Constructing it once up front
+// would hide whether the writer pool actually survives reconstruction, which is
+// exactly the regression this benchmark exists to surface.
+func BenchmarkGzipMiddleware(b *testing.B) {
+ payload := gzipTestPayload()
+ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write(payload)
+ })
+
+ b.ReportAllocs()
+ b.RunParallel(func(pb *testing.PB) {
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ for pb.Next() {
+ h := GzipMiddleware(gzip.BestSpeed, inner)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ _, _ = io.Copy(io.Discard, rec.Body)
+ }
+ })
+}
diff --git a/internal/hash.go b/internal/hash.go
index aeec173..c2913b6 100644
--- a/internal/hash.go
+++ b/internal/hash.go
@@ -11,9 +11,8 @@ import (
// SHA256sum computes a cryptographic hash. Still used for proof-of-work challenges
// where we need the security properties of a cryptographic hash function.
func SHA256sum(text string) string {
- hash := sha256.New()
- hash.Write([]byte(text))
- return hex.EncodeToString(hash.Sum(nil))
+ sum := sha256.Sum256([]byte(text))
+ return hex.EncodeToString(sum[:])
}
// FastHash is a high-performance non-cryptographic hash function suitable for
diff --git a/internal/hash_bench_test.go b/internal/hash_bench_test.go
index 5384570..9302d9f 100644
--- a/internal/hash_bench_test.go
+++ b/internal/hash_bench_test.go
@@ -48,7 +48,7 @@ var (
`request.userAgent.matches(".*[Bb]ot.*") || request.userAgent.matches(".*[Cc]rawler.*")`,
}
- // Thoth ASN checker inputs
+ // geoip ASN checker inputs
asnInputs = []string{
"ASNChecker\nAS 15169\nAS 8075\nAS 32934",
"ASNChecker\nAS 13335\nAS 16509\nAS 14061",
@@ -184,7 +184,7 @@ func TestHashCollisions(t *testing.T) {
for _, prefix := range prefixes {
for _, suffix := range suffixes {
for _, variation := range variations {
- for i := 0; i < 100; i++ {
+ for i := range 100 {
input := fmt.Sprintf("%s%s%s-%d", prefix, suffix, variation, i)
hash := XXHash64sum(input)
if existing, exists := xxhashHashes[hash]; exists {
@@ -211,7 +211,7 @@ func TestHashCollisions(t *testing.T) {
seqCount := 0
for _, pattern := range patterns {
- for i := 0; i < 10000; i++ {
+ for i := range 10000 {
input := fmt.Sprintf(pattern, i)
hash := XXHash64sum(input)
if existing, exists := xxhashHashes[hash]; exists {
@@ -251,6 +251,7 @@ func TestXXHashFormat(t *testing.T) {
// Make sure it's all hex characters
for _, char := range hash {
+ //nolint:staticcheck
if !((char >= '0' && char <= '9') || (char >= 'a' && char <= 'f')) {
t.Errorf("Non-hex character %c in hash %s for input %q", char, hash, input)
}
diff --git a/internal/headers.go b/internal/headers.go
index 5293cfb..3e7548a 100644
--- a/internal/headers.go
+++ b/internal/headers.go
@@ -8,6 +8,7 @@ import (
"net"
"net/http"
"net/netip"
+ "slices"
"strings"
"github.com/TecharoHQ/anubis"
@@ -62,7 +63,7 @@ func CustomRealIPHeader(customRealIPHeaderValue string, next http.Handler) http.
})
}
-// RemoteXRealIP sets the X-Real-Ip header to the request's real IP if
+// RemoteXRealIP sets the X-Real-IP header to the request's real IP if
// the setting is enabled by the user.
func RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler) http.Handler {
if !useRemoteAddress {
@@ -74,7 +75,7 @@ func RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler)
// For local sockets there is no real remote address but the localhost
// address should be sensible.
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- r.Header.Set("X-Real-Ip", "127.0.0.1")
+ r.Header.Set("X-Real-IP", "127.0.0.1")
next.ServeHTTP(w, r)
})
}
@@ -84,7 +85,7 @@ func RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler)
if err != nil {
panic(err) // this should never happen
}
- r.Header.Set("X-Real-Ip", host)
+ r.Header.Set("X-Real-IP", host)
if addr, err := netip.ParseAddr(host); err == nil {
r = r.WithContext(context.WithValue(r.Context(), realIPKey{}, addr))
}
@@ -92,14 +93,14 @@ func RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler)
})
}
-// XForwardedForToXRealIP sets the X-Real-Ip header based on the contents
+// XForwardedForToXRealIP sets the X-Real-IP header based on the contents
// of the X-Forwarded-For header.
func XForwardedForToXRealIP(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if xffHeader := r.Header.Get("X-Forwarded-For"); r.Header.Get("X-Real-Ip") == "" && xffHeader != "" {
+ if xffHeader := r.Header.Get("X-Forwarded-For"); r.Header.Get("X-Real-IP") == "" && xffHeader != "" {
ip := xff.Parse(xffHeader)
- slog.Debug("setting X-Real-Ip from X-Forwarded-For", "to", ip, "x-forwarded-for", xffHeader)
- r.Header.Set("X-Real-Ip", ip)
+ slog.DebugContext(r.Context(), "setting X-Real-IP from X-Forwarded-For", "to", ip, "x-forwarded-for", xffHeader)
+ r.Header.Set("X-Real-IP", ip)
if addr, err := netip.ParseAddr(ip); err == nil {
r = r.WithContext(context.WithValue(r.Context(), realIPKey{}, addr))
}
@@ -134,7 +135,7 @@ func XForwardedForUpdate(stripPrivate bool, next http.Handler) http.Handler {
xffHeaderString, err := computeXFFHeader(remoteAddr, origXFFHeader, pref)
if err != nil {
- slog.Debug("computing X-Forwarded-For header failed", "err", err)
+ slog.DebugContext(r.Context(), "computing X-Forwarded-For header failed", "err", err)
return
}
@@ -161,7 +162,7 @@ func computeXFFHeader(remoteAddr string, origXFFHeader string, pref XFFComputePr
return "", fmt.Errorf("%w: %w", ErrCantParseRemoteIP, err)
}
- origForwardedList := make([]string, 0, 4)
+ var origForwardedList []string
if origXFFHeader != "" {
origForwardedList = strings.Split(origXFFHeader, ",")
for i := range origForwardedList {
@@ -203,8 +204,12 @@ func computeXFFHeader(remoteAddr string, origXFFHeader string, pref XFFComputePr
if pref.StripCGNAT && CGNat.Contains(segmentIP) {
continue
}
- forwardedList = append([]string{segmentIP.String()}, forwardedList...)
+ // Build the kept chain in reverse (cheap appends into the
+ // pre-sized slice) and flip it once below, instead of prepending
+ // a freshly allocated slice on every iteration.
+ forwardedList = append(forwardedList, segmentIP.String())
}
+ slices.Reverse(forwardedList)
var xffHeaderString string
if len(forwardedList) == 0 {
xffHeaderString = ""
diff --git a/internal/honeypot/naive/log_permissions_test.go b/internal/honeypot/naive/log_permissions_test.go
new file mode 100644
index 0000000..ec0cfaa
--- /dev/null
+++ b/internal/honeypot/naive/log_permissions_test.go
@@ -0,0 +1,42 @@
+package naive
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/TecharoHQ/anubis/lib/config"
+ "github.com/TecharoHQ/anubis/lib/store/memory"
+)
+
+func TestIPLogPermissions(t *testing.T) {
+ for _, existing := range []bool{false, true} {
+ t.Run(map[bool]string{false: "new", true: "existing"}[existing], func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "ips.log")
+ if existing {
+ if err := os.WriteFile(path, []byte("old"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ i, err := New(&config.Honeypot{IPLogFile: path}, memory.New(ctx), slog.Default())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = i.fout.Close() }()
+ stat, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if stat.Size() != 0 {
+ t.Fatalf("existing contents remain: size=%d", stat.Size())
+ }
+ if got := stat.Mode().Perm(); got != 0600 {
+ t.Fatalf("mode=%o", got)
+ }
+ })
+ }
+}
diff --git a/internal/honeypot/naive/naive.go b/internal/honeypot/naive/naive.go
index f62f4ef..05d276a 100644
--- a/internal/honeypot/naive/naive.go
+++ b/internal/honeypot/naive/naive.go
@@ -1,17 +1,25 @@
package naive
import (
+ "bytes"
"context"
_ "embed"
"fmt"
+ "io"
"log/slog"
+ "math"
"math/rand/v2"
"net/http"
"net/netip"
+ "os"
+ "slices"
+ "sort"
"time"
"github.com/TecharoHQ/anubis/internal"
+ "github.com/TecharoHQ/anubis/internal/bundler"
"github.com/TecharoHQ/anubis/internal/honeypot"
+ "github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/policy/checker"
"github.com/TecharoHQ/anubis/lib/store"
"github.com/a-h/templ"
@@ -36,7 +44,7 @@ var titles string
//go:embed affirmations.txt
var affirmations string
-func New(st store.Interface, lg *slog.Logger) (*Impl, error) {
+func New(cfg *config.Honeypot, st store.Interface, lg *slog.Logger) (*Impl, error) {
affirmation, err := spintax.Parse(affirmations)
if err != nil {
return nil, fmt.Errorf("can't parse affirmations: %w", err)
@@ -52,6 +60,74 @@ func New(st store.Interface, lg *slog.Logger) (*Impl, error) {
return nil, fmt.Errorf("can't parse titles: %w", err)
}
+ var fout *os.File
+ var foutBundler *bundler.Bundler[string]
+
+ if cfg.IPLogFile != "" {
+ lg.InfoContext(context.Background(), "logging honeypot IP addresses", "foutName", cfg.IPLogFile)
+
+ fout, err = os.OpenFile(cfg.IPLogFile, os.O_CREATE|os.O_RDWR, 0600)
+ if err == nil {
+ err = fout.Chmod(0600)
+ if err != nil {
+ _ = fout.Close()
+ }
+ }
+ if err != nil {
+ return nil, fmt.Errorf("can't open ip log file %q: %w", cfg.IPLogFile, err)
+ }
+
+ if _, err := fout.Seek(0, 0); err != nil {
+ return nil, fmt.Errorf("can't rewind ip log file %q: %w", cfg.IPLogFile, err)
+ }
+
+ if err := fout.Truncate(0); err != nil {
+ return nil, fmt.Errorf("can't truncate ip log file %q: %w", cfg.IPLogFile, err)
+ }
+
+ lg := lg.With("in", "foutBundler")
+
+ foutBundler = bundler.New(func(ctx context.Context, ips []string) {
+ st, err := fout.Stat()
+ if err != nil {
+ lg.ErrorContext(ctx, "can't stat ip log file", "foutName", cfg.IPLogFile, "err", err)
+ return
+ }
+
+ if st.Size() >= 65536 {
+ if _, err := fout.Seek(0, 0); err != nil {
+ lg.ErrorContext(ctx, "can't rewind ip log file", "foutName", cfg.IPLogFile, "err", err)
+ return
+ }
+
+ if err := fout.Truncate(0); err != nil {
+ lg.ErrorContext(ctx, "can't truncate ip log file", "foutName", cfg.IPLogFile, "err", err)
+ return
+ }
+ }
+
+ sort.Strings(ips)
+ ips = slices.Compact(ips)
+
+ buf := bytes.NewBuffer(nil)
+ for _, ip := range ips {
+ fmt.Fprintln(buf, ip)
+ }
+
+ if _, err := io.Copy(fout, buf); err != nil {
+ lg.ErrorContext(ctx, "can't write buffered IP addresses to output file", "foutName", cfg.IPLogFile, "err", err)
+ return
+ }
+
+ if err := fout.Sync(); err != nil {
+ lg.ErrorContext(ctx, "can't sync output file", "foutName", cfg.IPLogFile, "err", err)
+ }
+ })
+
+ foutBundler.BundleByteLimit = 32768
+ foutBundler.DelayThreshold = time.Minute
+ }
+
lg.Debug("initialized basic bullshit generator", "affirmations", affirmation.Count(), "bodies", body.Count(), "titles", title.Count())
return &Impl{
@@ -63,6 +139,8 @@ func New(st store.Interface, lg *slog.Logger) (*Impl, error) {
body: body,
title: title,
lg: lg.With("component", "honeypot/naive"),
+ fout: fout,
+ foutBundler: foutBundler,
}, nil
}
@@ -72,38 +150,33 @@ type Impl struct {
uaWeight store.JSON[int]
networkWeight store.JSON[int]
lg *slog.Logger
+ fout *os.File
+ foutBundler *bundler.Bundler[string]
affirmation, body, title spintax.Spintax
}
-func (i *Impl) incrementUA(ctx context.Context, userAgent string) int {
- result, _ := i.uaWeight.Get(ctx, internal.SHA256sum(userAgent))
- result++
- i.uaWeight.Set(ctx, internal.SHA256sum(userAgent), result, time.Hour)
- return result
-}
-
func (i *Impl) incrementNetwork(ctx context.Context, network string) int {
- result, _ := i.networkWeight.Get(ctx, internal.SHA256sum(network))
+ key := internal.SHA256sum(network)
+ result, _ := i.networkWeight.Get(ctx, key)
result++
- i.networkWeight.Set(ctx, internal.SHA256sum(network), result, time.Hour)
+ _ = i.networkWeight.Set(ctx, key, result, time.Hour)
return result
}
-func (i *Impl) CheckUA() checker.Impl {
- return checker.Func(func(r *http.Request) (bool, error) {
- result, _ := i.uaWeight.Get(r.Context(), internal.SHA256sum(r.UserAgent()))
- if result >= 25 {
- return true, nil
- }
-
- return false, nil
- })
-}
-
func (i *Impl) CheckNetwork() checker.Impl {
return checker.Func(func(r *http.Request) (bool, error) {
- result, _ := i.uaWeight.Get(r.Context(), internal.SHA256sum(r.UserAgent()))
+ realIP, _ := internal.RealIP(r)
+ if !realIP.IsValid() {
+ realIP, _ = netip.ParseAddr(r.Header.Get("X-Real-IP"))
+ }
+
+ network, ok := internal.ClampIP(realIP)
+ if !ok {
+ return false, nil
+ }
+
+ result, _ := i.networkWeight.Get(r.Context(), internal.SHA256sum(network.String()))
if result >= 25 {
return true, nil
}
@@ -120,7 +193,7 @@ func (i *Impl) makeAffirmations() []string {
count := rand.IntN(5) + 1
var result []string
- for j := 0; j < count; j++ {
+ for range count {
result = append(result, i.affirmation.Spin())
}
@@ -131,7 +204,7 @@ func (i *Impl) makeSpins() []string {
count := rand.IntN(5) + 1
var result []string
- for j := 0; j < count; j++ {
+ for range count {
result = append(result, i.body.Spin())
}
@@ -153,30 +226,37 @@ func (i *Impl) ServeHTTP(w http.ResponseWriter, r *http.Request) {
realIP, _ := internal.RealIP(r)
if !realIP.IsValid() {
- realIP = netip.MustParseAddr(r.Header.Get("X-Real-Ip"))
+ realIP, _ = netip.ParseAddr(r.Header.Get("X-Real-IP"))
+ }
+
+ if i.foutBundler != nil {
+ rip := realIP.String()
+ _ = i.foutBundler.Add(rip, len(rip)+1) // for the newline
}
network, ok := internal.ClampIP(realIP)
if !ok {
- lg.Error("clampIP failed", "output", network, "ok", ok)
+ lg.ErrorContext(r.Context(), "clampIP failed", "output", network, "ok", ok)
http.Error(w, "The cake is a lie", http.StatusTeapot)
return
}
networkCount := i.incrementNetwork(r.Context(), network.String())
- uaCount := i.incrementUA(r.Context(), r.UserAgent())
stage := r.PathValue("stage")
if stage == "init" {
- lg.Debug("found new entrance point", "id", id, "stage", stage, "userAgent", r.UserAgent(), "clampedIP", network)
+ lg.DebugContext(r.Context(), "found new entrance point", "id", id, "stage", stage, "userAgent", r.UserAgent(), "clampedIP", network)
} else {
- switch {
- case networkCount%256 == 0, uaCount%256 == 0:
- lg.Warn("found possible crawler", "id", id, "network", network)
+ switch networkCount % 256 {
+ case 0:
+ lg.WarnContext(r.Context(), "found possible crawler", "id", id, "network", network, "userAgent", r.UserAgent())
}
}
+ millisecondAmount := min(math.Pow(float64(networkCount), 2), 1000)
+ time.Sleep(time.Duration(millisecondAmount) * time.Millisecond)
+
spins := i.makeSpins()
affirmations := i.makeAffirmations()
title := i.makeTitle()
diff --git a/internal/honeypot/naive/naive_test.go b/internal/honeypot/naive/naive_test.go
new file mode 100644
index 0000000..2644d1c
--- /dev/null
+++ b/internal/honeypot/naive/naive_test.go
@@ -0,0 +1,35 @@
+package naive
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/TecharoHQ/anubis/lib/config"
+ "github.com/TecharoHQ/anubis/lib/store/memory"
+)
+
+func TestInvalidClientIP(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ i, err := New(&config.Honeypot{}, memory.New(ctx), slog.Default())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, ip := range []string{"", "invalid", "1.2.3.999"} {
+ t.Run(ip, func(t *testing.T) {
+ r := httptest.NewRequest("GET", "http://example.com/", nil)
+ r.Header.Set("X-Real-IP", ip)
+ w := httptest.NewRecorder()
+ i.ServeHTTP(w, r)
+ if w.Code != http.StatusTeapot {
+ t.Errorf("status=%d", w.Code)
+ }
+ if match, err := i.CheckNetwork().Check(r); err != nil || match {
+ t.Fatalf("match=%v err=%v", match, err)
+ }
+ })
+ }
+}
diff --git a/internal/honeypot/naive/page_templ.go b/internal/honeypot/naive/page_templ.go
index 0554b1f..4105639 100644
--- a/internal/honeypot/naive/page_templ.go
+++ b/internal/honeypot/naive/page_templ.go
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
-// templ: version: v0.3.960
+// templ: version: v0.3.1070
package naive
//lint:file-ignore SA4006 This context is only used if a nested component is present.
diff --git a/internal/http_server.go b/internal/http_server.go
new file mode 100644
index 0000000..cd78a39
--- /dev/null
+++ b/internal/http_server.go
@@ -0,0 +1,15 @@
+package internal
+
+import (
+ "net/http"
+ "time"
+)
+
+func NewHTTPServer(handler http.Handler) http.Server {
+ return http.Server{
+ Handler: handler,
+ ErrorLog: GetFilteredHTTPLogger(),
+ ReadHeaderTimeout: 10 * time.Second,
+ IdleTimeout: 2 * time.Minute,
+ }
+}
diff --git a/internal/http_server_test.go b/internal/http_server_test.go
new file mode 100644
index 0000000..1f8d2bb
--- /dev/null
+++ b/internal/http_server_test.go
@@ -0,0 +1,59 @@
+package internal
+
+import (
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "testing"
+ "time"
+)
+
+func TestHTTPServerTimeouts(t *testing.T) {
+ s := NewHTTPServer(http.NotFoundHandler())
+ if s.ReadHeaderTimeout <= 0 || s.IdleTimeout <= 0 {
+ t.Fatal("unbounded request connection")
+ }
+ if s.WriteTimeout != 0 {
+ t.Fatal("streaming responses must remain supported")
+ }
+}
+
+func TestHTTPServerClosesIncompleteHeaders(t *testing.T) {
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ called := make(chan struct{}, 1)
+ s := NewHTTPServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called <- struct{}{} }))
+ s.ReadHeaderTimeout = 50 * time.Millisecond
+ go func() {
+ if err := s.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ t.Error(err)
+ }
+ }()
+ t.Cleanup(func() {
+ if err := s.Close(); err != nil {
+ t.Error(err)
+ }
+ })
+ conn, err := net.Dial("tcp", listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = conn.Close() }()
+ if err := conn.SetDeadline(time.Now().Add(time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.WriteString(conn, "GET / HTTP/1.1\r\nHost: example.com\r\nX-Incomplete: "); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := conn.Read(make([]byte, 1)); err != io.EOF {
+ t.Fatalf("expected connection close, got %v", err)
+ }
+ select {
+ case <-called:
+ t.Fatal("incomplete request reached handler")
+ default:
+ }
+}
diff --git a/internal/iplist/iplist.go b/internal/iplist/iplist.go
new file mode 100644
index 0000000..eb75cd7
--- /dev/null
+++ b/internal/iplist/iplist.go
@@ -0,0 +1,47 @@
+// Package iplist parses published bot IP prefix lists in the Google/OpenAI JSON format.
+package iplist
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+)
+
+// Prefix is a single IPv4 or IPv6 CIDR advertised by a bot provider.
+type Prefix struct {
+ IPv4Prefix string `json:"ipv4Prefix"`
+ IPv6Prefix string `json:"ipv6Prefix"`
+}
+
+// PrefixList is a published list of bot IP prefixes.
+type PrefixList struct {
+ CreationTime string `json:"creationTime"`
+ Prefixes []Prefix `json:"prefixes"`
+}
+
+// Parse decodes a JSON document in the Google/OpenAI bot IP range format.
+func Parse(r io.Reader) (*PrefixList, error) {
+ var pl PrefixList
+ if err := json.NewDecoder(r).Decode(&pl); err != nil {
+ return nil, fmt.Errorf("can't decode prefix list: %w", err)
+ }
+ return &pl, nil
+}
+
+// CIDRs returns every IPv4 and IPv6 prefix in the list.
+func (pl *PrefixList) CIDRs() []string {
+ if pl == nil {
+ return nil
+ }
+
+ var prefixes []string
+ for _, p := range pl.Prefixes {
+ switch {
+ case p.IPv4Prefix != "":
+ prefixes = append(prefixes, p.IPv4Prefix)
+ case p.IPv6Prefix != "":
+ prefixes = append(prefixes, p.IPv6Prefix)
+ }
+ }
+ return prefixes
+}
diff --git a/internal/iplist/iplist_test.go b/internal/iplist/iplist_test.go
new file mode 100644
index 0000000..bbfb9e0
--- /dev/null
+++ b/internal/iplist/iplist_test.go
@@ -0,0 +1,107 @@
+package iplist
+
+import (
+ "errors"
+ "io"
+ "slices"
+ "strings"
+ "testing"
+)
+
+func TestParse(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ want []string
+ wantCT string
+ wantErr bool
+ }{
+ {
+ // Published lists (OpenAI, Google, ...) put one address family
+ // per prefixes[] object, so both IPv4 and IPv6 are collected.
+ name: "openai-style",
+ input: `{
+ "creationTime": "2025-01-02T03:04:05.000000",
+ "prefixes": [
+ {"ipv4Prefix": "20.42.10.176/28"},
+ {"ipv6Prefix": "2a01:111:f403:2::/64"}
+ ]
+ }`,
+ want: []string{"20.42.10.176/28", "2a01:111:f403:2::/64"},
+ wantCT: "2025-01-02T03:04:05.000000",
+ },
+ {
+ name: "empty prefixes",
+ input: `{"creationTime": "2025-01-02T03:04:05.000000", "prefixes": []}`,
+ want: nil,
+ wantCT: "2025-01-02T03:04:05.000000",
+ wantErr: false,
+ },
+ {
+ name: "invalid json",
+ input: `{not json`,
+ wantErr: true,
+ },
+ {
+ name: "empty body",
+ input: ``,
+ wantErr: true,
+ },
+ {
+ name: "skips objects with no prefixes",
+ input: `{"creationTime": "t", "prefixes": [{}, {"ipv4Prefix": "1.1.1.1/32"}]}`,
+ want: []string{"1.1.1.1/32"},
+ wantCT: "t",
+ wantErr: false,
+ },
+ {
+ // One prefixes[] object with both fields set is not used by the
+ // published format. CIDRs() treats the fields as exclusive and
+ // keeps ipv4Prefix when both are present (same as iplist2rule).
+ name: "both prefixes prefers ipv4",
+ input: `{"creationTime": "t", "prefixes": [{"ipv4Prefix": "8.8.8.8/32", "ipv6Prefix": "2001:4860:4860::8888/128"}]}`,
+ want: []string{"8.8.8.8/32"},
+ wantCT: "t",
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ pl, err := Parse(strings.NewReader(tt.input))
+ if tt.wantErr {
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("Parse: %v", err)
+ }
+ if pl.CreationTime != tt.wantCT {
+ t.Errorf("CreationTime = %q, want %q", pl.CreationTime, tt.wantCT)
+ }
+ got := pl.CIDRs()
+ if !slices.Equal(got, tt.want) {
+ t.Errorf("CIDRs() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestParseNilReader(t *testing.T) {
+ _, err := Parse(io.NopCloser(strings.NewReader("")))
+ if err == nil {
+ t.Fatal("expected error for empty input")
+ }
+ if !errors.Is(err, io.EOF) && !strings.Contains(err.Error(), "can't decode prefix list") {
+ t.Errorf("unexpected error: %v", err)
+ }
+}
+
+func TestCIDRsNilReceiver(t *testing.T) {
+ var pl *PrefixList
+ if got := pl.CIDRs(); got != nil {
+ t.Errorf("nil receiver CIDRs() = %v, want nil", got)
+ }
+}
diff --git a/internal/ja4h.go b/internal/ja4h.go
index d4c8c1d..fe7c0c3 100644
--- a/internal/ja4h.go
+++ b/internal/ja4h.go
@@ -6,9 +6,15 @@ import (
"github.com/lum8rjack/go-ja4h"
)
+// JA4HHeaderName is the name of the HTTP header that the [JA4H] middleware adds
+// to requests, holding the request's JA4H fingerprint. It is also used to
+// detect whether a policy references the fingerprint, so that the relatively
+// expensive computation can be skipped when no rule needs it.
+const JA4HHeaderName = "X-Http-Fingerprint-Ja4h"
+
func JA4H(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- r.Header.Add("X-Http-Fingerprint-JA4H", ja4h.JA4H(r))
+ r.Header.Set(JA4HHeaderName, ja4h.JA4H(r))
next.ServeHTTP(w, r)
})
}
diff --git a/internal/ja4h_test.go b/internal/ja4h_test.go
new file mode 100644
index 0000000..9ef80b3
--- /dev/null
+++ b/internal/ja4h_test.go
@@ -0,0 +1,22 @@
+package internal
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/lum8rjack/go-ja4h"
+)
+
+func TestJA4HReplacesClientFingerprint(t *testing.T) {
+ r := httptest.NewRequest("GET", "http://example.com/", nil)
+ r.Header.Add(JA4HHeaderName, "forged")
+ r.Header.Add(JA4HHeaderName, "another forgery")
+ want := ja4h.JA4H(r)
+ JA4H(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ values := r.Header.Values(JA4HHeaderName)
+ if len(values) != 1 || values[0] != want {
+ t.Fatalf("fingerprint=%q want %q", values, want)
+ }
+ })).ServeHTTP(httptest.NewRecorder(), r)
+}
diff --git a/internal/listor.go b/internal/listor.go
index b6ba57f..73110b7 100644
--- a/internal/listor.go
+++ b/internal/listor.go
@@ -16,7 +16,7 @@ func (lo *ListOr[T]) UnmarshalJSON(data []byte) error {
// Check if first non-whitespace character is '['
firstChar := data[0]
- for i := 0; i < len(data); i++ {
+ for i := range data {
if data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' {
firstChar = data[i]
break
@@ -36,4 +36,4 @@ func (lo *ListOr[T]) UnmarshalJSON(data []byte) error {
}
return nil
-}
\ No newline at end of file
+}
diff --git a/internal/listor_test.go b/internal/listor_test.go
index 31fffbf..f67fc7a 100644
--- a/internal/listor_test.go
+++ b/internal/listor_test.go
@@ -76,4 +76,4 @@ func TestListOr_UnmarshalJSON(t *testing.T) {
t.Errorf("Expected [1, 2, 3], got %v", lo)
}
})
-}
\ No newline at end of file
+}
diff --git a/internal/log.go b/internal/log.go
index 4b8bd02..fa2a817 100644
--- a/internal/log.go
+++ b/internal/log.go
@@ -42,7 +42,7 @@ func GetRequestLogger(base *slog.Logger, r *http.Request) *slog.Logger {
"accept_language", r.Header.Get("Accept-Language"),
"priority", r.Header.Get("Priority"),
"x-forwarded-for", r.Header.Get("X-Forwarded-For"),
- "x-real-ip", r.Header.Get("X-Real-Ip"),
+ "x-real-ip", r.Header.Get("X-Real-IP"),
)
}
diff --git a/internal/mimetype.go b/internal/mimetype.go
index a0a1566..e7a2c21 100644
--- a/internal/mimetype.go
+++ b/internal/mimetype.go
@@ -3,5 +3,5 @@ package internal
import "mime"
func init() {
- mime.AddExtensionType(".mjs", "text/javascript")
+ _ = mime.AddExtensionType(".mjs", "text/javascript")
}
diff --git a/internal/multifile/multifile.go b/internal/multifile/multifile.go
new file mode 100644
index 0000000..37594d6
--- /dev/null
+++ b/internal/multifile/multifile.go
@@ -0,0 +1,140 @@
+// Package multifile combines multiple fs.File instances into one logical file.
+//
+// This is used in the configuration parsing subsystem to load multiple logical
+// bot rules files as one composite yaml file.
+//
+// See function YAMLList for more information.
+package multifile
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "time"
+)
+
+var (
+ ErrCantOpen = errors.New("multifile: can't open")
+ ErrCantStat = errors.New("multifile: can't stat")
+ ErrCantClose = errors.New("multifile: can't close")
+)
+
+// YAMLList opens multiple files from the given filesystem and gloms them
+// together into one big YAML reader where each component file is its own
+// YAML document.
+//
+// This works because the import logic calls yaml decoding in a loop,
+// making sure that every YAML document is decoded until the file runs
+// out of data.
+//
+// Make sure to call yaml decoding in a loop until this file returns
+// io.EOF.
+func YAMLList(fsys fs.FS, fnames []string) (fs.File, error) {
+ var files []fs.File
+ var readers []io.Reader
+ var errs []error
+ var mfi multiFileInfo
+
+ mfi.name = fmt.Sprintf("multifile: %v", fnames)
+ mfi.mode = 0666 // the filemode of the beast
+
+ for _, fname := range fnames {
+ var (
+ fin fs.File
+ err error
+ )
+
+ switch fsys == nil {
+ case true:
+ fin, err = os.Open(fname)
+ case false:
+ fin, err = fsys.Open(fname)
+ }
+ if err != nil {
+ errs = append(errs, fmt.Errorf("%w: %q: %w", ErrCantOpen, fname, err))
+ continue
+ }
+ files = append(files, fin)
+ readers = append(readers, fin)
+ readers = append(readers, bytes.NewBufferString("\n---\n"))
+ mfi.size += 5
+
+ st, err := fin.Stat()
+ if err != nil {
+ if closeErr := fin.Close(); closeErr != nil {
+ errs = append(errs, fmt.Errorf("%w: %q: %w", ErrCantClose, fname, err))
+ }
+
+ errs = append(errs, fmt.Errorf("%w: %q: %w", ErrCantStat, fname, err))
+ continue
+ }
+
+ mfi.size += st.Size()
+
+ if mfi.modTime.Before(st.ModTime()) {
+ mfi.modTime = st.ModTime()
+ }
+ }
+
+ if len(errs) != 0 {
+ // drain files and clean up
+ for _, fin := range files {
+ _ = fin.Close() // if there's an error here, we're already in trouble
+ }
+
+ return nil, errors.Join(errs...)
+ }
+
+ return multiFile{
+ files: files,
+ reader: io.MultiReader(readers...),
+ st: mfi,
+ }, nil
+}
+
+type multiFile struct {
+ files []fs.File
+ reader io.Reader
+ st fs.FileInfo
+}
+
+func (mf multiFile) Stat() (fs.FileInfo, error) { return mf.st, nil }
+func (mf multiFile) Read(p []byte) (int, error) { return mf.reader.Read(p) }
+
+func (mf multiFile) Close() error {
+ var errs []error
+
+ for _, fin := range mf.files {
+ if err := fin.Close(); err != nil {
+ st, stErr := fin.Stat()
+ if stErr != nil {
+ errs = append(errs, fmt.Errorf("%w: %w", ErrCantStat, err))
+ continue
+ }
+ errs = append(errs, fmt.Errorf("%q (%T): %w", st.Name(), st, err))
+ }
+ }
+
+ if len(errs) != 0 {
+ return fmt.Errorf("%w: %w", ErrCantClose, errors.Join(errs...))
+ }
+
+ return nil
+}
+
+type multiFileInfo struct {
+ name string
+ size int64
+ mode fs.FileMode
+ modTime time.Time
+}
+
+func (mfi multiFileInfo) Name() string { return mfi.name }
+func (mfi multiFileInfo) Size() int64 { return mfi.size }
+func (mfi multiFileInfo) Mode() fs.FileMode { return mfi.mode }
+func (mfi multiFileInfo) ModTime() time.Time { return mfi.modTime }
+func (mfi multiFileInfo) IsDir() bool { return false }
+func (mfi multiFileInfo) Sys() any { return nil }
diff --git a/internal/multifile/multifile_test.go b/internal/multifile/multifile_test.go
new file mode 100644
index 0000000..92ee077
--- /dev/null
+++ b/internal/multifile/multifile_test.go
@@ -0,0 +1,151 @@
+package multifile
+
+import (
+ "bytes"
+ "embed"
+ "errors"
+ "io"
+ "io/fs"
+ "slices"
+ "testing"
+
+ datapkg "github.com/TecharoHQ/anubis/data"
+ "github.com/goreleaser/fileglob"
+ "k8s.io/apimachinery/pkg/util/yaml"
+)
+
+//go:embed testdata/*.yaml testdata/*.json
+var testdata embed.FS
+
+type data struct {
+ Name string `json:"name" yaml:"name"`
+}
+
+type testCase struct {
+ name string
+ fnames []string
+ wantYamlError bool
+ validate func(*testing.T, []data)
+}
+
+func runTestCase(tt testCase, t *testing.T, fsys fs.FS) {
+ fin, err := YAMLList(fsys, tt.fnames)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st, err := fin.Stat()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Log(st.Name())
+ defer func() {
+ if err := fin.Close(); err != nil {
+ t.Logf("can't close file: %v", err)
+ }
+ }()
+
+ var got []data
+
+ dec := yaml.NewYAMLToJSONDecoder(fin)
+
+outer:
+ for {
+ var thisGot []data
+ err = dec.Decode(&thisGot)
+ switch {
+ case errors.Is(err, io.EOF):
+ break outer
+ case err == nil && tt.wantYamlError:
+ t.Error("wanted yaml error but got none")
+ case err != nil && !tt.wantYamlError:
+ t.Errorf("did not want yaml error but got: %v", err)
+ default:
+ if err != nil {
+ t.Log(err)
+ }
+ }
+ got = append(got, thisGot...)
+ }
+
+ if tt.validate != nil {
+ tt.validate(t, got)
+ }
+}
+
+func TestYAMLList(t *testing.T) {
+ for _, tt := range []testCase{
+ {
+ name: "simple happy",
+ fnames: []string{"testdata/a.yaml", "testdata/b.yaml"},
+ validate: func(t *testing.T, got []data) {
+ want := []data{
+ {"foo"},
+ {"bar"},
+ }
+
+ if !slices.EqualFunc(want, got, func(a data, b data) bool { return a.Name == b.Name }) {
+ t.Logf("want: %#v", want)
+ t.Logf(" got: %#v", got)
+ t.Error("did not parse yaml correctly")
+ }
+ },
+ },
+ {
+ name: "invalid object when wanted list",
+ fnames: []string{"testdata/object.yaml"},
+ wantYamlError: true,
+ validate: func(t *testing.T, got []data) {
+ if len(got) != 0 {
+ t.Error("wanted data to not be populated")
+ }
+ },
+ },
+ {
+ name: "mixed indentation",
+ fnames: []string{"testdata/a.yaml", "testdata/b.yaml", "testdata/indented.yaml"},
+ },
+ {
+ name: "mixed json and yaml",
+ fnames: []string{"testdata/a.yaml", "testdata/data.json"},
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Run("embed fs", func(t *testing.T) {
+ runTestCase(tt, t, testdata)
+ })
+ t.Run("os", func(t *testing.T) {
+ runTestCase(tt, t, nil)
+ })
+ })
+ }
+}
+
+func TestReadAllOfData(t *testing.T) {
+ matches, err := fileglob.Glob("{apps,bots,bots/irc-bots,clients,common,crawlers,meta,services}/*.{yaml,yml}", fileglob.WithFs(datapkg.BotPolicies))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Log(matches)
+
+ fin, err := YAMLList(datapkg.BotPolicies, matches)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if err := fin.Close(); err != nil {
+ t.Logf("can't close file: %v", err)
+ }
+ }()
+
+ buf, err := io.ReadAll(fin)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var got []any
+ if err := yaml.NewYAMLToJSONDecoder(bytes.NewBuffer(buf)).Decode(&got); err != nil {
+ t.Fatal(err)
+ }
+
+ t.Logf("read %d entries", len(got))
+}
diff --git a/internal/multifile/testdata/a.yaml b/internal/multifile/testdata/a.yaml
new file mode 100644
index 0000000..1c7d562
--- /dev/null
+++ b/internal/multifile/testdata/a.yaml
@@ -0,0 +1 @@
+- name: foo
diff --git a/internal/multifile/testdata/b.yaml b/internal/multifile/testdata/b.yaml
new file mode 100644
index 0000000..a556bce
--- /dev/null
+++ b/internal/multifile/testdata/b.yaml
@@ -0,0 +1 @@
+- name: bar
diff --git a/internal/multifile/testdata/data.json b/internal/multifile/testdata/data.json
new file mode 100644
index 0000000..c060cb9
--- /dev/null
+++ b/internal/multifile/testdata/data.json
@@ -0,0 +1,5 @@
+[
+ {
+ "name": "foo"
+ }
+]
diff --git a/internal/multifile/testdata/indented.yaml b/internal/multifile/testdata/indented.yaml
new file mode 100644
index 0000000..d4b8952
--- /dev/null
+++ b/internal/multifile/testdata/indented.yaml
@@ -0,0 +1 @@
+- name: boz
diff --git a/internal/multifile/testdata/object.yaml b/internal/multifile/testdata/object.yaml
new file mode 100644
index 0000000..496c821
--- /dev/null
+++ b/internal/multifile/testdata/object.yaml
@@ -0,0 +1 @@
+name: toplevel
diff --git a/internal/ogtags/cache.go b/internal/ogtags/cache.go
index 838d016..9e6d095 100644
--- a/internal/ogtags/cache.go
+++ b/internal/ogtags/cache.go
@@ -5,9 +5,7 @@ import (
"errors"
"log/slog"
"net/url"
- "strings"
"syscall"
- "time"
)
// GetOGTags is the main function that retrieves Open Graph tags for a URL
@@ -31,7 +29,7 @@ func (c *OGTagCache) GetOGTags(ctx context.Context, url *url.URL, originalHost s
// Fetch HTML content, passing the original host
doc, err := c.fetchHTMLDocumentWithCache(ctx, target, originalHost, cacheKey)
if errors.Is(err, syscall.ECONNREFUSED) {
- slog.Debug("Connection refused, returning empty tags")
+ slog.DebugContext(ctx, "Connection refused, returning empty tags")
return nil, nil
} else if errors.Is(err, ErrOgHandled) {
// Error was handled in fetchHTMLDocument, return empty tags
@@ -44,20 +42,8 @@ func (c *OGTagCache) GetOGTags(ctx context.Context, url *url.URL, originalHost s
// Extract OG tags
ogTags := c.extractOGTags(doc)
- // Store in cache
- c.cache.Set(ctx, cacheKey, ogTags, c.ogTimeToLive)
-
- for k, v := range ogTags {
- switch {
- case strings.HasSuffix(k, "image"), strings.HasSuffix(k, "audio"), strings.HasSuffix(k, "secure_url"), strings.HasSuffix(k, "video"):
- v, _ = strings.CutPrefix(v, "http://")
- v, _ = strings.CutPrefix(v, "https://")
- slog.Debug("setting ogtags allow for", "url", k)
- if err := c.cache.Underlying.Set(ctx, "ogtags:allow:"+v, []byte(k), time.Hour); err != nil {
- slog.Debug("can't set ogtag allow cache", "err", err)
- }
- }
- }
+ // Store in cache, the error doesn't matter
+ _ = c.cache.Set(ctx, cacheKey, ogTags, c.ogTimeToLive)
return ogTags, nil
}
@@ -76,9 +62,9 @@ func (c *OGTagCache) generateCacheKey(target string, originalHost string) string
// checkCache checks if we have the tags cached and returns them if so
func (c *OGTagCache) checkCache(ctx context.Context, cacheKey string) map[string]string {
if cachedTags, err := c.cache.Get(ctx, cacheKey); err == nil {
- slog.Debug("cache hit", "tags", cachedTags)
+ slog.DebugContext(ctx, "cache hit", "tags", cachedTags)
return cachedTags
}
- slog.Debug("cache miss", "url", cacheKey)
+ slog.DebugContext(ctx, "cache miss", "url", cacheKey)
return nil
}
diff --git a/internal/ogtags/cache_test.go b/internal/ogtags/cache_test.go
index 9f2c124..1273773 100644
--- a/internal/ogtags/cache_test.go
+++ b/internal/ogtags/cache_test.go
@@ -69,7 +69,9 @@ func TestCheckCache(t *testing.T) {
}
// Manually add to cache
- cache.cache.Set(t.Context(), cacheKey, expectedTags, time.Minute)
+ if err := cache.cache.Set(t.Context(), cacheKey, expectedTags, time.Minute); err != nil {
+ t.Fatal(err)
+ }
// Test cache hit
tags = cache.checkCache(t.Context(), cacheKey)
@@ -94,6 +96,7 @@ func TestGetOGTags(t *testing.T) {
t.Fatalf("Test route loaded more than once, cache failed")
}
w.Header().Set("Content-Type", "text/html")
+ // nolint:errcheck
w.Write([]byte(`
@@ -170,9 +173,9 @@ func TestGetOGTags(t *testing.T) {
}
}
- t.Run("ensure image is cached as allow", func(t *testing.T) {
- if _, err := cache.cache.Underlying.Get(t.Context(), "ogtags:allow:example.com/image.jpg"); errors.Is(err, store.ErrNotFound) {
- t.Fatal("ogtags allow caching for example.com/image.jpg did not work")
+ t.Run("metadata does not authorize assets", func(t *testing.T) {
+ if _, err := cache.cache.Underlying.Get(t.Context(), "ogtags:allow:example.com/image.jpg"); !errors.Is(err, store.ErrNotFound) {
+ t.Fatal("metadata created an authorization cache entry")
}
})
}
@@ -185,6 +188,7 @@ func TestGetOGTagsWithHostConsideration(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
loadCount++ // Increment counter on each request to the server
w.Header().Set("Content-Type", "text/html")
+ // nolint:errcheck
w.Write([]byte(`
diff --git a/internal/ogtags/fetch.go b/internal/ogtags/fetch.go
index 0bfb0a1..a566270 100644
--- a/internal/ogtags/fetch.go
+++ b/internal/ogtags/fetch.go
@@ -40,6 +40,10 @@ func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr stri
// Add proxy headers
req.Header.Set("X-Forwarded-Proto", "https")
+ // Forward Host header as X-Forwarded-Host for webapps to dispatch against
+ if originalHost != "" {
+ req.Header.Set("X-Forwarded-Host", originalHost)
+ }
req.Header.Set("User-Agent", "Anubis-OGTag-Fetcher/1.0") // For tracking purposes
serverName := hostForRequest
@@ -53,8 +57,9 @@ func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr stri
if err != nil {
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
- slog.Debug("og: request timed out", "url", urlStr)
- c.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2) // Cache empty result for half the TTL to not spam the server
+ slog.DebugContext(ctx, "og: request timed out", "url", urlStr)
+ // Cache empty result for half the TTL to not spam the server, errors don't matter
+ _ = c.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2)
}
return nil, fmt.Errorf("http get failed: %w", err)
}
@@ -63,13 +68,14 @@ func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr stri
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
- slog.Debug("og: error closing response body", "url", urlStr, "error", err)
+ slog.DebugContext(ctx, "og: error closing response body", "url", urlStr, "error", err)
}
}(resp.Body)
if resp.StatusCode != http.StatusOK {
- slog.Debug("og: received non-OK status code", "url", urlStr, "status", resp.StatusCode)
- c.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive) // Cache empty result for non-successful status codes
+ slog.DebugContext(ctx, "og: received non-OK status code", "url", urlStr, "status", resp.StatusCode)
+ // Cache empty result for non-successful status codes
+ _ = c.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive)
return nil, fmt.Errorf("%w: page not found", ErrOgHandled)
}
@@ -80,12 +86,12 @@ func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr stri
} else {
mediaType, _, err := mime.ParseMediaType(ct)
if err != nil {
- slog.Debug("og: malformed Content-Type header", "url", urlStr, "contentType", ct)
+ slog.DebugContext(ctx, "og: malformed Content-Type header", "url", urlStr, "contentType", ct)
return nil, fmt.Errorf("%w malformed Content-Type header: %w", ErrOgHandled, err)
}
if mediaType != "text/html" && mediaType != "application/xhtml+xml" {
- slog.Debug("og: unsupported Content-Type", "url", urlStr, "contentType", mediaType)
+ slog.DebugContext(ctx, "og: unsupported Content-Type", "url", urlStr, "contentType", mediaType)
return nil, fmt.Errorf("%w unsupported Content-Type: %s", ErrOgHandled, mediaType)
}
}
@@ -97,7 +103,7 @@ func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr stri
// Check if the error is specifically because the limit was exceeded
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
- slog.Debug("og: content exceeded max length", "url", urlStr, "limit", maxContentLength)
+ slog.DebugContext(ctx, "og: content exceeded max length", "url", urlStr, "limit", maxContentLength)
return nil, fmt.Errorf("content too large: exceeded %d bytes", maxContentLength)
}
return nil, fmt.Errorf("failed to parse HTML: %w", err)
@@ -105,3 +111,14 @@ func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr stri
return doc, nil
}
+
+func sameOriginRedirect(req *http.Request, via []*http.Request) error {
+ if len(via) >= 10 || len(via) == 0 {
+ return ErrOgHandled
+ }
+ origin := via[0].URL
+ if req.URL.Scheme != origin.Scheme || req.URL.Host != origin.Host {
+ return ErrOgHandled
+ }
+ return nil
+}
diff --git a/internal/ogtags/fetch_test.go b/internal/ogtags/fetch_test.go
index 402cb18..e48303d 100644
--- a/internal/ogtags/fetch_test.go
+++ b/internal/ogtags/fetch_test.go
@@ -75,10 +75,10 @@ func TestFetchHTMLDocument(t *testing.T) {
if tt.contentLength > 0 {
// Simulate content length but avoid sending too much actual data
w.Header().Set("Content-Length", fmt.Sprintf("%d", tt.contentLength))
- io.CopyN(w, strings.NewReader("X"), tt.contentLength)
+ io.CopyN(w, strings.NewReader("X"), tt.contentLength) //nolint:errcheck
} else {
w.WriteHeader(tt.statusCode)
- w.Write([]byte(tt.htmlContent))
+ w.Write([]byte(tt.htmlContent)) //nolint:errcheck
}
}))
defer ts.Close()
@@ -136,3 +136,64 @@ func (c *OGTagCache) fetchHTMLDocument(ctx context.Context, urlStr string, origi
cacheKey := c.generateCacheKey(urlStr, originalHost)
return c.fetchHTMLDocumentWithCache(ctx, urlStr, originalHost, cacheKey)
}
+
+// TestFetchForwardsOriginalHostHeader ensures the fetcher forwards the public
+// hostname as X-Forwarded-Host so name-based backends can dispatch.
+func TestFetchForwardsOriginalHostHeader(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ targetHost string
+ originalHost string
+ wantHost string
+ wantForwardedHost string
+ }{
+ {
+ name: "target host pinned, original host still forwarded",
+ targetHost: "origin-herisau.sp-ar.ch",
+ originalHost: "sp-ar.ch",
+ wantHost: "origin-herisau.sp-ar.ch",
+ wantForwardedHost: "sp-ar.ch",
+ },
+ {
+ name: "no target host falls back to original host",
+ targetHost: "",
+ originalHost: "sp-ar.ch",
+ wantHost: "sp-ar.ch",
+ wantForwardedHost: "sp-ar.ch",
+ },
+ {
+ name: "no original host means no forwarded host header",
+ targetHost: "origin-herisau.sp-ar.ch",
+ originalHost: "",
+ wantHost: "origin-herisau.sp-ar.ch",
+ wantForwardedHost: "",
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ var gotHost, gotForwardedHost string
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotHost = r.Host
+ gotForwardedHost = r.Header.Get("X-Forwarded-Host")
+ w.Header().Set("Content-Type", "text/html")
+ w.Write([]byte(``)) //nolint:errcheck
+ }))
+ defer ts.Close()
+
+ cache := NewOGTagCache("", config.OpenGraph{
+ Enabled: true,
+ TimeToLive: time.Minute,
+ }, memory.New(t.Context()), TargetOptions{Host: tt.targetHost})
+
+ if _, err := cache.fetchHTMLDocument(t.Context(), ts.URL, tt.originalHost); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ if gotHost != tt.wantHost {
+ t.Errorf("Host header: got %q, want %q", gotHost, tt.wantHost)
+ }
+ if gotForwardedHost != tt.wantForwardedHost {
+ t.Errorf("X-Forwarded-Host header: got %q, want %q", gotForwardedHost, tt.wantForwardedHost)
+ }
+ })
+ }
+}
diff --git a/internal/ogtags/integration_test.go b/internal/ogtags/integration_test.go
index f13f75f..69df2ba 100644
--- a/internal/ogtags/integration_test.go
+++ b/internal/ogtags/integration_test.go
@@ -11,6 +11,7 @@ import (
"github.com/TecharoHQ/anubis/lib/store/memory"
)
+//nolint:errcheck
func TestIntegrationGetOGTags(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
diff --git a/internal/ogtags/mem_test.go b/internal/ogtags/mem_test.go
index 3770a73..aebb4f6 100644
--- a/internal/ogtags/mem_test.go
+++ b/internal/ogtags/mem_test.go
@@ -95,7 +95,7 @@ func TestMemoryUsage(t *testing.T) {
// Run getTarget many times
u, _ := url.Parse("/path/to/resource?query=1&foo=bar&baz=qux")
- for i := 0; i < 10000; i++ {
+ for range 10000 {
_ = cache.getTarget(u)
}
@@ -129,7 +129,7 @@ func TestMemoryUsage(t *testing.T) {
runtime.GC()
runtime.ReadMemStats(&m1)
- for i := 0; i < 1000; i++ {
+ for range 1000 {
_ = cache.extractOGTags(doc)
}
diff --git a/internal/ogtags/ogtags.go b/internal/ogtags/ogtags.go
index 62cd89c..2efa5e2 100644
--- a/internal/ogtags/ogtags.go
+++ b/internal/ogtags/ogtags.go
@@ -104,8 +104,9 @@ func NewOGTagCache(target string, conf config.OpenGraph, backend store.Interface
}
client := &http.Client{
- Timeout: httpTimeout,
- Transport: transport,
+ Timeout: httpTimeout,
+ CheckRedirect: sameOriginRedirect,
+ Transport: transport,
}
return &OGTagCache{
diff --git a/internal/ogtags/ogtags_fuzz_test.go b/internal/ogtags/ogtags_fuzz_test.go
index 6355eeb..8b7abb9 100644
--- a/internal/ogtags/ogtags_fuzz_test.go
+++ b/internal/ogtags/ogtags_fuzz_test.go
@@ -3,6 +3,7 @@ package ogtags
import (
"context"
"net/url"
+ "slices"
"strings"
"testing"
"unicode/utf8"
@@ -78,7 +79,7 @@ func FuzzGetTarget(f *testing.F) {
}
// Ensure no memory corruption by calling multiple times
- for i := 0; i < 3; i++ {
+ for range 3 {
result2 := cache.getTarget(u)
if result != result2 {
t.Errorf("getTarget not deterministic: %q != %q", result, result2)
@@ -148,11 +149,8 @@ func FuzzExtractOGTags(f *testing.F) {
}
}
if !approved {
- for _, tag := range cache.approvedTags {
- if property == tag {
- approved = true
- break
- }
+ if slices.Contains(cache.approvedTags, property) {
+ approved = true
}
}
if !approved {
@@ -260,11 +258,8 @@ func FuzzExtractMetaTagInfo(f *testing.F) {
}
}
if !approved {
- for _, tag := range cache.approvedTags {
- if property == tag {
- approved = true
- break
- }
+ if slices.Contains(cache.approvedTags, property) {
+ approved = true
}
}
if !approved {
diff --git a/internal/ogtags/ogtags_test.go b/internal/ogtags/ogtags_test.go
index 2b931a8..cf658c8 100644
--- a/internal/ogtags/ogtags_test.go
+++ b/internal/ogtags/ogtags_test.go
@@ -118,7 +118,7 @@ func TestNewOGTagCache_UnixSocket(t *testing.T) {
// Attempt a dummy dial to see if it uses the correct path (optional, more involved check)
dummyConn, err := transport.DialContext(context.Background(), "", "")
if err == nil {
- dummyConn.Close()
+ _ = dummyConn.Close() // error doesn't matter
t.Log("DialContext seems functional, but couldn't verify path without a listener")
} else if !strings.Contains(err.Error(), "connect: connection refused") && !strings.Contains(err.Error(), "connect: no such file or directory") {
// We expect connection refused or not found if nothing is listening
@@ -225,6 +225,7 @@ func TestIntegrationGetOGTags_UnixSocket(t *testing.T) {
}(listener, socketPath)
server := &http.Server{
+ //nolint:errcheck
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprintln(w, `Test`)
@@ -291,6 +292,7 @@ func TestGetOGTagsWithTargetHostOverride(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seenHosts <- r.Host
w.Header().Set("Content-Type", "text/html")
+ //nolint:errcheck
fmt.Fprintln(w, `ok`)
}))
defer ts.Close()
@@ -342,6 +344,7 @@ func TestGetOGTagsWithTargetHostOverride(t *testing.T) {
func TestGetOGTagsWithInsecureSkipVerify(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
+ //nolint:errcheck
fmt.Fprintln(w, `hello`)
})
ts := httptest.NewTLSServer(handler)
@@ -457,6 +460,7 @@ func newSNIServer(t *testing.T, body string) (*httptest.Server, *sniRecorder) {
t.Helper()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
+ //nolint:errcheck
fmt.Fprint(w, body)
})
diff --git a/internal/ogtags/parse.go b/internal/ogtags/parse.go
index c21fd79..9817655 100644
--- a/internal/ogtags/parse.go
+++ b/internal/ogtags/parse.go
@@ -1,6 +1,7 @@
package ogtags
import (
+ "slices"
"strings"
"golang.org/x/net/html"
@@ -65,10 +66,8 @@ func (c *OGTagCache) extractMetaTagInfo(n *html.Node) (property, content string)
}
// Check exact matches
- for _, tag := range c.approvedTags {
- if propertyKey == tag {
- return propertyKey, content
- }
+ if slices.Contains(c.approvedTags, propertyKey) {
+ return propertyKey, content
}
return "", content
diff --git a/internal/ogtags/redirect_test.go b/internal/ogtags/redirect_test.go
new file mode 100644
index 0000000..d94341c
--- /dev/null
+++ b/internal/ogtags/redirect_test.go
@@ -0,0 +1,55 @@
+package ogtags
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/TecharoHQ/anubis/lib/config"
+ "github.com/TecharoHQ/anubis/lib/store/memory"
+)
+
+func TestOGRedirectOrigin(t *testing.T) {
+ for _, sni := range []string{"", "auto"} {
+ t.Run(sni, func(t *testing.T) {
+ var reached atomic.Bool
+ other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ reached.Store(true)
+ w.Header().Set("Content-Type", "text/html")
+ if _, err := w.Write([]byte(``)); err != nil {
+ t.Error(err)
+ }
+ }))
+ defer other.Close()
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/external":
+ http.Redirect(w, r, other.URL, http.StatusFound)
+ case "/local":
+ http.Redirect(w, r, "/document", http.StatusFound)
+ default:
+ w.Header().Set("Content-Type", "text/html")
+ if _, err := w.Write([]byte(``)); err != nil {
+ t.Error(err)
+ }
+ }
+ }))
+ defer origin.Close()
+ cache := NewOGTagCache(origin.URL, config.OpenGraph{Enabled: true, TimeToLive: time.Minute}, memory.New(t.Context()), TargetOptions{SNI: sni})
+ for _, path := range []string{"/external", "/local"} {
+ u, _ := url.Parse(path)
+ tags, err := cache.GetOGTags(t.Context(), u, "example.com")
+ if path == "/external" {
+ if reached.Load() || tags["og:title"] == "secret" {
+ t.Fatal("cross-origin redirect fetched protected metadata")
+ }
+ } else if err != nil || tags["og:title"] != "safe" {
+ t.Fatalf("same-origin redirect: tags=%v err=%v", tags, err)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/ogtags/sni.go b/internal/ogtags/sni.go
index 46cfe03..73056e7 100644
--- a/internal/ogtags/sni.go
+++ b/internal/ogtags/sni.go
@@ -34,8 +34,16 @@ func (c *OGTagCache) clientForSNI(serverName string) *http.Client {
}
cli = &http.Client{
- Timeout: httpTimeout,
- Transport: tr,
+ Timeout: httpTimeout,
+ CheckRedirect: sameOriginRedirect,
+ Transport: tr,
+ }
+ if len(c.sniClients) >= 128 {
+ for name, old := range c.sniClients {
+ delete(c.sniClients, name)
+ old.CloseIdleConnections()
+ break
+ }
}
c.sniClients[serverName] = cli
return cli
diff --git a/internal/ogtags/sni_limit_test.go b/internal/ogtags/sni_limit_test.go
new file mode 100644
index 0000000..95cb3d1
--- /dev/null
+++ b/internal/ogtags/sni_limit_test.go
@@ -0,0 +1,23 @@
+package ogtags
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/TecharoHQ/anubis/lib/config"
+ "github.com/TecharoHQ/anubis/lib/store/memory"
+)
+
+func TestSNIClientCacheBounded(t *testing.T) {
+ cache := NewOGTagCache("https://example.com", config.OpenGraph{}, memory.New(t.Context()), TargetOptions{SNI: "auto"})
+ first := cache.clientForSNI("stable.example.com")
+ if cache.clientForSNI("stable.example.com") != first {
+ t.Fatal("client not reused")
+ }
+ for n := 0; n < 1000; n++ {
+ cache.clientForSNI(fmt.Sprintf("%d.example.com", n))
+ }
+ if len(cache.sniClients) > 128 {
+ t.Fatalf("retained %d clients", len(cache.sniClients))
+ }
+}
diff --git a/internal/servicesid/servicesid.go b/internal/servicesid/servicesid.go
new file mode 100644
index 0000000..b5293cd
--- /dev/null
+++ b/internal/servicesid/servicesid.go
@@ -0,0 +1,57 @@
+package servicesid
+
+import (
+ "crypto/sha1"
+ "encoding/binary"
+ "fmt"
+ "strings"
+ "unicode/utf16"
+)
+
+// serviceSIDPrefix is the identifier authority Windows files per-service SIDs
+// under. Everything below it is derived from the service name.
+const serviceSIDPrefix = "S-1-5-80"
+
+// anubisServiceName is the name the MSI registers the service under. It is the
+// input to the SID derivation below, so it has to match ServiceInstall/@Name in
+// run/windows/anubis.wxs exactly, case aside.
+const AnubisServiceName = "Anubis"
+
+// anubisServiceSID is the SID of the NT SERVICE\Anubis virtual account the
+// service runs as, spelled out rather than computed so that the value the
+// installer grants access to is visible in a diff and pinned by a test.
+const AnubisServiceSID = "S-1-5-80-765274699-3418405142-632509039-2036741013-1444054785"
+
+// Encode returns the SID of the NT SERVICE account belonging to a Windows
+// service, in the string form icacls and the rest of Windows accept.
+//
+// Windows derives these rather than allocating them: it uppercases the service
+// name, encodes it as UTF-16LE, takes the SHA-1 of that, and appends the digest
+// to S-1-5-80 as five little-endian uint32 subauthorities. The service does not
+// have to exist for the SID to be meaningful, which is what lets the installer
+// grant access to the config directory before the service is registered.
+//
+// The SHA-1 here is Windows' choice of construction, not a security decision of
+// ours. Any other hash would produce a SID that names nothing.
+//
+// This lives outside service_windows.go on purpose. Nothing in the build or in
+// CI runs Windows, so anything behind that build constraint is compiled and
+// never executed; keeping the arithmetic portable is what makes it testable.
+func Encode(name string) string {
+ encoded := utf16.Encode([]rune(strings.ToUpper(name)))
+
+ buf := make([]byte, 2*len(encoded))
+ for i, unit := range encoded {
+ binary.LittleEndian.PutUint16(buf[2*i:], unit)
+ }
+
+ sum := sha1.Sum(buf)
+
+ var sb strings.Builder
+ sb.WriteString(serviceSIDPrefix)
+ for i := 0; i < len(sum); i += 4 {
+ fmt.Fprintf(&sb, "-%d", binary.LittleEndian.Uint32(sum[i:]))
+ }
+
+ return sb.String()
+}
diff --git a/internal/servicesid/servicesid_test.go b/internal/servicesid/servicesid_test.go
new file mode 100644
index 0000000..c307c6f
--- /dev/null
+++ b/internal/servicesid/servicesid_test.go
@@ -0,0 +1,44 @@
+package servicesid
+
+import "testing"
+
+func TestServiceSID(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ service string
+ want string
+ }{
+ {
+ // TrustedInstaller ships with Windows and its SID is published in
+ // enough places to serve as a known-answer test for the whole
+ // derivation. If this case fails, the arithmetic is wrong.
+ name: "TrustedInstaller matches the published SID",
+ service: "TrustedInstaller",
+ want: "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464",
+ },
+ {
+ // Pins the hardcoded constant to the derivation. Renaming the
+ // service without recomputing the SID fails here rather than on a
+ // Windows box, where it would surface as the service being unable
+ // to read its own configuration.
+ name: "the pinned Anubis SID is the derived one",
+ service: AnubisServiceName,
+ want: AnubisServiceSID,
+ },
+ {
+ // The name is uppercased before hashing, so case in the service
+ // name must not reach the digest.
+ name: "case in the service name does not matter",
+ service: "aNuBiS",
+ want: AnubisServiceSID,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ if got := Encode(tt.service); got != tt.want {
+ t.Errorf("Encode(%q) = %q, want %q", tt.service, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/setuplistener.go b/internal/setuplistener.go
new file mode 100644
index 0000000..72a2f28
--- /dev/null
+++ b/internal/setuplistener.go
@@ -0,0 +1,92 @@
+package internal
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// parseBindNetFromAddr determine bind network and address based on the given network and address.
+func parseBindNetFromAddr(address string) (string, string, error) {
+ defaultScheme := "http://"
+ if !strings.Contains(address, "://") {
+ if strings.HasPrefix(address, ":") {
+ address = defaultScheme + "localhost" + address
+ } else {
+ address = defaultScheme + address
+ }
+ }
+
+ bindUri, err := url.Parse(address)
+ if err != nil {
+ return "", "", fmt.Errorf("failed to parse bind URL: %w", err)
+ }
+
+ switch bindUri.Scheme {
+ case "unix":
+ return "unix", bindUri.Path, nil
+ case "tcp", "http", "https":
+ return "tcp", bindUri.Host, nil
+ default:
+ return "", "", fmt.Errorf("unsupported network scheme %s in address %s", bindUri.Scheme, address)
+ }
+}
+
+// SetupListener sets up a network listener based on the input from configuration
+// envvars. It returns a network listener and the URL to that listener or an error.
+func SetupListener(network, address, socketMode string) (net.Listener, string, error) {
+ formattedAddress := ""
+ var err error
+
+ if network == "" {
+ // keep compatibility
+ network, address, err = parseBindNetFromAddr(address)
+ }
+
+ if err != nil {
+ return nil, "", fmt.Errorf("can't parse bind and network: %w", err)
+ }
+
+ switch network {
+ case "unix":
+ formattedAddress = "unix:" + address
+ case "tcp":
+ if strings.HasPrefix(address, ":") { // assume it's just a port e.g. :4259
+ formattedAddress = "http://localhost" + address
+ } else {
+ formattedAddress = "http://" + address
+ }
+ default:
+ formattedAddress = fmt.Sprintf(`(%s) %s`, network, address)
+ }
+
+ ln, err := net.Listen(network, address)
+ if err != nil {
+ return nil, "", fmt.Errorf("failed to bind to %s: %w", formattedAddress, err)
+ }
+
+ // additional permission handling for unix sockets
+ if network == "unix" {
+ mode, err := strconv.ParseUint(socketMode, 8, 0)
+ if err != nil {
+ _ = ln.Close()
+ return nil, "", fmt.Errorf("could not parse socket mode %s: %w", socketMode, err)
+ }
+
+ err = os.Chmod(address, os.FileMode(mode))
+ if err != nil {
+ err := fmt.Errorf("could not change socket mode: %w", err)
+ clErr := ln.Close()
+ if clErr != nil {
+ return nil, "", errors.Join(err, clErr)
+ }
+ return nil, "", err
+ }
+ }
+
+ return ln, formattedAddress, nil
+}
diff --git a/internal/setuplistener_test.go b/internal/setuplistener_test.go
new file mode 100644
index 0000000..2048873
--- /dev/null
+++ b/internal/setuplistener_test.go
@@ -0,0 +1,180 @@
+package internal
+
+import (
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestParseBindNetFromAddr(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ address string
+ wantErr bool
+ network string
+ bind string
+ }{
+ {
+ name: "simple tcp",
+ address: "localhost:9090",
+ wantErr: false,
+ network: "tcp",
+ bind: "localhost:9090",
+ },
+ {
+ name: "simple unix",
+ address: "unix:///tmp/foo.sock",
+ wantErr: false,
+ network: "unix",
+ bind: "/tmp/foo.sock",
+ },
+ {
+ name: "invalid network",
+ address: "foo:///tmp/bar.sock",
+ wantErr: true,
+ },
+ {
+ name: "tcp uri",
+ address: "tcp://[::]:9090",
+ wantErr: false,
+ network: "tcp",
+ bind: "[::]:9090",
+ },
+ {
+ name: "http uri",
+ address: "http://[::]:9090",
+ wantErr: false,
+ network: "tcp",
+ bind: "[::]:9090",
+ },
+ {
+ name: "https uri",
+ address: "https://[::]:9090",
+ wantErr: false,
+ network: "tcp",
+ bind: "[::]:9090",
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ network, bind, err := parseBindNetFromAddr(tt.address)
+
+ switch {
+ case tt.wantErr && err == nil:
+ t.Errorf("parseBindNetFromAddr(%q) should have errored but did not", tt.address)
+ case !tt.wantErr && err != nil:
+ t.Errorf("parseBindNetFromAddr(%q) threw an error: %v", tt.address, err)
+ }
+
+ if network != tt.network {
+ t.Errorf("parseBindNetFromAddr(%q) wanted network: %q, got: %q", tt.address, tt.network, network)
+ }
+
+ if bind != tt.bind {
+ t.Errorf("parseBindNetFromAddr(%q) wanted bind: %q, got: %q", tt.address, tt.bind, bind)
+ }
+ })
+ }
+}
+
+func TestSetupListener(t *testing.T) {
+ td := t.TempDir()
+
+ for _, tt := range []struct {
+ name string
+ network, address, socketMode string
+ wantErr bool
+ socketURLPrefix string
+ }{
+ {
+ name: "simple tcp",
+ network: "",
+ address: ":0",
+ wantErr: false,
+ socketURLPrefix: "http://localhost:",
+ },
+ {
+ name: "simple unix",
+ network: "",
+ address: "unix://" + filepath.Join(td, "a"),
+ socketMode: "0770",
+ wantErr: false,
+ socketURLPrefix: "unix:" + filepath.Join(td, "a"),
+ },
+ {
+ name: "tcp",
+ network: "tcp",
+ address: ":0",
+ wantErr: false,
+ socketURLPrefix: "http://localhost:",
+ },
+ {
+ name: "udp",
+ network: "udp",
+ address: ":0",
+ wantErr: true,
+ socketURLPrefix: "http://localhost:",
+ },
+ {
+ name: "unix socket",
+ network: "unix",
+ socketMode: "0770",
+ address: filepath.Join(td, "a"),
+ wantErr: false,
+ socketURLPrefix: "unix:" + filepath.Join(td, "a"),
+ },
+ {
+ name: "invalid socket mode",
+ network: "unix",
+ socketMode: "taco bell",
+ address: filepath.Join(td, "a"),
+ wantErr: true,
+ socketURLPrefix: "unix:" + filepath.Join(td, "a"),
+ },
+ {
+ name: "empty socket mode",
+ network: "unix",
+ socketMode: "",
+ address: filepath.Join(td, "a"),
+ wantErr: true,
+ socketURLPrefix: "unix:" + filepath.Join(td, "a"),
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ ln, socketURL, err := SetupListener(tt.network, tt.address, tt.socketMode)
+ switch {
+ case tt.wantErr && err == nil:
+ t.Errorf("SetupListener(%q, %q, %q) should have errored but did not", tt.network, tt.address, tt.socketMode)
+ case !tt.wantErr && err != nil:
+ t.Fatalf("SetupListener(%q, %q, %q) threw an error: %v", tt.network, tt.address, tt.socketMode, err)
+ }
+
+ if ln != nil {
+ defer ln.Close() //nolint:errcheck
+ }
+
+ if !tt.wantErr && !strings.HasPrefix(socketURL, tt.socketURLPrefix) {
+ t.Errorf("SetupListener(%q, %q, %q) should have returned a URL with prefix %q but got: %q", tt.network, tt.address, tt.socketMode, tt.socketURLPrefix, socketURL)
+ }
+
+ if tt.socketMode != "" {
+ mode, err := strconv.ParseUint(tt.socketMode, 8, 0)
+ if err != nil {
+ return
+ }
+
+ sockPath := strings.TrimPrefix(socketURL, "unix:")
+ st, err := os.Stat(sockPath)
+ if err != nil {
+ t.Fatalf("can't os.Stat(%q): %v", sockPath, err)
+ }
+
+ if st.Mode().Perm() != fs.FileMode(mode) {
+ t.Errorf("file mode of %q should be %s but is actually %s", sockPath, strconv.FormatUint(mode, 8), strconv.FormatUint(uint64(st.Mode()), 8))
+ }
+ }
+ })
+ }
+}
diff --git a/internal/test/csp_test.go b/internal/test/csp_test.go
new file mode 100644
index 0000000..efb6953
--- /dev/null
+++ b/internal/test/csp_test.go
@@ -0,0 +1,235 @@
+package test
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/TecharoHQ/anubis"
+ libanubis "github.com/TecharoHQ/anubis/lib"
+ "github.com/mxschmitt/playwright-go"
+)
+
+// blobBlockingCSP is the Content-Security-Policy (CSP) reported in
+// TecharoHQ/anubis#1864. This CSP doesn't set worker-src, so worker-src
+// falls back through script-src to `default-src 'self'`, which does not
+// cover blob: URIs.
+//
+// In order to reduce server request pressure, Anubis pre-fetches browser
+// worker JS from the server and packs it into a blob: URI. This policy
+// makes browsers reject that behaviour as an error event, leading the
+// workers to all die off and then users to be SOL.
+//
+// This policy also enforces Anubis to fall back to the old behaviour
+// where each worker fetches its own copy of the worker script in one
+// request per thread. This kinda sucks, but such is life in late-stage
+// capitalism.
+const blobBlockingCSP = "default-src 'self' 'unsafe-eval' 'unsafe-inline'; img-src * data:;"
+
+func TestPlaywrightBlobWorkerBlockedByCSP(t *testing.T) {
+ if os.Getenv("DONT_USE_NETWORK") != "" {
+ t.Skip("test requires network egress")
+ return
+ }
+
+ if os.Getenv("SKIP_INTEGRATION") != "" {
+ t.Skip("SKIP_INTEGRATION was set")
+ return
+ }
+
+ startPlaywright(t)
+
+ pw := setupPlaywright(t)
+
+ // Every JavaScript-driven challenge shares the same worker spawning logic,
+ // so every one of them has to survive a policy that forbids blob: workers.
+ // An empty policy file means the default policy, which issues "fast"
+ // challenges.
+ for _, cs := range []struct {
+ name string
+ policyFname string
+ }{
+ {name: "fast", policyFname: ""},
+ {name: "sha256", policyFname: "testdata/wasm-sha256.yaml"},
+ {name: "hashx", policyFname: "testdata/wasm-hashx.yaml"},
+ {name: "argon2id", policyFname: "testdata/wasm-argon2id.yaml"},
+ } {
+ t.Run(cs.name, func(t *testing.T) {
+ anubisURL := spawnAnubisWithPolicy(t, cs.policyFname, "", blobBlockingCSP)
+
+ for _, typ := range []playwright.BrowserType{pw.Chromium, pw.Firefox, pw.WebKit} {
+ t.Run(typ.Name(), func(t *testing.T) {
+ mustSolveChallenge(t, typ, anubisURL)
+ })
+ }
+ })
+ }
+}
+
+// TestPlaywrightWASMAlgorithms checks the WASM challenges on the happy path,
+// where the worker source is served out of a blob: URL and the compiled
+// WebAssembly.Module is handed to each worker over postMessage.
+//
+// TestPlaywrightBlobWorkerBlockedByCSP only ever exercises the fallback, so
+// without this the blob path for these algorithms is untested.
+func TestPlaywrightWASMAlgorithms(t *testing.T) {
+ if os.Getenv("DONT_USE_NETWORK") != "" {
+ t.Skip("test requires network egress")
+ return
+ }
+
+ if os.Getenv("SKIP_INTEGRATION") != "" {
+ t.Skip("SKIP_INTEGRATION was set")
+ return
+ }
+
+ startPlaywright(t)
+
+ pw := setupPlaywright(t)
+
+ for _, algorithm := range []string{"sha256", "hashx", "argon2id"} {
+ t.Run(algorithm, func(t *testing.T) {
+ anubisURL := spawnAnubisWithPolicy(t, "testdata/wasm-"+algorithm+".yaml", "", "")
+
+ for _, typ := range []playwright.BrowserType{pw.Chromium, pw.Firefox, pw.WebKit} {
+ t.Run(typ.Name(), func(t *testing.T) {
+ mustSolveChallenge(t, typ, anubisURL)
+ })
+ }
+ })
+ }
+}
+
+// mustSolveChallenge drives a browser through whatever challenge the server at
+// anubisURL issues and fails the test unless the browser lands on the target.
+func mustSolveChallenge(t *testing.T, typ playwright.BrowserType, anubisURL string) {
+ t.Helper()
+
+ browser, err := typ.Connect(buildBrowserConnect(typ.Name()))
+ if err != nil {
+ t.Fatalf("could not connect to remote browser: %v", err)
+ }
+ defer browser.Close()
+
+ ctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
+ AcceptDownloads: playwright.Bool(false),
+ ExtraHttpHeaders: map[string]string{
+ "X-Real-IP": placeholderIP,
+ },
+ UserAgent: playwright.String("Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"),
+ })
+ if err != nil {
+ t.Fatalf("could not create context: %v", err)
+ }
+ defer ctx.Close()
+
+ page, err := ctx.NewPage()
+ if err != nil {
+ t.Fatalf("could not create page: %v", err)
+ }
+ defer page.Close()
+
+ page.OnConsole(func(msg playwright.ConsoleMessage) {
+ t.Logf("console: %s", msg.Text())
+ })
+
+ if _, err := page.Goto(anubisURL, playwright.PageGotoOptions{
+ Timeout: playwright.Float(float64(playwrightMaxTime.Milliseconds())),
+ }); err != nil {
+ t.Fatalf("could not navigate to test server: %v", err)
+ }
+
+ if err := page.Locator("#anubis-test").WaitFor(playwright.LocatorWaitForOptions{
+ Timeout: playwright.Float(float64(challengeSolveTimeout.Milliseconds())),
+ }); err != nil {
+ t.Fatal(pwFail(t, page, "challenge did not complete: %v", err))
+ }
+}
+
+// challengeSolveTimeout is the maximum amount of time browsers get to solve
+// test challenges. By default this _should_ be good enough on the hardware
+// that CI runs on. If this ends up being a bad assumption, revise this
+// constant and document the tale of woe here.
+const challengeSolveTimeout = 30 * time.Second
+
+// spawnAnubisWithCSP starts Anubis with an additional inline middleware
+// that stamps every request with the given Content-Security-Policy, which
+// imitates the behaviour in TecharoHQ/anubis#1864 that caused workers to
+// be unable to spawn.
+//
+// If you set no csp value, no Content-Security-Policy is injected.
+func spawnAnubisWithCSP(t *testing.T, basePrefix, csp string) string {
+ t.Helper()
+
+ return spawnAnubisWithPolicy(t, "", basePrefix, csp)
+}
+
+// spawnAnubisWithPolicy is spawnAnubisWithCSP with control over which policy
+// file Anubis loads, so that tests can pin the challenge algorithm. An empty
+// policyFname loads the default policy, which issues "fast" challenges.
+func spawnAnubisWithPolicy(t *testing.T, policyFname, basePrefix, csp string) string {
+ t.Helper()
+
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Add("Content-Type", "text/html")
+ fmt.Fprintf(w, "%d", time.Now().Unix())
+ })
+
+ policy, err := libanubis.LoadPoliciesOrDefault(t.Context(), policyFname, anubis.DefaultDifficulty, "info", false)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Bind loopback explicitly: binding every interface makes ts.URL the
+ // unspecified address (http://[::]:port), which Firefox refuses to navigate
+ // to with NS_ERROR_CONNECTION_REFUSED.
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("can't listen on random port: %v", err)
+ }
+
+ // XXX(Xe): I'd love to use httptest.NewServer for this, but we need to know
+ // the address of the target ahead of time.
+ addr := listener.Addr().(*net.TCPAddr)
+ host := "localhost"
+ port := strconv.Itoa(addr.Port)
+
+ s, err := libanubis.New(libanubis.Options{
+ Next: h,
+ Policy: policy,
+ ServeRobotsTXT: true,
+ Target: "http://" + host + ":" + port,
+ BasePrefix: basePrefix,
+ CookieExpiration: anubis.CookieDefaultExpirationTime,
+ })
+ if err != nil {
+ t.Fatalf("can't construct libanubis.Server: %v", err)
+ }
+
+ var handler http.Handler = s
+ if csp != "" {
+ inner := handler
+ handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Security-Policy", csp)
+ inner.ServeHTTP(w, r)
+ })
+ }
+
+ ts := &httptest.Server{
+ Listener: listener,
+ Config: &http.Server{Handler: handler},
+ }
+ ts.Start()
+ t.Log(ts.URL)
+
+ t.Cleanup(func() {
+ ts.Close()
+ })
+
+ return ts.URL
+}
diff --git a/internal/test/playwright_test.go b/internal/test/playwright_test.go
index b1cab34..10886b3 100644
--- a/internal/test/playwright_test.go
+++ b/internal/test/playwright_test.go
@@ -7,7 +7,7 @@
// Anubis must be configured to redirect to the server started by the test suite.
// The bind address and the Anubis server can be specified using the flags `-bind` and `-anubis` respectively.
//
-// Playwright must be started in server mode using `npx playwright@1.50.1 run-server --port 3000`.
+// Playwright must be started in server mode using `npx playwright@1.61.1 run-server --port 9001`.
// The version must match the minor used by the playwright-go package.
//
// On unsupported systems you may be able to use a container instead: https://playwright.dev/docs/docker#remote-connection
@@ -18,19 +18,17 @@ package test
import (
"flag"
"fmt"
- "net"
"net/http"
- "net/http/httptest"
"net/url"
"os"
"os/exec"
- "strconv"
+ "strings"
+ "syscall"
"testing"
"time"
"github.com/TecharoHQ/anubis"
- libanubis "github.com/TecharoHQ/anubis/lib"
- "github.com/playwright-community/playwright-go"
+ "github.com/mxschmitt/playwright-go"
)
var (
@@ -99,7 +97,7 @@ const (
actionChallenge action = "CHALLENGE"
placeholderIP = "fd11:5ee:bad:c0de::"
- playwrightVersion = "1.52.0"
+ playwrightVersion = "1.62.1"
)
type action string
@@ -158,20 +156,27 @@ func daemonize(t *testing.T, command string) {
cmd.Stdin = nil
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
+ // Run in its own process group so cleanup can reap the whole tree. Killing
+ // only sh leaves the server holding the test binary's stdout, which makes go
+ // test report "Test I/O incomplete" and fail even when every test passed.
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
t.Fatalf("can't daemonize command: %v", err)
}
t.Cleanup(func() {
- cmd.Process.Kill()
+ if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil {
+ t.Logf("can't kill process group of %d: %v", cmd.Process.Pid, err)
+ }
})
}
func startPlaywright(t *testing.T) {
t.Helper()
- if *playwrightRunner == "npx" {
+ switch *playwrightRunner {
+ case "npx":
doesCommandExist(t, "npx")
if os.Getenv("CI") == "true" {
@@ -181,7 +186,7 @@ func startPlaywright(t *testing.T) {
}
daemonize(t, fmt.Sprintf("npx --yes playwright@%s run-server --port %d", playwrightVersion, *playwrightPort))
- } else if *playwrightRunner == "docker" || *playwrightRunner == "podman" {
+ case "docker", "podman":
doesCommandExist(t, *playwrightRunner)
// docs: https://playwright.dev/docs/docker
@@ -190,9 +195,9 @@ func startPlaywright(t *testing.T) {
t.Cleanup(func() {
run(t, fmt.Sprintf("%s rm --force %s", *playwrightRunner, container))
})
- } else if *playwrightRunner == "none" {
+ case "none":
t.Log("not starting Playwright, assuming it is already running")
- } else {
+ default:
t.Skipf("unknown runner: %s, skipping", *playwrightRunner)
}
@@ -228,9 +233,7 @@ func TestPlaywrightBrowser(t *testing.T) {
for _, typ := range browsers {
t.Run(typ.Name()+"/warmup", func(t *testing.T) {
- browser, err := typ.Connect(buildBrowserConnect(typ.Name()), playwright.BrowserTypeConnectOptions{
- ExposeNetwork: playwright.String(""),
- })
+ browser, err := typ.Connect(buildBrowserConnect(typ.Name()))
if err != nil {
t.Fatalf("could not connect to remote browser: %v", err)
}
@@ -239,7 +242,7 @@ func TestPlaywrightBrowser(t *testing.T) {
ctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
AcceptDownloads: playwright.Bool(false),
ExtraHttpHeaders: map[string]string{
- "X-Real-Ip": "127.0.0.1",
+ "X-Real-IP": "127.0.0.1",
},
UserAgent: playwright.String("Sephiroth"),
})
@@ -270,7 +273,7 @@ func TestPlaywrightBrowser(t *testing.T) {
var performedAction action
var err error
- for i := 0; i < 5; i++ {
+ for i := range 5 {
performedAction, err = executeTestCase(t, tc, typ, anubisURL)
if performedAction == tc.action {
break
@@ -316,9 +319,7 @@ func TestPlaywrightWithBasePrefix(t *testing.T) {
for _, typ := range browsers {
t.Run(typ.Name()+"/basePrefix", func(t *testing.T) {
- browser, err := typ.Connect(buildBrowserConnect(typ.Name()), playwright.BrowserTypeConnectOptions{
- ExposeNetwork: playwright.String(""),
- })
+ browser, err := typ.Connect(buildBrowserConnect(typ.Name()))
if err != nil {
t.Fatalf("could not connect to remote browser: %v", err)
}
@@ -327,7 +328,7 @@ func TestPlaywrightWithBasePrefix(t *testing.T) {
ctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
AcceptDownloads: playwright.Bool(false),
ExtraHttpHeaders: map[string]string{
- "X-Real-Ip": "127.0.0.1",
+ "X-Real-IP": "127.0.0.1",
},
UserAgent: playwright.String("Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"),
})
@@ -400,9 +401,11 @@ func TestPlaywrightWithBasePrefix(t *testing.T) {
pwFail(t, page, "could not get cookies: %v", err)
}
+ // The cookie name has a suffix that is derived from the cookie
+ // settings, so match on the prefix only.
var found bool
for _, cookie := range cookies {
- if cookie.Name == anubis.CookieName {
+ if strings.HasPrefix(cookie.Name, anubis.CookieName+"-") {
found = true
if cookie.Path != basePrefix+"/" {
t.Errorf("cookie path is wrong, wanted %s, got: %s", basePrefix+"/", cookie.Path)
@@ -418,6 +421,12 @@ func TestPlaywrightWithBasePrefix(t *testing.T) {
}
}
+// buildBrowserConnect returns the URL to connect to for the named browser.
+//
+// Callers pass no BrowserTypeConnectOptions: playwright-go does not implement
+// the SocksSupport channel that exposeNetwork relies on, so requesting it makes
+// the server close the connection. The browser therefore has to share the
+// host's loopback, which both supported runners do.
func buildBrowserConnect(name string) string {
u, _ := url.Parse(*playwrightServer)
@@ -431,9 +440,7 @@ func buildBrowserConnect(name string) string {
func executeTestCase(t *testing.T, tc testCase, typ playwright.BrowserType, anubisURL string) (action, error) {
deadline, _ := t.Deadline()
- browser, err := typ.Connect(buildBrowserConnect(typ.Name()), playwright.BrowserTypeConnectOptions{
- ExposeNetwork: playwright.String(""),
- })
+ browser, err := typ.Connect(buildBrowserConnect(typ.Name()))
if err != nil {
return "", fmt.Errorf("could not connect to remote browser: %w", err)
}
@@ -442,7 +449,7 @@ func executeTestCase(t *testing.T, tc testCase, typ playwright.BrowserType, anub
ctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
AcceptDownloads: playwright.Bool(false),
ExtraHttpHeaders: map[string]string{
- "X-Real-Ip": tc.realIP,
+ "X-Real-IP": tc.realIP,
},
UserAgent: playwright.String(tc.userAgent),
})
@@ -588,48 +595,5 @@ func spawnAnubis(t *testing.T) string {
}
func spawnAnubisWithOptions(t *testing.T, basePrefix string) string {
- t.Helper()
-
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Add("Content-Type", "text/html")
- fmt.Fprintf(w, "%d", time.Now().Unix())
- })
-
- policy, err := libanubis.LoadPoliciesOrDefault(t.Context(), "", anubis.DefaultDifficulty, "info")
- if err != nil {
- t.Fatal(err)
- }
-
- listener, err := net.Listen("tcp", ":0")
- if err != nil {
- t.Fatalf("can't listen on random port: %v", err)
- }
-
- addr := listener.Addr().(*net.TCPAddr)
- host := "localhost"
- port := strconv.Itoa(addr.Port)
-
- s, err := libanubis.New(libanubis.Options{
- Next: h,
- Policy: policy,
- ServeRobotsTXT: true,
- Target: "http://" + host + ":" + port,
- BasePrefix: basePrefix,
- })
- if err != nil {
- t.Fatalf("can't construct libanubis.Server: %v", err)
- }
-
- ts := &httptest.Server{
- Listener: listener,
- Config: &http.Server{Handler: s},
- }
- ts.Start()
- t.Log(ts.URL)
-
- t.Cleanup(func() {
- ts.Close()
- })
-
- return ts.URL
+ return spawnAnubisWithCSP(t, basePrefix, "")
}
diff --git a/internal/test/server_setup_test.go b/internal/test/server_setup_test.go
new file mode 100644
index 0000000..ca40ce7
--- /dev/null
+++ b/internal/test/server_setup_test.go
@@ -0,0 +1,24 @@
+package test
+
+import (
+ "net/http"
+ "testing"
+)
+
+func TestIntegrationServerLoadsDefaultPolicy(t *testing.T) {
+ server := spawnAnubisWithPolicy(t, "", "", "")
+ request, err := http.NewRequest(http.MethodGet, server+"/", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("X-Real-IP", "127.0.0.1")
+ request.Header.Set("User-Agent", "Sephiroth")
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { response.Body.Close() })
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d", response.StatusCode)
+ }
+}
diff --git a/internal/test/testdata/wasm-argon2id.yaml b/internal/test/testdata/wasm-argon2id.yaml
new file mode 100644
index 0000000..c7df68c
--- /dev/null
+++ b/internal/test/testdata/wasm-argon2id.yaml
@@ -0,0 +1,9 @@
+# Forces every client through the argon2id WASM challenge so that the browser
+# tests exercise the WASM path rather than the default "fast" challenge.
+bots:
+ - name: everyone
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ algorithm: argon2id
+ difficulty: 2
diff --git a/internal/test/testdata/wasm-hashx.yaml b/internal/test/testdata/wasm-hashx.yaml
new file mode 100644
index 0000000..9a7564c
--- /dev/null
+++ b/internal/test/testdata/wasm-hashx.yaml
@@ -0,0 +1,9 @@
+# Forces every client through the hashx WASM challenge so that the browser
+# tests exercise the WASM path rather than the default "fast" challenge.
+bots:
+ - name: everyone
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ algorithm: hashx
+ difficulty: 2
diff --git a/internal/test/testdata/wasm-sha256.yaml b/internal/test/testdata/wasm-sha256.yaml
new file mode 100644
index 0000000..4184ba4
--- /dev/null
+++ b/internal/test/testdata/wasm-sha256.yaml
@@ -0,0 +1,9 @@
+# Forces every client through the sha256 WASM challenge so that the browser
+# tests exercise the WASM path rather than the default "fast" challenge.
+bots:
+ - name: everyone
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ algorithm: sha256
+ difficulty: 2
diff --git a/internal/unbreakdocker.go b/internal/unbreakdocker.go
index 8bf29fd..2547c7c 100644
--- a/internal/unbreakdocker.go
+++ b/internal/unbreakdocker.go
@@ -17,6 +17,6 @@ func UnbreakDocker() {
// This is a horrifying monstrosity, but the part that scares me the most
// is the fact that it works.
if hostname, err := os.Hostname(); err == nil {
- exec.Command("docker", "network", "connect", "bridge", hostname).Run()
+ _ = exec.Command("docker", "network", "connect", "bridge", hostname).Run()
}
}
diff --git a/lib/anubis.go b/lib/anubis.go
index feff53a..c182d45 100644
--- a/lib/anubis.go
+++ b/lib/anubis.go
@@ -4,18 +4,24 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
+ "net/netip"
"net/url"
+ "slices"
+ "strconv"
"strings"
+ "sync"
"time"
+ "cel.dev/cel-go/common/types"
"github.com/golang-jwt/jwt/v5"
- "github.com/google/cel-go/common/types"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
@@ -27,6 +33,7 @@ import (
"github.com/TecharoHQ/anubis/internal/dnsbl"
"github.com/TecharoHQ/anubis/internal/ogtags"
"github.com/TecharoHQ/anubis/lib/challenge"
+ "github.com/TecharoHQ/anubis/lib/challenge/extension"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/localization"
"github.com/TecharoHQ/anubis/lib/policy"
@@ -37,55 +44,101 @@ import (
_ "github.com/TecharoHQ/anubis/lib/challenge/metarefresh"
_ "github.com/TecharoHQ/anubis/lib/challenge/preact"
_ "github.com/TecharoHQ/anubis/lib/challenge/proofofwork"
+ _ "github.com/TecharoHQ/anubis/lib/challenge/wasm"
+
+ // extension implementations
+ _ "github.com/TecharoHQ/anubis/lib/challenge/extension/css-load"
)
+type contextKey int
+
+const asnContextKey contextKey = iota
+
+type asnInfo struct {
+ ASN string
+ Description string
+}
+
+func asnFromContext(ctx context.Context) (string, string) {
+ if v, ok := ctx.Value(asnContextKey).(asnInfo); ok {
+ return v.ASN, v.Description
+ }
+ return "", ""
+}
+
var (
challengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_challenges_issued",
Help: "The total number of challenges issued",
- }, []string{"method"})
+ }, []string{"method", "asn", "asn_description"})
challengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_challenges_validated",
Help: "The total number of challenges validated",
- }, []string{"method"})
+ }, []string{"method", "asn", "asn_description"})
droneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_dronebl_hits",
Help: "The total number of hits from DroneBL",
- }, []string{"status"})
+ }, []string{"status", "asn", "asn_description"})
failedValidations = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_failed_validations",
Help: "The total number of failed validations",
- }, []string{"method"})
+ }, []string{"method", "asn", "asn_description"})
requestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_proxied_requests_total",
Help: "Number of requests proxied through Anubis to upstream targets",
- }, []string{"host"})
+ }, []string{"host", "asn", "asn_description"})
+
+ requestsByASN = promauto.NewCounterVec(prometheus.CounterOpts{
+ Name: "anubis_requests_by_asn_total",
+ Help: "Number of requests by ASN",
+ }, []string{"asn", "asn_description"})
)
type Server struct {
- next http.Handler
- store store.Interface
- mux *http.ServeMux
- policy *policy.ParsedConfig
- OGTags *ogtags.OGTagCache
- logger *slog.Logger
- opts Options
- ed25519Priv ed25519.PrivateKey
- hs512Secret []byte
+ challengeLocks [256]sync.Mutex
+ next http.Handler
+ store store.Interface
+ mux *http.ServeMux
+ policy *policy.ParsedConfig
+ OGTags *ogtags.OGTagCache
+ logger *slog.Logger
+ opts Options
+ ed25519Priv ed25519.PrivateKey
+ hs512Secret []byte
+}
+
+func (s *Server) getRequestLogger(r *http.Request) (*slog.Logger, *http.Request) {
+ lg := internal.GetRequestLogger(s.logger, r)
+
+ if s.policy.LogASN && s.policy.GeoIP.HasASN() {
+ if addr, err := netip.ParseAddr(r.Header.Get("X-Real-IP")); err == nil {
+ if asNumber, description, ok := s.policy.GeoIP.LookupASN(addr); ok {
+ asn := strconv.FormatUint(uint64(asNumber), 10)
+ lg = lg.With("asn", asNumber, "asn_description", description)
+ requestsByASN.WithLabelValues(asn, description).Inc()
+ r = r.WithContext(context.WithValue(r.Context(), asnContextKey, asnInfo{
+ ASN: asn,
+ Description: description,
+ }))
+ }
+ }
+ }
+
+ return lg, r
}
func (s *Server) getTokenKeyfunc() jwt.Keyfunc {
// return ED25519 key if HS512 is not set
if len(s.hs512Secret) == 0 {
- return func(token *jwt.Token) (interface{}, error) {
+ return func(token *jwt.Token) (any, error) {
return s.ed25519Priv.Public().(ed25519.PublicKey), nil
}
} else {
- return func(token *jwt.Token) (interface{}, error) {
+ return func(token *jwt.Token) (any, error) {
return s.hs512Secret, nil
}
}
@@ -100,16 +153,50 @@ func (s *Server) getChallenge(r *http.Request) (*challenge.Challenge, error) {
return &chall, err
}
+// shouldRetryMissingTestCookie reports whether a client that reached
+// PassChallenge without the verification cookie should be sent through a fresh
+// challenge instead of being shown the cookies disabled error. Some browsers
+// drop the verification cookie in edge cases such as an HTTP to HTTPS upgrade
+// on the first navigation, and a fresh challenge then succeeds. See
+// https://github.com/TecharoHQ/anubis/issues/1916
+//
+// A retry is only granted for a live, unspent challenge and at most once per
+// client (IP address and User-Agent) per challenge lifetime, so clients that
+// never send cookies get the error after one extra challenge instead of
+// looping.
+func (s *Server) shouldRetryMissingTestCookie(r *http.Request) bool {
+ chall, err := s.getChallenge(r)
+ if err != nil || chall.Spent {
+ return false
+ }
+
+ key := "cookie-retry:" + internal.SHA256sum(r.Header.Get("X-Real-IP")+":"+r.Header.Get("User-Agent"))
+ if _, err := s.store.Get(r.Context(), key); err == nil {
+ return false
+ }
+
+ // Same lifetime as an issued challenge.
+ return s.store.Set(r.Context(), key, []byte("1"), 30*time.Minute) == nil
+}
+
func (s *Server) issueChallenge(ctx context.Context, r *http.Request, lg *slog.Logger, cr policy.CheckResult, rule *policy.Bot) (*challenge.Challenge, error) {
if cr.Rule != config.RuleChallenge {
- slog.Error("this should be impossible, asked to issue a challenge but the rule is not a challenge rule", "cr", cr, "rule", rule)
+ slog.ErrorContext(ctx, "this should be impossible, asked to issue a challenge but the rule is not a challenge rule", "cr", cr, "rule", rule)
//return nil, errors.New("[unexpected] this codepath should be impossible, asked to issue a challenge for a non-challenge rule")
}
+ if rule.Challenge == nil {
+ rule.Challenge = &config.ChallengeRules{
+ Difficulty: s.policy.DefaultDifficulty,
+ Algorithm: config.DefaultAlgorithm,
+ }
+ }
+
id, err := uuid.NewV7()
if err != nil {
return nil, err
}
+ idStr := id.String()
var randomData = make([]byte, 64)
if _, err := rand.Read(randomData); err != nil {
@@ -117,24 +204,26 @@ func (s *Server) issueChallenge(ctx context.Context, r *http.Request, lg *slog.L
}
chall := challenge.Challenge{
- ID: id.String(),
+ ID: idStr,
Method: rule.Challenge.Algorithm,
- RandomData: fmt.Sprintf("%x", randomData),
+ RandomData: hex.EncodeToString(randomData),
IssuedAt: time.Now(),
Difficulty: rule.Challenge.Difficulty,
PolicyRuleHash: rule.Hash(),
+ Extensions: slices.Clone(rule.Challenge.Extensions),
Metadata: map[string]string{
"User-Agent": r.Header.Get("User-Agent"),
- "X-Real-Ip": r.Header.Get("X-Real-Ip"),
+ "X-Real-IP": r.Header.Get("X-Real-IP"),
+ "Referer": r.Header.Get("Referer"),
},
}
j := store.JSON[challenge.Challenge]{Underlying: s.store}
- if err := j.Set(ctx, "challenge:"+id.String(), chall, 30*time.Minute); err != nil {
+ if err := j.Set(ctx, "challenge:"+idStr, chall, 30*time.Minute); err != nil {
return nil, err
}
- lg.Info("new challenge issued", "challenge", id.String())
+ lg.InfoContext(ctx, "new challenge issued", "challenge", idStr, "weight", cr.Weight)
return &chall, err
}
@@ -148,6 +237,14 @@ func (s *Server) hydrateChallengeRule(rule *policy.Bot, chall *challenge.Challen
rule = &policy.Bot{
Rules: &checker.List{},
}
+ } else {
+ copiedRule := *rule
+ if rule.Challenge != nil {
+ copiedChallenge := *rule.Challenge
+ copiedChallenge.Extensions = slices.Clone(rule.Challenge.Extensions)
+ copiedRule.Challenge = &copiedChallenge
+ }
+ rule = &copiedRule
}
if chall.Difficulty == 0 {
@@ -185,14 +282,51 @@ func (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request)
s.maybeReverseProxy(w, r, false)
}
-func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {
- lg := internal.GetRequestLogger(s.logger, r)
+const (
+ downstreamRiskRuleHeader = "X-Anubis-Rule"
+ downstreamRiskActionHeader = "X-Anubis-Action"
+ downstreamRiskStatusHeader = "X-Anubis-Status"
+)
- if val, _ := s.store.Get(r.Context(), fmt.Sprintf("ogtags:allow:%s%s", r.Host, r.URL.String())); val != nil {
- lg.Debug("serving opengraph tag asset")
- s.ServeHTTPNext(w, r)
+func isDownstreamRiskHeader(name string) bool {
+ switch http.CanonicalHeaderKey(name) {
+ case downstreamRiskRuleHeader, downstreamRiskActionHeader, downstreamRiskStatusHeader:
+ return true
+ }
+ return false
+}
+
+func removeDownstreamRiskConnectionTokens(header http.Header) {
+ connectionValues := header.Values("Connection")
+ header.Del("Connection")
+ for _, value := range connectionValues {
+ var remaining []string
+ for token := range strings.SplitSeq(value, ",") {
+ token = strings.TrimSpace(token)
+ if token == "" || isDownstreamRiskHeader(token) {
+ continue
+ }
+ remaining = append(remaining, token)
+ }
+ if len(remaining) != 0 {
+ header.Add("Connection", strings.Join(remaining, ", "))
+ }
+ }
+}
+
+func setDownstreamRiskHeaders(header http.Header, cr policy.CheckResult, status string) {
+ removeDownstreamRiskConnectionTokens(header)
+ header.Set(downstreamRiskRuleHeader, cr.Name)
+ header.Set(downstreamRiskActionHeader, string(cr.Rule))
+ if status == "" {
+ header.Del(downstreamRiskStatusHeader)
return
}
+ header.Set(downstreamRiskStatusHeader, status)
+}
+
+func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {
+ lg, r := s.getRequestLogger(r)
// Adjust cookie path if base prefix is not empty
cookiePath := "/"
@@ -202,18 +336,19 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
cr, rule, err := s.check(r, lg)
if err != nil {
- lg.Error("check failed", "err", err)
+ lg.ErrorContext(r.Context(), "check failed", "err", err)
localizer := localization.GetLocalizer(r)
s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy\"", localizer.T("internal_server_error")), makeCode(err))
return
}
- r.Header.Add("X-Anubis-Rule", cr.Name)
- r.Header.Add("X-Anubis-Action", string(cr.Rule))
lg = lg.With("check_result", cr)
- policy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)
+ {
+ asn, asnDesc := asnFromContext(r.Context())
+ policy.Applications.WithLabelValues(cr.Name, string(cr.Rule), asn, asnDesc).Add(1)
+ }
- ip := r.Header.Get("X-Real-Ip")
+ ip := r.Header.Get("X-Real-IP")
if s.handleDNSBL(w, r, ip, lg) {
return
@@ -223,23 +358,25 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
return
}
- ckie, err := r.Cookie(anubis.CookieName)
+ ckie, err := s.getCookie(r, anubis.CookieName)
if err != nil {
- lg.Debug("cookie not found", "path", r.URL.Path)
- s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
+ // Don't clear the cookie, there is none to clear. This response can land
+ // after a concurrent pass-challenge issued a valid one and would delete
+ // it. See https://github.com/TecharoHQ/anubis/issues/1314
+ lg.DebugContext(r.Context(), "cookie not found", "path", r.URL.Path)
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if err := ckie.Valid(); err != nil {
- lg.Debug("cookie is invalid", "err", err)
+ lg.DebugContext(r.Context(), "cookie is invalid", "err", err)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {
- lg.Debug("cookie expired", "path", r.URL.Path)
+ lg.DebugContext(r.Context(), "cookie expired", "path", r.URL.Path)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
@@ -248,7 +385,7 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
token, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())
if err != nil || !token.Valid {
- lg.Debug("invalid token", "path", r.URL.Path, "err", err)
+ lg.DebugContext(r.Context(), "invalid token", "path", r.URL.Path, "err", err)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
@@ -256,7 +393,7 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
- lg.Debug("invalid token claims type", "path", r.URL.Path)
+ lg.DebugContext(r.Context(), "invalid token claims type", "path", r.URL.Path)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
@@ -264,30 +401,49 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
policyRule, ok := claims["policyRule"].(string)
if !ok {
- lg.Debug("policyRule claim is not a string")
+ lg.DebugContext(r.Context(), "policyRule claim is not a string")
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if policyRule != rule.Hash() {
- lg.Debug("user originally passed with a different rule, issuing new challenge", "old", policyRule, "new", rule.Name)
+ lg.DebugContext(r.Context(), "user originally passed with a different rule, issuing new challenge", "old", policyRule, "new", rule.Name)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
if s.opts.JWTRestrictionHeader != "" && claims["restriction"] != internal.SHA256sum(r.Header.Get(s.opts.JWTRestrictionHeader)) {
- lg.Debug("JWT restriction header is invalid")
+ lg.DebugContext(r.Context(), "JWT restriction header is invalid")
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.RenderIndex(w, r, cr, rule, httpStatusOnly)
return
}
- r.Header.Add("X-Anubis-Status", "PASS")
+ s.restoreOriginalReferer(w, r, cookiePath)
+
+ setDownstreamRiskHeaders(r.Header, cr, "PASS")
s.ServeHTTPNext(w, r)
}
+// restoreOriginalReferer looks for the one-shot cookie set by PassChallenge and, if
+// present, overwrites the request's Referer header with the value it carries before
+// the request is proxied upstream. The cookie only survives the single redirect from
+// PassChallenge back to the original URL, so this only ever fires for that one request.
+func (s *Server) restoreOriginalReferer(w http.ResponseWriter, r *http.Request, cookiePath string) {
+ ckie, err := s.getCookie(r, anubis.OriginalRefererCookieName)
+ if err != nil || ckie.Value == "" {
+ return
+ }
+
+ s.ClearCookie(w, CookieOpts{Name: anubis.OriginalRefererCookieName, Path: cookiePath, Host: r.Host})
+
+ if referer, err := url.QueryUnescape(ckie.Value); err == nil {
+ r.Header.Set("Referer", referer)
+ }
+}
+
func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {
// Adjust cookie path if base prefix is not empty
cookiePath := "/"
@@ -299,31 +455,32 @@ func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.Ch
switch cr.Rule {
case config.RuleAllow:
- lg.Debug("allowing traffic to origin (explicit)")
+ lg.DebugContext(r.Context(), "allowing traffic to origin (explicit)")
+ setDownstreamRiskHeaders(r.Header, cr, "")
s.ServeHTTPNext(w, r)
return true
case config.RuleDeny:
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
- lg.Info("explicit deny")
+ lg.InfoContext(r.Context(), "explicit deny")
if rule == nil {
- lg.Error("rule is nil, cannot calculate checksum")
+ lg.ErrorContext(r.Context(), "rule is nil, cannot calculate checksum")
s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy.RuleDeny\"", localizer.T("internal_server_error")), makeCode(ErrActualAnubisBug))
return true
}
hash := rule.Hash()
- lg.Debug("rule hash", "hash", hash)
+ lg.DebugContext(r.Context(), "rule hash", "hash", hash)
s.respondWithStatus(w, r, fmt.Sprintf("%s %s", localizer.T("access_denied"), hash), "", s.policy.StatusCodes.Deny)
return true
case config.RuleChallenge:
- lg.Debug("challenge requested")
+ lg.DebugContext(r.Context(), "challenge requested")
case config.RuleBenchmark:
- lg.Debug("serving benchmark page")
+ lg.DebugContext(r.Context(), "serving benchmark page")
s.RenderBench(w, r)
return true
default:
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
- lg.Error("CONFIG ERROR: unknown rule", "rule", cr.Rule)
+ lg.ErrorContext(r.Context(), "CONFIG ERROR: unknown rule", "rule", cr.Rule)
s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy.Rules\"", localizer.T("internal_server_error")), makeCode(ErrActualAnubisBug))
return true
}
@@ -331,21 +488,28 @@ func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.Ch
}
func (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {
+ return s.handleDNSBLWithLookup(w, r, ip, lg, dnsbl.Lookup)
+}
+
+func (s *Server) handleDNSBLWithLookup(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger, lookup func(string) (dnsbl.DroneBLResponse, error)) bool {
db := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: "dronebl:"}
if s.policy.DNSBL && ip != "" {
resp, err := db.Get(r.Context(), ip)
if err != nil {
- lg.Debug("looking up ip in dnsbl")
- resp, err := dnsbl.Lookup(ip)
+ lg.DebugContext(r.Context(), "looking up ip in dnsbl")
+ resp, err = lookup(ip)
if err != nil {
- lg.Error("can't look up ip in dnsbl", "err", err)
+ lg.ErrorContext(r.Context(), "can't look up ip in dnsbl", "err", err)
+ s.respondWithStatus(w, r, localization.GetLocalizer(r).T("internal_server_error"), "", http.StatusServiceUnavailable)
+ return true
}
- db.Set(r.Context(), ip, resp, 24*time.Hour)
- droneBLHits.WithLabelValues(resp.String()).Inc()
+ _ = db.Set(r.Context(), ip, resp, 24*time.Hour) // worst case we do the dns lookup again
+ asn, asnDesc := asnFromContext(r.Context())
+ droneBLHits.WithLabelValues(resp.String(), asn, asnDesc).Inc()
}
if resp != dnsbl.AllGood {
- lg.Info("DNSBL hit", "status", resp.String())
+ lg.InfoContext(r.Context(), "DNSBL hit", "status", resp.String())
localizer := localization.GetLocalizer(r)
s.respondWithStatus(w, r, fmt.Sprintf("%s: %s, %s https://dronebl.org/lookup?ip=%s",
localizer.T("dronebl_entry"),
@@ -359,19 +523,25 @@ func (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string,
}
func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
- lg := internal.GetRequestLogger(s.logger, r)
+ if !prepareChallengeForm(w, r) {
+ return
+ }
+ defer cleanupChallengeForm(r)
+ lg, r := s.getRequestLogger(r)
localizer := localization.GetLocalizer(r)
redir := r.FormValue("redir")
if redir == "" {
w.WriteHeader(http.StatusBadRequest)
encoder := json.NewEncoder(w)
- lg.Error("invalid invocation of MakeChallenge", "redir", redir)
- encoder.Encode(struct {
+ lg.ErrorContext(r.Context(), "invalid invocation of MakeChallenge", "redir", redir)
+ if err := encoder.Encode(struct {
Error string `json:"error"`
}{
Error: localizer.T("invalid_invocation"),
- })
+ }); err != nil {
+ s.logger.DebugContext(r.Context(), "can't write invalid invocation error to client, did they disconnect?", "err", err)
+ }
return
}
@@ -380,7 +550,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(w)
cr, rule, err := s.check(r, lg)
if err != nil {
- lg.Error("check failed", "err", err)
+ lg.ErrorContext(r.Context(), "check failed", "err", err)
w.WriteHeader(http.StatusInternalServerError)
err := encoder.Encode(struct {
Error string `json:"error"`
@@ -388,7 +558,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
Error: fmt.Sprintf("%s \"makeChallenge\"", localizer.T("internal_server_error")),
})
if err != nil {
- lg.Error("failed to encode error response", "err", err)
+ lg.ErrorContext(r.Context(), "failed to encode error response", "err", err)
w.WriteHeader(http.StatusInternalServerError)
}
return
@@ -397,7 +567,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
chall, err := s.issueChallenge(r.Context(), r, lg, cr, rule)
if err != nil {
- lg.Error("failed to fetch or issue challenge", "err", err)
+ lg.ErrorContext(r.Context(), "failed to fetch or issue challenge", "err", err)
w.WriteHeader(http.StatusInternalServerError)
err := encoder.Encode(struct {
Error string `json:"error"`
@@ -405,7 +575,7 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
Error: fmt.Sprintf("%s \"makeChallenge\"", localizer.T("internal_server_error")),
})
if err != nil {
- lg.Error("failed to encode error response", "err", err)
+ lg.ErrorContext(r.Context(), "failed to encode error response", "err", err)
w.WriteHeader(http.StatusInternalServerError)
}
return
@@ -423,32 +593,40 @@ func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
ID: chall.ID,
})
if err != nil {
- lg.Error("failed to encode challenge", "err", err)
+ lg.ErrorContext(r.Context(), "failed to encode challenge", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
- lg.Debug("made challenge", "challenge", chall, "rules", rule.Challenge, "cr", cr)
- challengesIssued.WithLabelValues("api").Inc()
+ lg.DebugContext(r.Context(), "made challenge", "challenge", chall, "rules", rule.Challenge, "cr", cr)
+ {
+ asn, asnDesc := asnFromContext(r.Context())
+ challengesIssued.WithLabelValues("api", asn, asnDesc).Inc()
+ }
+}
+
+func (s *Server) validateExtension(name string, r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {
+ ext, ok := extension.Get(name)
+ if !ok {
+ return fmt.Errorf("%w: %q", ErrUnknownChallengeExtension, name)
+ }
+ return ext.Validate(r, lg, in)
}
func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
- lg := internal.GetRequestLogger(s.logger, r)
+ if !prepareChallengeForm(w, r) {
+ return
+ }
+ defer cleanupChallengeForm(r)
+ lg, r := s.getRequestLogger(r)
localizer := localization.GetLocalizer(r)
redir := r.FormValue("redir")
- redirURL, err := url.ParseRequestURI(redir)
- if err != nil {
- lg.Error("invalid redirect", "err", err)
- s.respondWithStatus(w, r, localizer.T("invalid_redirect"), makeCode(err), http.StatusBadRequest)
- return
+ redirURL, err := s.validateRedirect(redir)
+ if err == nil && (redir == "" || (redirURL.Scheme == "" && !strings.HasPrefix(redir, "/"))) {
+ err = ErrInvalidRedirect
}
-
- switch redirURL.Scheme {
- case "", "http", "https":
- // allowed
- default:
- lg.Error("XSS attempt blocked, invalid redirect scheme", "scheme", redirURL.Scheme)
- s.respondWithStatus(w, r, localizer.T("invalid_redirect"), "", http.StatusBadRequest)
+ if err != nil {
+ s.rejectRedirect(w, r, err)
return
}
@@ -458,10 +636,15 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
}
- if _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {
+ if _, err := s.getCookie(r, anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})
- lg.Warn("user has cookies disabled, this is not an anubis bug")
+ if s.shouldRetryMissingTestCookie(r) {
+ lg.DebugContext(r.Context(), "verification cookie missing, retrying with a fresh challenge")
+ http.Redirect(w, r, redir, http.StatusFound)
+ return
+ }
+ lg.WarnContext(r.Context(), "user has cookies disabled, this is not an anubis bug")
s.respondWithError(w, r, localizer.T("cookies_disabled"), "")
return
}
@@ -469,43 +652,44 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
// used by the path checker rule
r.URL = redirURL
- urlParsed, err := r.URL.Parse(redir)
- if err != nil {
- s.respondWithError(w, r, localizer.T("redirect_not_parseable"), makeCode(err))
- return
- }
- if (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !matchRedirectDomain(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {
- lg.Debug("domain not allowed", "domain", urlParsed.Host)
- s.respondWithError(w, r, localizer.T("redirect_domain_not_allowed"), "")
- return
- }
-
cr, rule, err := s.check(r, lg)
if err != nil {
- lg.Error("check failed", "err", err)
+ lg.ErrorContext(r.Context(), "check failed", "err", err)
s.respondWithError(w, r, fmt.Sprintf("%s \"passChallenge\"", localizer.T("internal_server_error")), makeCode(err))
return
}
lg = lg.With("check_result", cr)
+ lockIndex := sha256.Sum256([]byte(r.FormValue("id")))
+ lock := &s.challengeLocks[lockIndex[0]]
+ lock.Lock()
+ defer lock.Unlock()
+
chall, err := s.getChallenge(r)
if err != nil {
- lg.Error("getChallenge failed", "err", err)
- s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), rule.Challenge.Algorithm), makeCode(err))
+ lg.ErrorContext(r.Context(), "getChallenge failed", "err", err)
+ s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), "getChallenge failed"), makeCode(err))
return
}
if chall.Spent {
- lg.Error("double spend prevented", "reason", "double_spend")
+ lg.ErrorContext(r.Context(), "double spend prevented", "reason", "double_spend")
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), "double_spend"), "")
return
}
+ if cr.Rule != config.RuleChallenge || rule == nil || rule.Challenge == nil ||
+ chall.PolicyRuleHash != rule.Hash() || chall.Method != rule.Challenge.Algorithm ||
+ chall.Difficulty != rule.Challenge.Difficulty || !slices.Equal(chall.Extensions, rule.Challenge.Extensions) {
+ s.respondWithStatus(w, r, localizer.T("internal_server_error"), makeCode(challenge.ErrFailed), http.StatusForbidden)
+ return
+ }
+
rule = s.hydrateChallengeRule(rule, chall, lg)
impl, ok := challenge.Get(chall.Method)
if !ok {
- lg.Error("check failed", "err", err)
+ lg.ErrorContext(r.Context(), "check failed", "err", err)
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), rule.Challenge.Algorithm), makeCode(ErrActualAnubisBug))
return
}
@@ -519,26 +703,56 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
}
if err := impl.Validate(r, lg, in); err != nil {
- failedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()
+ asn, asnDesc := asnFromContext(r.Context())
+ failedValidations.WithLabelValues(rule.Challenge.Algorithm, asn, asnDesc).Inc()
var cerr *challenge.Error
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
- lg.Debug("challenge validate call failed", "err", err)
+ lg.DebugContext(r.Context(), "challenge validate call failed", "err", err)
switch {
case errors.As(err, &cerr):
switch {
case errors.Is(err, challenge.ErrFailed):
- lg.Error("challenge failed", "err", err)
+ lg.ErrorContext(r.Context(), "challenge failed", "err", err)
s.respondWithStatus(w, r, cerr.PublicReason, makeCode(err), cerr.StatusCode)
return
case errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):
- lg.Error("invalid challenge format", "err", err)
+ lg.ErrorContext(r.Context(), "invalid challenge format", "err", err)
s.respondWithError(w, r, cerr.PublicReason, makeCode(err))
return
}
}
+ s.respondWithError(w, r, localizer.T("internal_server_error"), makeCode(err))
+ return
}
+ for _, name := range chall.Extensions {
+ if err := s.validateExtension(name, r, lg, in); err != nil {
+ asn, asnDesc := asnFromContext(r.Context())
+ failedValidations.WithLabelValues("extension/"+name, asn, asnDesc).Inc()
+ s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
+ lg.ErrorContext(r.Context(), "challenge extension failed", "extension", name, "err", err)
+
+ var cerr *challenge.Error
+ if errors.As(err, &cerr) {
+ s.respondWithStatus(w, r, cerr.PublicReason, makeCode(err), cerr.StatusCode)
+ } else {
+ s.respondWithError(w, r, localizer.T("internal_server_error"), makeCode(err))
+ }
+ return
+ }
+ }
+
+ chall.Spent = true
+ j := store.JSON[challenge.Challenge]{Underlying: s.store}
+ if err := j.Set(r.Context(), "challenge:"+chall.ID, *chall, 30*time.Minute); err != nil {
+ lg.DebugContext(r.Context(), "can't update information about challenge", "err", err)
+ s.respondWithError(w, r, localizer.T("internal_server_error"), makeCode(err))
+ return
+ }
+
+ lg.InfoContext(r.Context(), "challenge accepted")
+
// generate JWT cookie
var tokenString string
@@ -551,7 +765,7 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
}
if s.opts.JWTRestrictionHeader != "" {
if r.Header.Get(s.opts.JWTRestrictionHeader) == "" {
- lg.Error("JWTRestrictionHeader is set in config but not found in request, please check your reverse proxy config.")
+ lg.ErrorContext(r.Context(), "JWTRestrictionHeader is set in config but not found in request, please check your reverse proxy config.")
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.respondWithError(w, r, "failed to sign JWT", makeCode(err))
return
@@ -565,7 +779,7 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
tokenString, err = s.signJWT(claims)
if err != nil {
- lg.Error("failed to sign JWT", "err", err)
+ lg.ErrorContext(r.Context(), "failed to sign JWT", "err", err)
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
s.respondWithError(w, r, localizer.T("failed_to_sign_jwt"), makeCode(err))
return
@@ -573,15 +787,69 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
s.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})
- chall.Spent = true
- j := store.JSON[challenge.Challenge]{Underlying: s.store}
- if err := j.Set(r.Context(), "challenge:"+chall.ID, *chall, 30*time.Minute); err != nil {
- lg.Debug("can't update information about challenge", "err", err)
+ if origReferer := chall.Metadata["Referer"]; origReferer != "" {
+ s.SetCookie(w, CookieOpts{
+ Path: cookiePath,
+ Host: r.Host,
+ Name: anubis.OriginalRefererCookieName,
+ Value: url.QueryEscape(origReferer),
+ Expiry: 1 * time.Minute,
+ })
}
- challengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()
- lg.Debug("challenge passed, redirecting to app")
- http.Redirect(w, r, redir, http.StatusFound)
+ {
+ asn, asnDesc := asnFromContext(r.Context())
+ challengesValidated.WithLabelValues(rule.Challenge.Algorithm, asn, asnDesc).Inc()
+ }
+ lg.DebugContext(r.Context(), "challenge passed, redirecting to app")
+ http.Redirect(w, r, s.withRefererAttributionQuery(redir, chall.Metadata["Referer"], r.Host), http.StatusFound)
+}
+
+// refererAttributionQueryParams lists query parameters that already carry
+// campaign or referrer attribution. When the redirect target has any of these,
+// withRefererAttributionQuery leaves it alone rather than overwrite genuine
+// campaign data.
+var refererAttributionQueryParams = []string{
+ "ref", "source",
+ "utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term",
+ "gclid", "msclkid",
+}
+
+// withRefererAttributionQuery appends utm_source/utm_medium query parameters
+// derived from the original external Referer to redir, so client-side analytics
+// tools that fall back to query parameters when document.referrer is unusable
+// (e.g. Plausible, GA4) can still attribute the visit. This exists because
+// document.referrer itself cannot be fixed here: it reflects the browser's
+// actual navigation history -- the challenge page -- and neither Anubis nor any
+// page script can override it. Opt-in via PreserveRefererQueryParam since it
+// changes the URL the visitor lands on. See
+// https://github.com/TecharoHQ/anubis/issues/1596
+func (s *Server) withRefererAttributionQuery(redir, origReferer, host string) string {
+ if !s.opts.PreserveRefererQueryParam || origReferer == "" {
+ return redir
+ }
+
+ refURL, err := url.Parse(origReferer)
+ if err != nil || refURL.Host == "" || refURL.Host == host {
+ return redir
+ }
+
+ u, err := url.Parse(redir)
+ if err != nil {
+ return redir
+ }
+
+ q := u.Query()
+ for _, name := range refererAttributionQueryParams {
+ if q.Has(name) {
+ return redir
+ }
+ }
+
+ q.Set("utm_source", refURL.Host)
+ q.Set("utm_medium", "referral")
+ u.RawQuery = q.Encode()
+ return u.String()
}
func cr(name string, rule config.Rule, weight int) policy.CheckResult {
@@ -594,9 +862,12 @@ func cr(name string, rule config.Rule, weight int) policy.CheckResult {
// Check evaluates the list of rules, and returns the result
func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *policy.Bot, error) {
- host := r.Header.Get("X-Real-Ip")
+ if err := s.policy.ValidateRequestPath(r); err != nil {
+ return policy.CheckResult{}, nil, err
+ }
+ host := r.Header.Get("X-Real-IP")
if host == "" {
- return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("[misconfiguration] X-Real-Ip header is not set")
+ return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("[misconfiguration] X-Real-IP header is not set")
}
addr := net.ParseIP(host)
@@ -606,7 +877,9 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
weight := 0
- for _, b := range s.policy.Bots {
+ // Ranging by index keeps b from escaping to the heap on every iteration.
+ for i := range s.policy.Bots {
+ b := &s.policy.Bots[i]
match, err := b.Rules.Check(r)
if err != nil {
return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("can't run check %s: %w", b.Name, err)
@@ -615,10 +888,13 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
if match {
switch b.Action {
case config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:
- return cr("bot/"+b.Name, b.Action, weight), &b, nil
+ // Return a copy of the rule, as the shared policy must not be modified.
+ bot := *b
+ return cr("bot/"+b.Name, b.Action, weight), &bot, nil
case config.RuleWeigh:
- lg.Debug("adjusting weight", "name", b.Name, "delta", b.Weight.Adjust)
- policy.Applications.WithLabelValues("bot/"+b.Name, "WEIGH").Add(1)
+ lg.DebugContext(r.Context(), "adjusting weight", "name", b.Name, "delta", b.Weight.Adjust)
+ asn, asnDesc := asnFromContext(r.Context())
+ policy.Applications.WithLabelValues("bot/"+b.Name, "WEIGH", asn, asnDesc).Add(1)
weight += b.Weight.Adjust
}
}
@@ -627,7 +903,7 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
for _, t := range s.policy.Thresholds {
result, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})
if err != nil {
- lg.Error("error when evaluating threshold expression", "expression", t.Expression.String(), "err", err)
+ lg.ErrorContext(r.Context(), "error when evaluating threshold expression", "expression", t.Expression.String(), "err", err)
continue
}
@@ -638,14 +914,30 @@ func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *p
}
if matches {
+ challRules := t.Challenge
+ if challRules == nil {
+ // Non-CHALLENGE thresholds (ALLOW/DENY) don't have challenge config.
+ // Use an empty struct so hydrateChallengeRule can fill from stored
+ // challenge data during validation, rather than baking in defaults
+ // that could mismatch the difficulty the client actually solved for.
+ challRules = &config.ChallengeRules{}
+ }
+ identity, err := json.Marshal(t.Threshold)
+ if err != nil {
+ return policy.CheckResult{}, nil, err
+ }
return cr("threshold/"+t.Name, t.Action, weight), &policy.Bot{
- Challenge: t.Challenge,
+ Name: "threshold/" + t.Name + ":" + internal.FastHash(string(identity)),
+ Action: t.Action,
+ Challenge: challRules,
Rules: &checker.List{},
}, nil
}
}
return cr("default/allow", config.RuleAllow, weight), &policy.Bot{
+ Name: "default/allow",
+ Action: config.RuleAllow,
Challenge: &config.ChallengeRules{
Difficulty: s.policy.DefaultDifficulty,
Algorithm: config.DefaultAlgorithm,
diff --git a/lib/anubis_test.go b/lib/anubis_test.go
index 07785d3..29a959e 100644
--- a/lib/anubis_test.go
+++ b/lib/anubis_test.go
@@ -11,6 +11,7 @@ import (
"net/http/httptest"
"net/url"
"os"
+ "regexp"
"strings"
"sync"
"testing"
@@ -21,9 +22,9 @@ import (
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/challenge"
"github.com/TecharoHQ/anubis/lib/config"
+ "github.com/TecharoHQ/anubis/lib/geoip/geoiptest"
"github.com/TecharoHQ/anubis/lib/policy"
"github.com/TecharoHQ/anubis/lib/store"
- "github.com/TecharoHQ/anubis/lib/thoth/thothmock"
)
// TLogWriter implements io.Writer by logging each line to t.Log.
@@ -38,8 +39,8 @@ func NewTLogWriter(t *testing.T) io.Writer {
// Write splits input on newlines and logs each line separately.
func (w *TLogWriter) Write(p []byte) (n int, err error) {
- lines := strings.Split(string(p), "\n")
- for _, line := range lines {
+ lines := strings.SplitSeq(string(p), "\n")
+ for line := range lines {
if line != "" {
w.t.Log(line)
}
@@ -50,7 +51,7 @@ func (w *TLogWriter) Write(p []byte) (n int, err error) {
func loadPolicies(t *testing.T, fname string, difficulty int) *policy.ParsedConfig {
t.Helper()
- ctx := thothmock.WithMockThoth(t)
+ ctx := geoiptest.WithMockGeoIP(t)
if fname == "" {
fname = "./testdata/test_config.yaml"
@@ -58,7 +59,7 @@ func loadPolicies(t *testing.T, fname string, difficulty int) *policy.ParsedConf
t.Logf("loading policy file: %s", fname)
- anubisPolicy, err := LoadPoliciesOrDefault(ctx, fname, difficulty, "info")
+ anubisPolicy, err := LoadPoliciesOrDefault(ctx, fname, difficulty, "info", false)
if err != nil {
t.Fatal(err)
}
@@ -107,7 +108,7 @@ func makeChallenge(t *testing.T, ts *httptest.Server, cli *http.Client) challeng
if err != nil {
t.Fatalf("can't request challenge: %v", err)
}
- defer resp.Body.Close()
+ defer resp.Body.Close() //nolint:errcheck
var chall challengeResp
if err := json.NewDecoder(resp.Body).Decode(&chall); err != nil {
@@ -248,9 +249,9 @@ func TestLoadPolicies(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- defer fin.Close()
+ defer fin.Close() //nolint:errcheck
- if _, err := policy.ParseConfig(t.Context(), fin, fname, 4, "info"); err != nil {
+ if _, err := policy.ParseConfig(t.Context(), fin, fname, 4, "info", false); err != nil {
t.Fatal(err)
}
})
@@ -279,159 +280,205 @@ func TestCVE2025_24369(t *testing.T) {
}
}
-func TestCookieCustomExpiration(t *testing.T) {
- pol := loadPolicies(t, "testdata/zero_difficulty.yaml", 0)
- ckieExpiration := 10 * time.Minute
-
- srv := spawnAnubis(t, Options{
- Next: http.NewServeMux(),
- Policy: pol,
-
- CookieExpiration: ckieExpiration,
- })
-
- 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)
-
- if resp.StatusCode != http.StatusFound {
- resp.Write(os.Stderr)
- t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
- }
-
- var ckie *http.Cookie
- for _, cookie := range resp.Cookies() {
- t.Logf("%#v", cookie)
- if cookie.Name == anubis.CookieName {
- ckie = cookie
- break
- }
- }
- if ckie == nil {
- t.Errorf("Cookie %q not found", anubis.CookieName)
- return
- }
-}
-
func TestCookieSettings(t *testing.T) {
- pol := loadPolicies(t, "testdata/zero_difficulty.yaml", 0)
+ const cookieDomain = "127.0.0.1"
- srv := spawnAnubis(t, Options{
- Next: http.NewServeMux(),
- Policy: pol,
-
- CookieDomain: "127.0.0.1",
- CookiePartitioned: true,
- CookieSecure: true,
- CookieSameSite: http.SameSiteNoneMode,
- CookieExpiration: anubis.CookieDefaultExpirationTime,
- })
-
- 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)
-
- if resp.StatusCode != http.StatusFound {
- resp.Write(os.Stderr)
- t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
+ testCases := []struct {
+ name string
+ partitioned bool
+ secure bool
+ httpOnly bool
+ sameSite http.SameSite
+ wantSameSite http.SameSite
+ expiration time.Duration
+ }{
+ {
+ name: "secure samesite none is preserved",
+ partitioned: true,
+ secure: true,
+ httpOnly: false,
+ sameSite: http.SameSiteNoneMode,
+ wantSameSite: http.SameSiteNoneMode,
+ expiration: anubis.CookieDefaultExpirationTime,
+ },
+ {
+ name: "secure samesite none with httponly is preserved",
+ partitioned: true,
+ secure: true,
+ httpOnly: true,
+ sameSite: http.SameSiteNoneMode,
+ wantSameSite: http.SameSiteNoneMode,
+ expiration: anubis.CookieDefaultExpirationTime,
+ },
+ {
+ name: "insecure samesite none downgrades to lax",
+ partitioned: true,
+ secure: false,
+ httpOnly: false,
+ sameSite: http.SameSiteNoneMode,
+ wantSameSite: http.SameSiteLaxMode,
+ expiration: anubis.CookieDefaultExpirationTime,
+ },
+ {
+ name: "insecure samesite lax with httponly is preserved",
+ partitioned: false,
+ secure: false,
+ httpOnly: true,
+ sameSite: http.SameSiteLaxMode,
+ wantSameSite: http.SameSiteLaxMode,
+ expiration: anubis.CookieDefaultExpirationTime,
+ },
+ {
+ name: "custom expiration is honored",
+ partitioned: false,
+ secure: true,
+ httpOnly: false,
+ sameSite: http.SameSiteLaxMode,
+ wantSameSite: http.SameSiteLaxMode,
+ expiration: 10 * time.Minute,
+ },
}
- var ckie *http.Cookie
- for _, cookie := range resp.Cookies() {
- t.Logf("%#v", cookie)
- if cookie.Name == anubis.CookieName {
- ckie = cookie
- break
- }
- }
- if ckie == nil {
- t.Errorf("Cookie %q not found", anubis.CookieName)
- return
- }
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // load per subtest: New() mutates the policy (appends the
+ // honeypot bot), so sharing one instance leaks state across cases
+ pol := loadPolicies(t, "testdata/zero_difficulty.yaml", 0)
- if ckie.Domain != "127.0.0.1" {
- t.Errorf("cookie domain is wrong, wanted 127.0.0.1, got: %s", ckie.Domain)
- }
+ srv := spawnAnubis(t, Options{
+ Next: http.NewServeMux(),
+ Policy: pol,
- if ckie.Partitioned != srv.opts.CookiePartitioned {
- t.Errorf("wanted partitioned flag %v, got: %v", srv.opts.CookiePartitioned, ckie.Partitioned)
- }
+ CookieDomain: cookieDomain,
+ CookiePartitioned: tc.partitioned,
+ CookieSecure: tc.secure,
+ CookieHttpOnly: tc.httpOnly,
+ CookieSameSite: tc.sameSite,
+ CookieExpiration: tc.expiration,
+ })
- if ckie.Secure != srv.opts.CookieSecure {
- t.Errorf("wanted secure flag %v, got: %v", srv.opts.CookieSecure, ckie.Secure)
- }
- if ckie.SameSite != srv.opts.CookieSameSite {
- t.Errorf("wanted same site option %v, got: %v", srv.opts.CookieSameSite, ckie.SameSite)
+ 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)
+
+ if resp.StatusCode != http.StatusFound {
+ _ = resp.Write(os.Stderr) // if this fails we have bigger problems
+ t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
+ }
+
+ wantCookieName := srv.cookieName(anubis.CookieName)
+
+ var ckie *http.Cookie
+ for _, cookie := range resp.Cookies() {
+ t.Logf("%#v", cookie)
+ if cookie.Name == wantCookieName {
+ ckie = cookie
+ break
+ }
+ }
+ if ckie == nil {
+ t.Errorf("Cookie %q not found", wantCookieName)
+ return
+ }
+
+ if ckie.Domain != cookieDomain {
+ t.Errorf("cookie domain is wrong, wanted %s, got: %s", cookieDomain, ckie.Domain)
+ }
+ if ckie.Partitioned != tc.partitioned {
+ t.Errorf("wanted partitioned flag %v, got: %v", tc.partitioned, ckie.Partitioned)
+ }
+ if ckie.HttpOnly != tc.httpOnly {
+ t.Errorf("wanted httponly flag %v, got: %v", tc.httpOnly, ckie.HttpOnly)
+ }
+ if ckie.Secure != tc.secure {
+ t.Errorf("wanted secure flag %v, got: %v", tc.secure, ckie.Secure)
+ }
+ if ckie.SameSite != tc.wantSameSite {
+ t.Errorf("wanted same site option %v, got: %v", tc.wantSameSite, ckie.SameSite)
+ }
+ if got := time.Until(ckie.Expires); (got - tc.expiration).Abs() > time.Minute {
+ t.Errorf("cookie expiry is wrong, wanted ~%s remaining, got: %s", tc.expiration, got)
+ }
+ })
}
}
-func TestCookieSettingsSameSiteNoneModeDowngradedToLaxWhenUnsecure(t *testing.T) {
- pol := loadPolicies(t, "testdata/zero_difficulty.yaml", 0)
-
+// Regression test for https://github.com/TecharoHQ/anubis/issues/1314
+//
+// A request without an Anubis cookie must not answer with a Set-Cookie that
+// clears it. Browsers issue subresource requests in parallel with the
+// challenge, so such a response can land after pass-challenge has already
+// issued a valid cookie and would delete it. A request that does carry a
+// cookie Anubis rejects must still have it cleared.
+func TestChallengeDoesNotClearAbsentCookie(t *testing.T) {
srv := spawnAnubis(t, Options{
Next: http.NewServeMux(),
- Policy: pol,
-
- CookieDomain: "127.0.0.1",
- CookiePartitioned: true,
- CookieSecure: false,
- CookieSameSite: http.SameSiteNoneMode,
- CookieExpiration: anubis.CookieDefaultExpirationTime,
+ Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0),
})
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
- defer ts.Close()
+ t.Cleanup(ts.Close)
- cli := httpClient(t)
- chall := makeChallenge(t, ts, cli)
+ cookieName := srv.cookieName(anubis.CookieName)
- resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
+ for _, tc := range []struct {
+ name string
+ cookie *http.Cookie
+ wantClear bool
+ }{
+ {
+ name: "absent cookie is left alone",
+ cookie: nil,
+ wantClear: false,
+ },
+ {
+ name: "unparseable token is cleared",
+ cookie: &http.Cookie{Name: cookieName, Value: "not-a-jwt"},
+ wantClear: true,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ req, err := http.NewRequest(http.MethodGet, ts.URL+"/", nil)
+ if err != nil {
+ t.Fatalf("can't make request: %v", err)
+ }
- if resp.StatusCode != http.StatusFound {
- resp.Write(os.Stderr)
- t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
- }
+ if tc.cookie != nil {
+ req.AddCookie(tc.cookie)
+ }
- var ckie *http.Cookie
- for _, cookie := range resp.Cookies() {
- t.Logf("%#v", cookie)
- if cookie.Name == anubis.CookieName {
- ckie = cookie
- break
- }
- }
- if ckie == nil {
- t.Errorf("Cookie %q not found", anubis.CookieName)
- return
- }
+ resp, err := httpClient(t).Do(req)
+ if err != nil {
+ t.Fatalf("can't do request: %v", err)
+ }
+ t.Cleanup(func() { resp.Body.Close() }) //nolint:errcheck
- if ckie.Domain != "127.0.0.1" {
- t.Errorf("cookie domain is wrong, wanted 127.0.0.1, got: %s", ckie.Domain)
- }
+ if resp.StatusCode != http.StatusOK {
+ t.Errorf("wanted the challenge page with status %d, got: %d", http.StatusOK, resp.StatusCode)
+ }
- if ckie.Partitioned != srv.opts.CookiePartitioned {
- t.Errorf("wanted partitioned flag %v, got: %v", srv.opts.CookiePartitioned, ckie.Partitioned)
- }
+ var cleared bool
+ for _, ckie := range resp.Cookies() {
+ t.Logf("%#v", ckie)
+ if ckie.Name == cookieName && ckie.MaxAge < 0 {
+ cleared = true
+ }
+ }
- if ckie.Secure != srv.opts.CookieSecure {
- t.Errorf("wanted secure flag %v, got: %v", srv.opts.CookieSecure, ckie.Secure)
- }
- if ckie.SameSite != http.SameSiteLaxMode {
- t.Errorf("wanted same site Lax option %v, got: %v", http.SameSiteLaxMode, ckie.SameSite)
+ if cleared != tc.wantClear {
+ t.Errorf("wanted cookie %q cleared: %v, got: %v", cookieName, tc.wantClear, cleared)
+ }
+ })
}
}
func TestCheckDefaultDifficultyMatchesPolicy(t *testing.T) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintln(w, "OK")
+ fmt.Fprintln(w, "OK") //nolint:errcheck
})
for i := 1; i < 10; i++ {
@@ -452,7 +499,7 @@ func TestCheckDefaultDifficultyMatchesPolicy(t *testing.T) {
t.Fatal(err)
}
- req.Header.Add("X-Real-Ip", "127.0.0.1")
+ req.Header.Add("X-Real-IP", "127.0.0.1")
cr, bot, err := s.check(req, s.logger)
if err != nil {
@@ -470,7 +517,7 @@ func TestCheckDefaultDifficultyMatchesPolicy(t *testing.T) {
func TestBasePrefix(t *testing.T) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintln(w, "OK")
+ fmt.Fprintln(w, "OK") //nolint:errcheck
})
testCases := []struct {
@@ -537,7 +584,11 @@ func TestBasePrefix(t *testing.T) {
if err != nil {
t.Fatalf("can't request challenge: %v", err)
}
- defer resp.Body.Close()
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ t.Fatal(err)
+ }
+ }()
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status code %d, got: %d", http.StatusOK, resp.StatusCode)
@@ -611,15 +662,17 @@ func TestBasePrefix(t *testing.T) {
}
// Check cookie path
+ wantCookieName := srv.cookieName(anubis.CookieName)
+
var ckie *http.Cookie
for _, cookie := range resp.Cookies() {
- if cookie.Name == anubis.CookieName {
+ if cookie.Name == wantCookieName {
ckie = cookie
break
}
}
if ckie == nil {
- t.Errorf("Cookie %q not found", anubis.CookieName)
+ t.Errorf("Cookie %q not found", wantCookieName)
return
}
@@ -639,7 +692,7 @@ func TestCustomStatusCodes(t *testing.T) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Log(r.UserAgent())
w.WriteHeader(http.StatusOK)
- fmt.Fprintln(w, "OK")
+ fmt.Fprintln(w, "OK") //nolint:errcheck
})
statusMap := map[string]int{
@@ -679,13 +732,148 @@ func TestCustomStatusCodes(t *testing.T) {
}
}
+func TestNonGzipClientGetsDenyStatus(t *testing.T) {
+ pol := loadPolicies(t, "testdata/aggressive_403.yaml", 0)
+
+ srv := spawnAnubis(t, Options{
+ Next: http.NewServeMux(),
+ Policy: pol,
+ })
+
+ var logs bytes.Buffer
+ srv.logger = slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo}))
+
+ const requests = 4096
+
+ var challenged, denied int
+
+ for i := 0; i < requests; i++ {
+ req := httptest.NewRequest("GET", "http://example.com/", nil)
+ req.Header.Set("X-Real-IP", "127.0.0.1")
+ req.Header.Set("User-Agent", "CHALLENGE")
+ req.Header.Set("Accept-Encoding", "br")
+
+ w := httptest.NewRecorder()
+ srv.maybeReverseProxyOrPage(w, req)
+
+ switch w.Code {
+ case pol.StatusCodes.Challenge:
+ challenged++
+ case pol.StatusCodes.Deny:
+ denied++
+ default:
+ t.Fatalf("request %d: got status %d, wanted %d (challenge) or %d (deny)", i, w.Code, pol.StatusCodes.Challenge, pol.StatusCodes.Deny)
+ }
+ }
+
+ t.Logf("%d of %d requests were challenged, %d were rejected", challenged, requests, denied)
+
+ if denied == 0 {
+ t.Fatalf("no request out of %d was rejected, the one in 64 gzip check never fired", requests)
+ }
+
+ const rejectionMessage = "client was given a challenge but does not in fact support gzip compression"
+
+ var logged int
+
+ for _, line := range strings.Split(logs.String(), "\n") {
+ if !strings.Contains(line, rejectionMessage) {
+ continue
+ }
+
+ logged++
+
+ var record struct {
+ Level string `json:"level"`
+ }
+
+ if err := json.Unmarshal([]byte(line), &record); err != nil {
+ t.Fatalf("can't parse log line %q: %v", line, err)
+ }
+
+ if record.Level != slog.LevelInfo.String() {
+ t.Errorf("rejection was logged at %s, wanted %s", record.Level, slog.LevelInfo)
+ }
+ }
+
+ if logged != denied {
+ t.Errorf("%d requests were rejected but %d rejections were logged", denied, logged)
+ }
+}
+
+func assertHeaderValues(t *testing.T, header http.Header, name string, want ...string) {
+ t.Helper()
+
+ got := header.Values(name)
+ if len(got) != len(want) {
+ t.Fatalf("header %s has values %q, wanted %q", name, got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("header %s has values %q, wanted %q", name, got, want)
+ }
+ }
+}
+
+func TestDownstreamAnubisHeadersAreAuthoritative(t *testing.T) {
+ const attackerValue = "attacker-controlled"
+
+ t.Run("explicit allow", func(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ spoof bool
+ }{
+ {name: "ordinary request"},
+ {name: "spoofed headers", spoof: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var forwarded http.Header
+ srv := spawnAnubis(t, Options{
+ Next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ forwarded = r.Header.Clone()
+ w.WriteHeader(http.StatusNoContent)
+ }),
+ Policy: loadPolicies(t, "testdata/permissive.yaml", 4),
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil)
+ req.Header.Set("X-Real-IP", "127.0.0.1")
+ if tc.spoof {
+ req.Header["X-Anubis-Rule"] = []string{attackerValue, "second-attacker-value"}
+ req.Header["X-Anubis-Action"] = []string{attackerValue, "second-attacker-value"}
+ req.Header["X-Anubis-Status"] = []string{attackerValue, "second-attacker-value"}
+ req.Header.Set("Connection", "keep-alive, x-anubis-rule, X-Anubis-Status")
+ }
+
+ cr, _, err := srv.check(req, srv.logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ rr := httptest.NewRecorder()
+ srv.maybeReverseProxyOrPage(rr, req)
+
+ if forwarded == nil {
+ t.Fatal("request was not forwarded")
+ }
+ assertHeaderValues(t, forwarded, "X-Anubis-Rule", cr.Name)
+ assertHeaderValues(t, forwarded, "X-Anubis-Action", string(cr.Rule))
+ assertHeaderValues(t, forwarded, "X-Anubis-Status")
+ if tc.spoof {
+ assertHeaderValues(t, forwarded, "Connection", "keep-alive")
+ }
+ })
+ }
+ })
+}
+
func TestCloudflareWorkersRule(t *testing.T) {
for _, variant := range []string{"cel", "header"} {
t.Run(variant, func(t *testing.T) {
pol := loadPolicies(t, "./testdata/cloudflare-workers-"+variant+".yaml", 0)
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintln(w, "OK")
+ fmt.Fprintln(w, "OK") //nolint:errcheck
})
s, err := New(Options{
@@ -703,7 +891,7 @@ func TestCloudflareWorkersRule(t *testing.T) {
t.Fatal(err)
}
- req.Header.Add("X-Real-Ip", "127.0.0.1")
+ req.Header.Add("X-Real-IP", "127.0.0.1")
req.Header.Add("Cf-Worker", "true")
cr, _, err := s.check(req, s.logger)
@@ -722,7 +910,7 @@ func TestCloudflareWorkersRule(t *testing.T) {
t.Fatal(err)
}
- req.Header.Add("X-Real-Ip", "127.0.0.1")
+ req.Header.Add("X-Real-IP", "127.0.0.1")
cr, _, err := s.check(req, s.logger)
if err != nil {
@@ -757,9 +945,9 @@ func TestRuleChange(t *testing.T) {
chall := makeChallenge(t, ts, cli)
resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
- if resp.StatusCode != http.StatusFound {
- resp.Write(os.Stderr)
- t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
+ if resp.StatusCode != http.StatusForbidden {
+ _ = resp.Write(os.Stderr) // if stderr fails, there are bigger problems
+ t.Errorf("wanted %d, got: %d", http.StatusForbidden, resp.StatusCode)
}
}
@@ -862,6 +1050,39 @@ func TestStripBasePrefixFromRequest(t *testing.T) {
}
}
+// TestCookieSuffixNotSet makes sure that setting DYNAMIC_COOKIE_SUFFIX=false
+// won't create cookie names with suffixes.
+func TestCookieSuffixNotSet(t *testing.T) {
+ srv := spawnAnubis(t, Options{
+ Next: http.NewServeMux(),
+ CookieDomain: "127.0.0.1",
+ DynamicCookieSuffix: false,
+ })
+
+ t.Run("make sure cookie has no suffix", func(t *testing.T) {
+ if srv.cookieName(anubis.TestCookieName) != anubis.TestCookieName {
+ t.Error("output and input of the cookieName method must be the same")
+ }
+ })
+}
+
+// TestCookieSuffixIsSet makes sure that leaving DYNAMIC_COOKIE_SUFFIX=true
+// creates cookie names with suffixes.
+func TestCookieSuffixIsSet(t *testing.T) {
+ srv := spawnAnubis(t, Options{
+ Next: http.NewServeMux(),
+ CookieDomain: "127.0.0.1",
+ DynamicCookieSuffix: true,
+ })
+
+ t.Run("make sure cookie has suffix", func(t *testing.T) {
+ var testCookieWithSuffix = regexp.MustCompile("^" + anubis.TestCookieName + `-[a-z0-9]{8}$`)
+ if !testCookieWithSuffix.MatchString(srv.cookieName(anubis.TestCookieName)) {
+ t.Error("Test cookie does not have suffix")
+ }
+ })
+}
+
// TestChallengeFor_ErrNotFound makes sure that users with invalid challenge IDs
// in the test cookie don't get rejected by the database lookup failing.
func TestChallengeFor_ErrNotFound(t *testing.T) {
@@ -886,7 +1107,11 @@ func TestChallengeFor_ErrNotFound(t *testing.T) {
srv.maybeReverseProxyOrPage(w, req)
resp := w.Result()
- defer resp.Body.Close()
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ t.Fatal(err)
+ }
+ }()
body := new(strings.Builder)
_, err := io.Copy(body, resp.Body)
@@ -913,7 +1138,7 @@ func TestChallengeFor_ErrNotFound(t *testing.T) {
t.Run("make sure new test cookie is issued", func(t *testing.T) {
found := false
for _, cookie := range resp.Cookies() {
- if cookie.Name == anubis.TestCookieName {
+ if cookie.Name == srv.cookieName(anubis.TestCookieName) {
if cookie.Value == wrongCookie {
t.Error("a new challenge cookie should be issued")
}
@@ -1050,12 +1275,275 @@ func TestPassChallengeXSS(t *testing.T) {
})
}
+// Regression test for https://github.com/TecharoHQ/anubis/issues/1596: the Referer
+// header a visitor arrived with (e.g. an external social/referral link) must survive
+// the challenge round trip instead of being replaced by the internal challenge page
+// as the apparent referrer once the request reaches the upstream origin.
+func TestPassChallengeRestoresOriginalReferer(t *testing.T) {
+ const originalReferer = "https://example-external.test/some/post?utm=abc"
+
+ var forwarded []string
+ srv := spawnAnubis(t, Options{
+ Next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ forwarded = append(forwarded, r.Header.Get("Referer"))
+ w.WriteHeader(http.StatusNoContent)
+ }),
+ Policy: loadPolicies(t, "testdata/zero_difficulty.yaml", 0),
+ CookieExpiration: 10 * time.Minute,
+ })
+
+ ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
+ defer ts.Close()
+
+ cli := &http.Client{
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ }
+
+ // The visitor arrives from an external site and gets challenged.
+ req, err := http.NewRequest(http.MethodPost, ts.URL+"/.within.website/x/cmd/anubis/api/make-challenge", nil)
+ if err != nil {
+ t.Fatalf("can't make request: %v", err)
+ }
+ req.Header.Set("Referer", originalReferer)
+ req.Header.Set("User-Agent", "Mozilla/5.0")
+ q := req.URL.Query()
+ q.Set("redir", "/")
+ req.URL.RawQuery = q.Encode()
+
+ resp, err := cli.Do(req)
+ if err != nil {
+ t.Fatalf("can't request challenge: %v", err)
+ }
+ defer resp.Body.Close() //nolint:errcheck
+
+ var chall challengeResp
+ if err := json.NewDecoder(resp.Body).Decode(&chall); err != nil {
+ t.Fatalf("can't decode challenge: %v", err)
+ }
+
+ var testCookie *http.Cookie
+ for _, c := range resp.Cookies() {
+ if c.Name == srv.cookieName(anubis.TestCookieName) {
+ testCookie = c
+ }
+ }
+ if testCookie == nil {
+ t.Fatal("make-challenge did not set the verification cookie")
+ }
+
+ // Solve the (zero-difficulty) challenge and pass it.
+ nonce := 0
+ calculated := internal.SHA256sum(fmt.Sprintf("%s%d", chall.Challenge, nonce))
+
+ passReq, err := http.NewRequest(http.MethodGet, ts.URL+"/.within.website/x/cmd/anubis/api/pass-challenge", nil)
+ if err != nil {
+ t.Fatalf("can't make request: %v", err)
+ }
+ passReq.Header.Set("User-Agent", "Mozilla/5.0")
+ passReq.AddCookie(testCookie)
+ pq := passReq.URL.Query()
+ pq.Set("response", calculated)
+ pq.Set("nonce", fmt.Sprint(nonce))
+ pq.Set("redir", "/")
+ pq.Set("elapsedTime", "420")
+ pq.Set("id", chall.ID)
+ passReq.URL.RawQuery = pq.Encode()
+
+ passResp, err := cli.Do(passReq)
+ if err != nil {
+ t.Fatalf("can't do request: %v", err)
+ }
+ defer passResp.Body.Close() //nolint:errcheck
+
+ if passResp.StatusCode != http.StatusFound {
+ body, _ := io.ReadAll(passResp.Body)
+ t.Fatalf("wanted %d from pass-challenge, got %d: %s", http.StatusFound, passResp.StatusCode, body)
+ }
+
+ var authCookie, relayCookie *http.Cookie
+ for _, c := range passResp.Cookies() {
+ switch c.Name {
+ case srv.cookieName(anubis.CookieName):
+ authCookie = c
+ case srv.cookieName(anubis.OriginalRefererCookieName):
+ relayCookie = c
+ }
+ }
+ if authCookie == nil {
+ t.Fatal("pass-challenge did not set the auth cookie")
+ }
+ if relayCookie == nil {
+ t.Fatal("pass-challenge did not set the original referer relay cookie")
+ }
+ if want := url.QueryEscape(originalReferer); relayCookie.Value != want {
+ t.Errorf("wanted relay cookie value %q, got %q", want, relayCookie.Value)
+ }
+
+ location := passResp.Header.Get("Location")
+ if location == "" {
+ t.Fatal("pass-challenge did not return a redirect Location")
+ }
+
+ // This simulates the browser's follow-up navigation to the real page. A real
+ // browser sends the challenge page itself as Referer here (same-site redirect);
+ // use that misleading value to prove Anubis overrides it with the true original
+ // referer rather than just forwarding whatever the browser happened to send.
+ followReq, err := http.NewRequest(http.MethodGet, ts.URL+location, nil)
+ if err != nil {
+ t.Fatalf("can't make request: %v", err)
+ }
+ followReq.Header.Set("User-Agent", "Mozilla/5.0")
+ followReq.Header.Set("Referer", ts.URL+"/.within.website/x/cmd/anubis/api/pass-challenge")
+ followReq.AddCookie(authCookie)
+ followReq.AddCookie(relayCookie)
+
+ followResp, err := cli.Do(followReq)
+ if err != nil {
+ t.Fatalf("can't do request: %v", err)
+ }
+ defer followResp.Body.Close() //nolint:errcheck
+
+ if len(forwarded) != 1 {
+ t.Fatalf("wanted exactly one proxied request, got %d", len(forwarded))
+ }
+ if forwarded[0] != originalReferer {
+ t.Errorf("wanted upstream Referer %q, got %q", originalReferer, forwarded[0])
+ }
+
+ var relayCleared bool
+ for _, c := range followResp.Cookies() {
+ if c.Name == srv.cookieName(anubis.OriginalRefererCookieName) && c.MaxAge < 0 {
+ relayCleared = true
+ }
+ }
+ if !relayCleared {
+ t.Error("wanted the original referer relay cookie to be cleared after use")
+ }
+
+ // A later, ordinary navigation doesn't carry the (already consumed) relay cookie,
+ // so its own Referer must pass through untouched.
+ nextReferer := "https://example.test/some-other-internal-page"
+ nextReq, err := http.NewRequest(http.MethodGet, ts.URL+"/", nil)
+ if err != nil {
+ t.Fatalf("can't make request: %v", err)
+ }
+ nextReq.Header.Set("User-Agent", "Mozilla/5.0")
+ nextReq.Header.Set("Referer", nextReferer)
+ nextReq.AddCookie(authCookie)
+
+ nextResp, err := cli.Do(nextReq)
+ if err != nil {
+ t.Fatalf("can't do request: %v", err)
+ }
+ defer nextResp.Body.Close() //nolint:errcheck
+
+ if len(forwarded) != 2 {
+ t.Fatalf("wanted exactly two proxied requests total, got %d", len(forwarded))
+ }
+ if forwarded[1] != nextReferer {
+ t.Errorf("wanted upstream Referer %q on subsequent request, got %q", nextReferer, forwarded[1])
+ }
+}
+
+// document.referrer itself can't be fixed (it's the browser's own record of the
+// challenge-page navigation, not something a proxy or script can override), so
+// withRefererAttributionQuery is the opt-in fallback: it hands the original
+// referrer's host to the destination page via utm_source/utm_medium, which
+// client-side analytics tools such as Plausible read instead of
+// document.referrer when present.
+func TestWithRefererAttributionQuery(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ enabled bool
+ redir string
+ origReferer string
+ host string
+ want string
+ }{
+ {
+ name: "disabled leaves redir untouched",
+ enabled: false,
+ redir: "/page",
+ origReferer: "https://example-external.test/post",
+ host: "site.tld",
+ want: "/page",
+ },
+ {
+ name: "no captured referer leaves redir untouched",
+ enabled: true,
+ redir: "/page",
+ host: "site.tld",
+ want: "/page",
+ },
+ {
+ name: "same-site referer leaves redir untouched",
+ enabled: true,
+ redir: "/page",
+ origReferer: "https://site.tld/other-page",
+ host: "site.tld",
+ want: "/page",
+ },
+ {
+ name: "unparseable referer leaves redir untouched",
+ enabled: true,
+ redir: "/page",
+ origReferer: "://not a url",
+ host: "site.tld",
+ want: "/page",
+ },
+ {
+ name: "external referer with no existing query gets utm params",
+ enabled: true,
+ redir: "/page",
+ origReferer: "https://example-external.test/some/post",
+ host: "site.tld",
+ want: "/page?utm_medium=referral&utm_source=example-external.test",
+ },
+ {
+ name: "existing unrelated query is preserved alongside new params",
+ enabled: true,
+ redir: "/page?foo=bar",
+ origReferer: "https://example-external.test/some/post",
+ host: "site.tld",
+ want: "/page?foo=bar&utm_medium=referral&utm_source=example-external.test",
+ },
+ {
+ name: "existing utm_source is not clobbered",
+ enabled: true,
+ redir: "/page?utm_source=newsletter",
+ origReferer: "https://example-external.test/some/post",
+ host: "site.tld",
+ want: "/page?utm_source=newsletter",
+ },
+ {
+ name: "existing ref param is not clobbered",
+ enabled: true,
+ redir: "/page?ref=already-set",
+ origReferer: "https://example-external.test/some/post",
+ host: "site.tld",
+ want: "/page?ref=already-set",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := &Server{opts: Options{PreserveRefererQueryParam: tc.enabled}}
+
+ got := srv.withRefererAttributionQuery(tc.redir, tc.origReferer, tc.host)
+ if got != tc.want {
+ t.Errorf("wanted %q, got %q", tc.want, got)
+ }
+ })
+ }
+}
+
func TestPassChallengeNilRuleChallengeFallback(t *testing.T) {
pol := loadPolicies(t, "testdata/zero_difficulty.yaml", 0)
srv := spawnAnubis(t, Options{
- Next: http.NewServeMux(),
- Policy: pol,
+ Next: http.NewServeMux(),
+ Policy: pol,
+ RedirectDomains: []string{"allowed.example"},
})
allowThreshold, err := policy.ParsedThresholdFromConfig(config.Threshold{
@@ -1090,23 +1578,42 @@ func TestPassChallengeNilRuleChallengeFallback(t *testing.T) {
q.Set("id", chall.ID)
q.Set("challenge", chall.RandomData)
req.URL.RawQuery = q.Encode()
- req.Header.Set("X-Real-Ip", "203.0.113.4")
+ req.Header.Set("X-Real-IP", "203.0.113.4")
req.Header.Set("User-Agent", "NilChallengeTester/1.0")
- req.AddCookie(&http.Cookie{Name: anubis.TestCookieName, Value: chall.ID})
+ req.AddCookie(&http.Cookie{Name: srv.cookieName(anubis.TestCookieName), Value: chall.ID})
+
+ for _, target := range []string{"https:///evil.com/", "https://evil.com/", "//evil.com", `/\evil.com`} {
+ badReq := req.Clone(req.Context())
+ badQuery := badReq.URL.Query()
+ badQuery.Set("redir", target)
+ badReq.URL.RawQuery = badQuery.Encode()
+ badResponse := httptest.NewRecorder()
+ srv.PassChallenge(badResponse, badReq)
+ if badResponse.Code != http.StatusBadRequest || badResponse.Header().Get("Location") != "" || len(badResponse.Result().Cookies()) != 0 {
+ t.Fatalf("invalid target %q: got %d, %v", target, badResponse.Code, badResponse.Header())
+ }
+ stored, err := j.Get(req.Context(), "challenge:"+chall.ID)
+ if err != nil || stored.Spent {
+ t.Fatalf("invalid redirect changed challenge state: spent=%v, err=%v", stored.Spent, err)
+ }
+ }
+ const target = "https://allowed.example/safe%2Fpath?q=%2F%2Fevil.com#fragment"
+ q.Set("redir", target)
+ req.URL.RawQuery = q.Encode()
rr := httptest.NewRecorder()
srv.PassChallenge(rr, req)
- if rr.Code != http.StatusFound {
- t.Fatalf("expected redirect when validating challenge, got %d", rr.Code)
+ if rr.Code != http.StatusForbidden || rr.Header().Get("Location") != "" || authCookie(srv, rr.Result()) != nil {
+ t.Fatalf("changed policy accepted stored challenge: status %d", rr.Code)
}
}
func TestXForwardedForNoDoubleComma(t *testing.T) {
var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Forwarded-For", r.Header.Get("X-Forwarded-For"))
- fmt.Fprintln(w, "OK")
+ fmt.Fprintln(w, "OK") //nolint:errcheck
})
h = internal.XForwardedForToXRealIP(h)
@@ -1126,7 +1633,7 @@ func TestXForwardedForNoDoubleComma(t *testing.T) {
t.Fatal(err)
}
- req.Header.Set("X-Real-Ip", "10.0.0.1")
+ req.Header.Set("X-Real-IP", "10.0.0.1")
resp, err := ts.Client().Do(req)
if err != nil {
@@ -1141,3 +1648,45 @@ func TestXForwardedForNoDoubleComma(t *testing.T) {
t.Errorf("X-Forwarded-For has two leading commas: %q", xff)
}
}
+
+func TestOpenGraphAllowCacheCannotBypassPolicy(t *testing.T) {
+ for _, ua := range []string{"DENY", "CHALLENGE"} {
+ t.Run(ua, func(t *testing.T) {
+ pol := loadPolicies(t, "testdata/aggressive_403.yaml", 0)
+ forwarded := false
+ srv := spawnAnubis(t, Options{Policy: pol, OpenGraph: config.OpenGraph{Enabled: true}, Next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { forwarded = true })})
+ req := httptest.NewRequest("GET", "http://example.com/admin/secret.jpg", nil)
+ req.Header.Set("X-Real-IP", "127.0.0.1")
+ req.Header.Set("User-Agent", ua)
+ req.Header.Set("Accept-Encoding", "gzip")
+ if err := srv.store.Set(t.Context(), "ogtags:allow:"+req.Host+req.URL.String(), []byte("og:image"), time.Hour); err != nil {
+ t.Fatal(err)
+ }
+ srv.maybeReverseProxyOrPage(httptest.NewRecorder(), req)
+ if forwarded {
+ t.Fatal("OpenGraph metadata bypassed policy")
+ }
+ })
+ }
+}
+
+func TestDefaultPolicyWithoutGeoIP(t *testing.T) {
+ fin, err := data.BotPolicies.Open("botPolicies.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = fin.Close() }()
+ parsed, err := policy.ParseConfig(t.Context(), fin, "botPolicies.yaml", 4, "info", false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(parsed.Bots) == 0 {
+ t.Fatal("no rules were loaded")
+ }
+ for _, bot := range parsed.Bots {
+ switch bot.Name {
+ case "countries-with-aggressive-scrapers", "aggressive-asns-without-functional-abuse-contact":
+ t.Errorf("loaded rule without its required database: %s", bot.Name)
+ }
+ }
+}
diff --git a/lib/asn_logging_test.go b/lib/asn_logging_test.go
new file mode 100644
index 0000000..1629da1
--- /dev/null
+++ b/lib/asn_logging_test.go
@@ -0,0 +1,46 @@
+package lib
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/TecharoHQ/anubis/lib/geoip/geoiptest"
+)
+
+func TestGetRequestLoggerASN(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ logASN bool
+ withDB bool
+ ip string
+ wantASN string
+ wantDesc string
+ }{
+ {name: "announced", logASN: true, withDB: true, ip: "1.1.1.1", wantASN: "13335", wantDesc: "Cloudflare, Inc."},
+ {name: "private", logASN: true, withDB: true, ip: "10.0.0.1"},
+ {name: "not an IP", logASN: true, withDB: true, ip: "taco"},
+ {name: "logging disabled", withDB: true, ip: "1.1.1.1"},
+ {name: "no database", logASN: true, ip: "1.1.1.1"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ pol := loadPolicies(t, "", 4)
+ pol.LogASN = tt.logASN
+ pol.GeoIP = nil
+ if tt.withDB {
+ pol.GeoIP = geoiptest.DB(t)
+ }
+
+ srv := spawnAnubis(t, Options{Policy: pol})
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.Header.Set("X-Real-IP", tt.ip)
+
+ _, req = srv.getRequestLogger(req)
+ asn, desc := asnFromContext(req.Context())
+ if asn != tt.wantASN || desc != tt.wantDesc {
+ t.Errorf("want (%q, %q), got (%q, %q)", tt.wantASN, tt.wantDesc, asn, desc)
+ }
+ })
+ }
+}
diff --git a/lib/challenge/challenge.go b/lib/challenge/challenge.go
index d075930..56db6cf 100644
--- a/lib/challenge/challenge.go
+++ b/lib/challenge/challenge.go
@@ -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
}
diff --git a/lib/challenge/challengepage/bootstrap.go b/lib/challenge/challengepage/bootstrap.go
new file mode 100644
index 0000000..5aac422
--- /dev/null
+++ b/lib/challenge/challengepage/bootstrap.go
@@ -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, ""); err != nil {
+ return err
+ }
+ return nil
+ })
+}
diff --git a/lib/challenge/challengepage/build.sh b/lib/challenge/challengepage/build.sh
new file mode 100755
index 0000000..5bd8904
--- /dev/null
+++ b/lib/challenge/challengepage/build.sh
@@ -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
+
+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
diff --git a/lib/challenge/challengepage/explanation.go b/lib/challenge/challengepage/explanation.go
new file mode 100644
index 0000000..bf80e7c
--- /dev/null
+++ b/lib/challenge/challengepage/explanation.go
@@ -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), `$2`)
+}
diff --git a/lib/challenge/challengepage/explanation.templ b/lib/challenge/challengepage/explanation.templ
new file mode 100644
index 0000000..369e718
--- /dev/null
+++ b/lib/challenge/challengepage/explanation.templ
@@ -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) {
+
+
In common with other websites, log files are stored on the web server saving details such as the visitor's IP address, browser type, referring page and time of visit.
+
+#
Cookies may be used to remember visitor preferences when interacting with the website.
+
+#
Where registration is required, the visitor's email and a username will be stored on the server.
+
+#
+
+# Open Graph passthrough configuration, see here for more information:
+# https://anubis.techaro.lol/docs/admin/configuration/open-graph/
+openGraph:
+ # Enables Open Graph passthrough
+ enabled: false
+ # Enables the use of the HTTP host in the cache key, this enables
+ # caching metadata for multiple http hosts at once.
+ considerHost: false
+ # How long cached OpenGraph metadata should last in memory
+ ttl: 24h
+ # # If set, return these opengraph values instead of looking them up with
+ # # the target service.
+ # #
+ # # Correlates to properties in https://ogp.me/
+ # override:
+ # # og:title is required, it is the title of the website
+ # "og:title": "Techaro Anubis"
+ # "og:description": >-
+ # Anubis is a Web AI Firewall Utility that helps you fight the bots
+ # away so that you can maintain uptime at work!
+ # "description": >-
+ # Anubis is a Web AI Firewall Utility that helps you fight the bots
+ # away so that you can maintain uptime at work!
+
+# By default, send HTTP 200 back to clients that either get issued a challenge
+# or a denial. This seems weird, but this is load-bearing due to the fact that
+# the most aggressive scraper bots seem to really, really, want an HTTP 200 and
+# will stop sending requests once they get it.
+status_codes:
+ CHALLENGE: 200
+ DENY: 200
+
+# # Configuration for the metrics server. See the docs for more information:
+# #
+# # https://anubis.techaro.lol/docs/admin/policies#metrics-server
+# #
+# # This is commented out by default so that command line flags take precedence.
+# metrics:
+# bind: ":9090"
+# network: "tcp"
+#
+# # To protect your metrics server with basic auth, set credentials below:
+# #
+# # https://anubis.techaro.lol/docs/admin/policies#http-basic-authentication
+# basicAuth:
+# username: ""
+# password: ""
+#
+# # To serve metrics over TLS, set the path to the right TLS certificate and key
+# # here. When the files change on disk, they will automatically be reloaded.
+# #
+# # https://anubis.techaro.lol/docs/admin/policies#tls
+# tls:
+# certificate: /path/to/tls.crt
+# key: /path/to/tls.key
+#
+# # If you want to secure your metrics endpoint using mutual TLS (mTLS), set
+# # the path to a certificate authority public certificate here.
+# #
+# # https://anubis.techaro.lol/docs/admin/policies#mtls
+# ca: /path/to/ca.crt
+
+# Anubis can store temporary data in one of a few backends. See the storage
+# backends section of the docs for more information:
+#
+# https://anubis.techaro.lol/docs/admin/policies#storage-backends
+store:
+ backend: memory
+ parameters: {}
+
+# The weight thresholds for when to trigger individual challenges. Any
+# CHALLENGE will take precedence over this.
+#
+# A threshold has four configuration options:
+#
+# - name: the name that is reported down the stack and used for metrics
+# - expression: A CEL expression with the request weight in the variable
+# weight
+# - action: the Anubis action to apply, similar to in a bot policy
+# - challenge: which challenge to send to the user, similar to in a bot policy
+#
+# See https://anubis.techaro.lol/docs/admin/configuration/thresholds for more
+# information.
+thresholds:
+ # By default Anubis ships with the following thresholds:
+ - name: minimal-suspicion # This client is likely fine, its soul is lighter than a feather
+ expression: weight <= 0 # a feather weighs zero units
+ action: ALLOW # Allow the traffic through
+ # For clients that had some weight reduced through custom rules, give them a
+ # lightweight challenge.
+ - name: mild-suspicion
+ expression:
+ all:
+ - weight > 0
+ - weight < 10
+ action: CHALLENGE
+ challenge:
+ # https://anubis.techaro.lol/docs/admin/configuration/challenges/metarefresh
+ algorithm: metarefresh
+ difficulty: 1
+ # For clients that are browser-like but have either gained points from custom rules or
+ # report as a standard browser.
+ - name: moderate-suspicion
+ expression:
+ all:
+ - weight >= 10
+ - weight < 20
+ action: CHALLENGE
+ challenge:
+ # https://anubis.techaro.lol/docs/admin/configuration/challenges/proof-of-work
+ algorithm: fast
+ difficulty: 2 # two leading zeros, very fast for most clients
+ - name: mild-proof-of-work
+ expression:
+ all:
+ - weight >= 20
+ - weight < 30
+ action: CHALLENGE
+ challenge:
+ # https://anubis.techaro.lol/docs/admin/configuration/challenges/proof-of-work
+ algorithm: fast
+ difficulty: 4
+ # For clients that are browser like and have gained many points from custom rules
+ - name: extreme-suspicion
+ expression: weight >= 30
+ action: CHALLENGE
+ challenge:
+ # https://anubis.techaro.lol/docs/admin/configuration/challenges/proof-of-work
+ algorithm: fast
+ difficulty: 6
diff --git a/test/gubal/fast.yaml b/test/gubal/fast.yaml
new file mode 100644
index 0000000..45935bf
--- /dev/null
+++ b/test/gubal/fast.yaml
@@ -0,0 +1,12 @@
+# Baseline sweep policy: challenge every visitor with Anubis's proof-of-work.
+# A real, non-headless browser (the whole point of this sweep) solves the
+# challenge and reaches the backend; a bare HTTP client does not. The challenge
+# interstitial itself contains "Anubis", so the smoke-job's `grep -qi anubis`
+# pre-check passes under this policy.
+bots:
+ - name: everything-else
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ difficulty: 4
+ algorithm: fast
diff --git a/test/gubal/hashx.yaml b/test/gubal/hashx.yaml
new file mode 100644
index 0000000..9dd5240
--- /dev/null
+++ b/test/gubal/hashx.yaml
@@ -0,0 +1,12 @@
+# Baseline sweep policy: challenge every visitor with Anubis's proof-of-work.
+# A real, non-headless browser (the whole point of this sweep) solves the
+# challenge and reaches the backend; a bare HTTP client does not. The challenge
+# interstitial itself contains "Anubis", so the smoke-job's `grep -qi anubis`
+# pre-check passes under this policy.
+bots:
+ - name: everything-else
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ difficulty: 10
+ algorithm: hashx
diff --git a/test/gubal/metarefresh.yaml b/test/gubal/metarefresh.yaml
new file mode 100644
index 0000000..aec4b62
--- /dev/null
+++ b/test/gubal/metarefresh.yaml
@@ -0,0 +1,12 @@
+# Baseline sweep policy: challenge every visitor with Anubis's proof-of-work.
+# A real, non-headless browser (the whole point of this sweep) solves the
+# challenge and reaches the backend; a bare HTTP client does not. The challenge
+# interstitial itself contains "Anubis", so the smoke-job's `grep -qi anubis`
+# pre-check passes under this policy.
+bots:
+ - name: everything-else
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ difficulty: 1
+ algorithm: metarefresh
diff --git a/test/gubal/preact.yaml b/test/gubal/preact.yaml
new file mode 100644
index 0000000..c1ff921
--- /dev/null
+++ b/test/gubal/preact.yaml
@@ -0,0 +1,12 @@
+# Baseline sweep policy: challenge every visitor with Anubis's proof-of-work.
+# A real, non-headless browser (the whole point of this sweep) solves the
+# challenge and reaches the backend; a bare HTTP client does not. The challenge
+# interstitial itself contains "Anubis", so the smoke-job's `grep -qi anubis`
+# pre-check passes under this policy.
+bots:
+ - name: everything-else
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ difficulty: 1
+ algorithm: preact
diff --git a/test/gubal/sha256.yaml b/test/gubal/sha256.yaml
new file mode 100644
index 0000000..9272b6b
--- /dev/null
+++ b/test/gubal/sha256.yaml
@@ -0,0 +1,12 @@
+# Baseline sweep policy: challenge every visitor with Anubis's proof-of-work.
+# A real, non-headless browser (the whole point of this sweep) solves the
+# challenge and reaches the backend; a bare HTTP client does not. The challenge
+# interstitial itself contains "Anubis", so the smoke-job's `grep -qi anubis`
+# pre-check passes under this policy.
+bots:
+ - name: everything-else
+ user_agent_regex: .
+ action: CHALLENGE
+ challenge:
+ difficulty: 16
+ algorithm: sha256
diff --git a/test/lightpanda/README.md b/test/lightpanda/README.md
new file mode 100644
index 0000000..830b1d4
--- /dev/null
+++ b/test/lightpanda/README.md
@@ -0,0 +1,11 @@
+# Lightpanda
+
+This test makes sure that [Lightpanda](https://github.com/lightpanda-io/browser) clients are blocked by Anubis. It does so by downloading the latest nightly release of Lightpanda and testing it against an actual Anubis install.
+
+## Tale of woe
+
+On August 6th, 2026, administrators of the Haskell gitlab server [noticed a massive flood of requests](https://mailman.haskell.org/archives/list/ghc-devs@haskell.org/thread/AKWY3G76BMMOS6CNV5PZ64PHNWGDK3MM/) with the User-Agent `Lightpanda` in them. This confused me, as they use Anubis and I knew that Anubis had a rule to block Lightpanda [since some time in 2025 before configuration snippet parsing was added](https://github.com/TecharoHQ/anubis/commit/74e11505c6133ee1107811e81a0fd53e1d7876dd). At some point between when that rule was written and this test was made, Lightpanda changed their User-Agent string and this rule no longer worked.
+
+It was at least working on [March 31, 2025](https://github.com/lightpanda-io/browser/issues/500), when a user asked if Lightpanda could do User-Agent spoofing.
+
+This smoke test will let us know when Lightpanda changes their User-Agent string again.
diff --git a/test/lightpanda/anubis.yaml b/test/lightpanda/anubis.yaml
new file mode 100644
index 0000000..017cb27
--- /dev/null
+++ b/test/lightpanda/anubis.yaml
@@ -0,0 +1,6 @@
+bots:
+ - import: (data)/bots/headless-browsers.yaml
+
+status_codes:
+ CHALLENGE: 200
+ DENY: 403
diff --git a/test/lightpanda/test.mjs b/test/lightpanda/test.mjs
new file mode 100644
index 0000000..097484e
--- /dev/null
+++ b/test/lightpanda/test.mjs
@@ -0,0 +1,71 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+
+const execFileAsync = promisify(execFile);
+
+const LIGHTPANDA = "./var/lightpanda";
+const TARGET = "http://localhost:8923/reqmeta";
+
+// Anubis renders "Access Denied: error code " on its DENY page. The hash
+// changes whenever the rule changes, so only match the stable prefix.
+const DENIED = "Access Denied: error code";
+
+async function lightpandaFetch(...extraArgs) {
+ const { stdout } = await execFileAsync(
+ LIGHTPANDA,
+ ["fetch", "--dump", "html", ...extraArgs, TARGET],
+ { maxBuffer: 16 * 1024 * 1024 },
+ );
+ return stdout;
+}
+
+// Sanity check: a request that isn't a headless browser must sail through. If
+// this fails then Anubis isn't up yet or it's denying everything, and the
+// Lightpanda assertions below would pass for the wrong reason.
+async function checkControl() {
+ const resp = await fetch(TARGET, {
+ headers: { "User-Agent": "AnubisCI" },
+ });
+
+ if (resp.status !== 200) {
+ throw new Error(`control request: wanted status 200, got ${resp.status}`);
+ }
+}
+
+const cases = [
+ {
+ name: "default user agent",
+ args: [],
+ },
+ {
+ // Lightpanda still sends Sec-Ch-Ua when --user-agent is overridden, so
+ // Anubis must catch it even though the User-Agent says otherwise.
+ name: "spoofed user agent",
+ args: ["--user-agent", "AnubisCI"],
+ },
+];
+
+(async () => {
+ await checkControl();
+
+ let failed = false;
+
+ for (const { name, args } of cases) {
+ const page = await lightpandaFetch(...args);
+
+ if (!page.includes(DENIED)) {
+ console.log(page);
+ console.log(`${name}: Lightpanda was not denied`);
+ failed = true;
+ continue;
+ }
+
+ console.log(`${name}: Lightpanda was denied`);
+ }
+
+ if (failed) {
+ throw new Error("lightpanda smoke test failed");
+ }
+
+ process.exit(0);
+})();
diff --git a/test/lightpanda/test.sh b/test/lightpanda/test.sh
new file mode 100755
index 0000000..ad11eb3
--- /dev/null
+++ b/test/lightpanda/test.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+function cleanup() {
+ pkill -P $$
+}
+
+trap cleanup EXIT SIGINT
+
+# Build static assets
+(cd ../.. && npm ci && npm run assets)
+
+mkdir -p ./var
+
+# Lightpanda only ships nightly builds, so grab one if we don't have it yet.
+if [ ! -x ./var/lightpanda ]; then
+ curl -fsSL -o ./var/lightpanda \
+ "https://github.com/lightpanda-io/browser/releases/download/nightly/lightpanda-$(uname -m)-linux"
+ chmod a+x ./var/lightpanda
+fi
+
+go tool anubis --help 2>/dev/null || :
+
+go run ../cmd/unixhttpd &
+
+go tool anubis \
+ --policy-fname ./anubis.yaml \
+ --use-remote-address \
+ --target=unix://$(pwd)/unixhttpd.sock &
+
+backoff-retry node ./test.mjs
diff --git a/test/lightpanda/var/.gitignore b/test/lightpanda/var/.gitignore
new file mode 100644
index 0000000..c96a04f
--- /dev/null
+++ b/test/lightpanda/var/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
\ No newline at end of file
diff --git a/test/proxmox-e2e/README.md b/test/proxmox-e2e/README.md
new file mode 100644
index 0000000..385fe05
--- /dev/null
+++ b/test/proxmox-e2e/README.md
@@ -0,0 +1,3 @@
+# Proxmox end to end testing
+
+Prevents recurrence of [TecharoHQ/anubis#2015](https://github.com/TecharoHQ/anubis/discussions/2015). It spins up a new Ubuntu VM from a pool of potential candidates, tries to install Anubis on it, tries to start Anubis, and if it fails then this CI job fails and it creates a new VM for the pool.
diff --git a/test/proxmox-e2e/test.js b/test/proxmox-e2e/test.js
new file mode 100644
index 0000000..be5e837
--- /dev/null
+++ b/test/proxmox-e2e/test.js
@@ -0,0 +1,15 @@
+try {
+ host$`cd ../.. && rm -rf ./var/proxmox-test && go tool yeet --package-dest-dir ./var/proxmox-test --filter 'method == "deb" && goos == "linux" && goarch == "amd64"'`;
+ const deb = host$`ls ../../var/proxmox-test/*.deb`.trim().split("\n")[0];
+ console.log("package:", deb);
+ scp(deb, "/root/anubis.deb");
+
+ $`sudo apt-get -f install /root/anubis.deb`;
+ $`sudo cp /etc/anubis/default.env /etc/anubis/web.env`;
+ $`sudo cp /usr/share/doc/anubis/botPolicies.yaml /etc/anubis/web.botPolicies.yaml`;
+ $`sudo systemctl enable --now anubis@web.service`;
+ console.log($`sudo systemctl status anubis@web.service`);
+} catch (e) {
+ console.log($`journalctl --no-pager`);
+ throw e;
+}
diff --git a/test/proxmox-e2e/test.sh b/test/proxmox-e2e/test.sh
new file mode 100644
index 0000000..797679a
--- /dev/null
+++ b/test/proxmox-e2e/test.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+go install within.website/x/cmd/vmbully@v1.31.1-0.20261012190235-f9a7c830a701
+vmbully script --os-template local:vztmpl/ubuntu-24.04-standard_24.04-2_amd64.tar.zst test.js
diff --git a/test/ssh-ci/Dockerfile b/test/ssh-ci/Dockerfile
index 652749d..a712e3e 100644
--- a/test/ssh-ci/Dockerfile
+++ b/test/ssh-ci/Dockerfile
@@ -1,5 +1,5 @@
ARG ALPINE_VERSION=3.22
FROM alpine:${ALPINE_VERSION}
-RUN apk add -U go nodejs git build-base git npm bash zstd brotli gzip
+RUN apk add -U go nodejs git build-base git npm bash zstd brotli gzip rust cargo rust-wasm
LABEL org.opencontainers.image.source="https://github.com/TecharoHQ/anubis"
\ No newline at end of file
diff --git a/test/ssh-ci/docker-bake.hcl b/test/ssh-ci/docker-bake.hcl
index eb72fac..83dc8b2 100644
--- a/test/ssh-ci/docker-bake.hcl
+++ b/test/ssh-ci/docker-bake.hcl
@@ -1,4 +1,4 @@
-variable "ALPINE_VERSION" { default = "3.22" }
+variable "ALPINE_VERSION" { default = "3.24" }
group "default" {
targets = [
@@ -8,14 +8,13 @@ group "default" {
target "ci-runner" {
args = {
- ALPINE_VERSION = "3.22"
+ ALPINE_VERSION = "3.24"
}
context = "."
dockerfile = "./Dockerfile"
platforms = [
"linux/amd64",
"linux/arm64",
- "linux/arm/v7",
"linux/ppc64le",
"linux/riscv64",
]
@@ -23,4 +22,4 @@ target "ci-runner" {
tags = [
"ghcr.io/techarohq/anubis/ci-runner:latest"
]
-}
\ No newline at end of file
+}
diff --git a/test/ssh-ci/in-container.sh b/test/ssh-ci/in-container.sh
index db93cf2..1e4bf6f 100644
--- a/test/ssh-ci/in-container.sh
+++ b/test/ssh-ci/in-container.sh
@@ -5,4 +5,4 @@ set -x
npm ci
npm run build
-SKIP_INTEGRATION=1 go test ./...
\ No newline at end of file
+SKIP_INTEGRATION=1 go test -short ./...
\ No newline at end of file
diff --git a/test/ssh-ci/rigging.sh b/test/ssh-ci/rigging.sh
index 2e35af7..6d39364 100644
--- a/test/ssh-ci/rigging.sh
+++ b/test/ssh-ci/rigging.sh
@@ -16,13 +16,43 @@ Hosts["aarch64-16k"]="ci@192.168.2.28" # GOARCH=arm64 GOOS=linux 16k page
CIRunnerImage="ghcr.io/techarohq/anubis/ci-runner:latest"
RunID=${GITHUB_RUN_ID:-$(uuidgen)}
-RunFolder="anubis/runs/${RunID}"
+RunFolder="anubis/runs/${RunID:?}"
Target="${Hosts["$1"]}"
+# A build step that prints nothing for a few minutes leaves the connection idle
+# for long enough that something between the runner and the host drops it, which
+# kills the run with "client_loop: send disconnect: Broken pipe". Keepalives stop
+# the connection from ever looking idle.
+ssh() {
+ command ssh -o ServerAliveInterval=30 -o ServerAliveCountMax=6 "$@"
+}
+
ssh "${Target}" uname -av >/dev/null
+ssh "${Target}" rm -rf "${RunFolder}"
ssh "${Target}" mkdir -p "${RunFolder}"
git archive HEAD | ssh "${Target}" tar xC "${RunFolder}"
+# The WebAssembly artifacts are identical on every architecture and the target
+# hosts are bad at building them: there is no fast WebAssembly runtime for
+# wasm-opt and wasm2js on ppc64le or riscv64, and node dies with SIGILL on the
+# riscv64 host. Ship whatever is already built here. tar keeps the timestamps,
+# which are newer than the ones git archive gives the sources, so the build
+# scripts on the target see them as up to date and skip the work.
+PrebuiltGlobs=(
+ web/static/wasm/simd128/*.wasm
+ web/static/wasm/baseline/*.wasm
+ web/js/gen/wasm2js/*.wasm.js
+)
+shopt -s nullglob
+# shellcheck disable=SC2206 # the globs are meant to expand
+Prebuilt=(${PrebuiltGlobs[@]})
+shopt -u nullglob
+if [ "${#Prebuilt[@]}" -ne 0 ]; then
+ tar c "${Prebuilt[@]}" | ssh "${Target}" tar xC "${RunFolder}"
+else
+ echo "no prebuilt WebAssembly artifacts found, ${1} will build its own" >&2
+fi
+
ssh "${Target}" < {
+ if (resp.status !== 200) {
+ throw new Error(`wanted status 200, got status: ${resp.status}`);
+ }
+ return resp;
+ })
+ .then((resp) => resp.json());
+}
+
+(async () => {
+ const languages = await fetchLanguages();
+ console.log(
+ "Anubis is running, which means that importing configuration worked",
+ );
+
+ process.exit(0);
+})();
diff --git a/test/wildcard-match/test.sh b/test/wildcard-match/test.sh
new file mode 100755
index 0000000..5f74b9d
--- /dev/null
+++ b/test/wildcard-match/test.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+function cleanup() {
+ pkill -P $$
+}
+
+trap cleanup EXIT SIGINT
+
+# Build static assets
+(cd ../.. && npm ci && npm run assets)
+
+go tool anubis --help 2>/dev/null ||:
+
+go run ../cmd/unixhttpd &
+
+go tool anubis \
+ --policy-fname ./anubis.yaml \
+ --use-remote-address \
+ --target=unix://$(pwd)/unixhttpd.sock &
+
+backoff-retry node ./test.mjs
diff --git a/test/wildcard-match/var/.gitignore b/test/wildcard-match/var/.gitignore
new file mode 100644
index 0000000..c96a04f
--- /dev/null
+++ b/test/wildcard-match/var/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
\ No newline at end of file
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..1e12abc
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "compilerOptions": {
+ "paths": {
+ "@lib/*": ["./web/js/lib/*"]
+ }
+ }
+}
diff --git a/utils/cmd/botgenerate/main.go b/utils/cmd/botgenerate/main.go
new file mode 100644
index 0000000..9dd7ba8
--- /dev/null
+++ b/utils/cmd/botgenerate/main.go
@@ -0,0 +1,437 @@
+package main
+
+import (
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/facebookgo/flagenv"
+ "gopkg.in/yaml.v3"
+)
+
+var (
+ dataDir = flag.String("data-dir", "data/crawlers", "folder holding the crawler policy files")
+ dryRun = flag.Bool("dry-run", false, "report what would change but don't write any files")
+ list = flag.Bool("list", false, "list every crawler this tool can update, then exit")
+ slogLevel = flag.String("slog-level", "INFO", "logging level (DEBUG, INFO, WARN, ERROR)")
+ timeout = flag.Duration("timeout", 30*time.Second, "how long to wait for a single feed")
+ userAgent = flag.String("user-agent", "Anubis-botgenerate (+https://github.com/TecharoHQ/anubis)", "User-Agent to send when fetching feeds")
+)
+
+var (
+ ErrNoSuchCrawler = errors.New("botgenerate: no crawler by that name")
+ ErrRuleNotFound = errors.New("botgenerate: policy file has no rule by that name")
+ ErrNoRemoteAddresses = errors.New("botgenerate: rule has no remote_addresses field")
+ ErrNoPrefixes = errors.New("botgenerate: feed returned no usable prefixes")
+ ErrUnexpectedStatus = errors.New("botgenerate: feed returned an unexpected HTTP status")
+)
+
+// Source says where one crawler's IP range list comes from.
+type Source struct {
+ // File is the policy file to update, relative to --data-dir. Its name
+ // without the extension is how the crawler is named on the command line.
+ File string
+
+ // Rule is the name of the rule inside File whose remote_addresses list gets
+ // replaced. A policy file may hold more than one rule.
+ Rule string
+
+ // URL is the operator's published feed.
+ URL string
+}
+
+// Name is how this crawler is spelled on the command line.
+func (s Source) Name() string {
+ return strings.TrimSuffix(s.File, filepath.Ext(s.File))
+}
+
+func (s Source) LogValue() slog.Value {
+ return slog.GroupValue(
+ slog.String("file", s.File),
+ slog.String("rule", s.Rule),
+ slog.String("url", s.URL),
+ )
+}
+
+var sources = []Source{
+ {
+ File: "applebot.yaml",
+ Rule: "applebot",
+ URL: "https://search.developer.apple.com/applebot.json",
+ },
+ {
+ File: "bingbot.yaml",
+ Rule: "bingbot",
+ URL: "https://www.bing.com/toolbox/bingbot.json",
+ },
+ {
+ File: "commoncrawl.yaml",
+ Rule: "common-crawl",
+ URL: "https://index.commoncrawl.org/ccbot.json",
+ },
+ {
+ File: "duckduckbot.yaml",
+ Rule: "duckduckbot",
+ URL: "https://duckduckgo.com/duckduckbot.json",
+ },
+ {
+ // The list of Google crawlers that respect robots.txt
+ // https://developers.google.com/crawling/docs/crawlers-fetchers/verify-google-requests
+ File: "googlebot.yaml",
+ Rule: "googlebot",
+ URL: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
+ },
+ {
+ File: "mojeekbot.yaml",
+ Rule: "mojeekbot",
+ URL: "https://www.mojeek.com/mojeekbot.json",
+ },
+ {
+ File: "openai-gptbot.yaml",
+ Rule: "openai-gptbot",
+ URL: "https://openai.com/gptbot.json",
+ },
+ {
+ File: "openai-searchbot.yaml",
+ Rule: "openai-searchbot",
+ URL: "https://openai.com/searchbot.json",
+ },
+ {
+ File: "perplexitybot.yaml",
+ Rule: "perplexitybot",
+ URL: "https://www.perplexity.com/perplexitybot.json",
+ },
+ {
+ File: "qwantbot.yaml",
+ Rule: "qwantbot",
+ URL: "https://help.qwant.com/wp-content/uploads/sites/latest/qwantbot.json",
+ },
+}
+
+func init() {
+ flag.Usage = func() {
+ _, _ = fmt.Fprintf(flag.CommandLine.Output(), `Usage of %[1]s:
+
+ %[1]s [flags] [crawler...]
+
+Updates the remote_addresses list of each crawler from the IP range lists
+their operators publish. If no crawler is passed, it updates everything.
+
+After running this, run npm run format
+
+Flags:
+`, filepath.Base(os.Args[0]))
+
+ flag.PrintDefaults()
+ }
+}
+
+func main() {
+ flagenv.Parse()
+ flag.Parse()
+
+ var lvl slog.Level
+ if err := lvl.UnmarshalText([]byte(*slogLevel)); err != nil {
+ fmt.Fprintf(os.Stderr, "--slog-level=%q is invalid: %v\n", *slogLevel, err)
+ os.Exit(2)
+ }
+ slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lvl})))
+
+ if *list {
+ for _, src := range sources {
+ fmt.Printf("%-20s %s\n", src.Name(), src.URL)
+ }
+ return
+ }
+
+ want, err := selectSources(flag.Args())
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "%v\n\nRun %s --list to see every known crawler.\n", err, filepath.Base(os.Args[0]))
+ os.Exit(2)
+ }
+
+ u := &updater{
+ cli: &http.Client{Timeout: *timeout},
+ dataDir: *dataDir,
+ dryRun: *dryRun,
+ userAgent: *userAgent,
+ }
+
+ var errs []error
+ for _, src := range want {
+ if err := u.update(src); err != nil {
+ errs = append(errs, fmt.Errorf("%s: %w", src.Name(), err))
+ }
+ }
+
+ if len(errs) != 0 {
+ slog.Error("could not update every crawler", "err", errors.Join(errs...))
+ os.Exit(1)
+ }
+}
+
+func selectSources(names []string) ([]Source, error) {
+ if len(names) == 0 {
+ return sources, nil
+ }
+
+ var (
+ want []Source
+ errs []error
+ )
+
+ for _, name := range names {
+ idx := slices.IndexFunc(sources, func(s Source) bool { return s.Name() == name })
+ if idx == -1 {
+ errs = append(errs, fmt.Errorf("%w: %q", ErrNoSuchCrawler, name))
+ continue
+ }
+
+ want = append(want, sources[idx])
+ }
+
+ if len(errs) != 0 {
+ return nil, errors.Join(errs...)
+ }
+
+ return want, nil
+}
+
+type updater struct {
+ cli *http.Client
+ dataDir string
+ dryRun bool
+ userAgent string
+}
+
+func (u *updater) update(src Source) error {
+ lg := slog.With("crawler", src.Name())
+
+ prefixes, err := u.fetchPrefixes(src.URL)
+ if err != nil {
+ return err
+ }
+
+ fname := filepath.Join(u.dataDir, src.File)
+
+ data, err := os.ReadFile(fname)
+ if err != nil {
+ return fmt.Errorf("can't read policy file: %w", err)
+ }
+
+ var root yaml.Node
+ if err := yaml.Unmarshal(data, &root); err != nil {
+ return fmt.Errorf("can't parse %s: %w", fname, err)
+ }
+
+ old, err := setRemoteAddresses(&root, src.Rule, prefixes)
+ if err != nil {
+ return fmt.Errorf("can't update %s: %w", fname, err)
+ }
+
+ added, removed := diff(old, prefixes)
+ if len(added) == 0 && len(removed) == 0 {
+ lg.Info("already up to date", "prefixes", len(prefixes))
+ return nil
+ }
+
+ lg.Info("IP ranges changed", "added", len(added), "removed", len(removed), "total", len(prefixes))
+ lg.Debug("IP ranges changed", "added", added, "removed", removed)
+
+ if u.dryRun {
+ return nil
+ }
+
+ out, err := marshal(&root)
+ if err != nil {
+ return fmt.Errorf("can't serialize %s: %w", fname, err)
+ }
+
+ if err := os.WriteFile(fname, out, 0o644); err != nil {
+ return fmt.Errorf("can't write %s: %w", fname, err)
+ }
+
+ lg.Info("wrote policy file", "file", fname)
+
+ return nil
+}
+
+// prefixList is the common subset of JSON fields in search engine IP prefix feeds
+type prefixList struct {
+ Prefixes []struct {
+ IPv4Prefix string `json:"ipv4Prefix"`
+ IPv6Prefix string `json:"ipv6Prefix"`
+ } `json:"prefixes"`
+}
+
+func (u *updater) fetchPrefixes(url string) ([]string, error) {
+ req, err := http.NewRequest(http.MethodGet, url, nil)
+ if err != nil {
+ return nil, fmt.Errorf("can't build request for %s: %w", url, err)
+ }
+ req.Header.Set("User-Agent", u.userAgent)
+ req.Header.Set("Accept", "application/json")
+
+ resp, err := u.cli.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("can't fetch %s: %w", url, err)
+ }
+ defer resp.Body.Close() //nolint:errcheck
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("%w: %s returned %s", ErrUnexpectedStatus, url, resp.Status)
+ }
+
+ prefixes, err := parsePrefixes(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("can't read %s: %w", url, err)
+ }
+
+ return prefixes, nil
+}
+
+func parsePrefixes(r io.Reader) ([]string, error) {
+ var pl prefixList
+ if err := json.NewDecoder(r).Decode(&pl); err != nil {
+ return nil, fmt.Errorf("can't decode prefix list: %w", err)
+ }
+
+ var prefixes []string
+ for i, p := range pl.Prefixes {
+ var raw string
+ switch {
+ case p.IPv4Prefix != "":
+ raw = p.IPv4Prefix
+ case p.IPv6Prefix != "":
+ raw = p.IPv6Prefix
+ default:
+ return nil, fmt.Errorf("prefix %d has neither ipv4Prefix nor ipv6Prefix", i)
+ }
+
+ pfx, err := netip.ParsePrefix(raw)
+ if err != nil {
+ return nil, fmt.Errorf("prefix %d (%q) is not a CIDR range: %w", i, raw, err)
+ }
+
+ prefixes = append(prefixes, pfx.String())
+ }
+
+ if len(prefixes) == 0 {
+ return nil, ErrNoPrefixes
+ }
+
+ return prefixes, nil
+}
+
+func setRemoteAddresses(root *yaml.Node, rule string, prefixes []string) ([]string, error) {
+ if len(root.Content) == 0 {
+ return nil, fmt.Errorf("%w: %s (file is empty)", ErrRuleNotFound, rule)
+ }
+
+ for _, node := range root.Content[0].Content {
+ name := mappingValue(node, "name")
+ if name == nil || name.Value != rule {
+ continue
+ }
+
+ addrs := mappingValue(node, "remote_addresses")
+ if addrs == nil {
+ return nil, fmt.Errorf("%w: %s", ErrNoRemoteAddresses, rule)
+ }
+
+ old := make([]string, 0, len(addrs.Content))
+ for _, item := range addrs.Content {
+ old = append(old, item.Value)
+ }
+
+ var style yaml.Style
+ if addrs.Style&yaml.FlowStyle != 0 {
+ style = yaml.DoubleQuotedStyle
+ }
+
+ content := make([]*yaml.Node, 0, len(prefixes))
+ for _, prefix := range prefixes {
+ content = append(content, &yaml.Node{
+ Kind: yaml.ScalarNode,
+ Tag: "!!str",
+ Value: prefix,
+ Style: style,
+ })
+ }
+
+ addrs.Kind = yaml.SequenceNode
+ addrs.Tag = "!!seq"
+ addrs.Content = content
+
+ return old, nil
+ }
+
+ return nil, fmt.Errorf("%w: %s", ErrRuleNotFound, rule)
+}
+
+func mappingValue(node *yaml.Node, key string) *yaml.Node {
+ if node.Kind != yaml.MappingNode {
+ return nil
+ }
+
+ for i := 0; i+1 < len(node.Content); i += 2 {
+ if node.Content[i].Value == key {
+ return node.Content[i+1]
+ }
+ }
+
+ return nil
+}
+
+func marshal(root *yaml.Node) ([]byte, error) {
+ var buf strings.Builder
+
+ enc := yaml.NewEncoder(&buf)
+ enc.SetIndent(2)
+
+ if err := enc.Encode(root); err != nil {
+ return nil, err
+ }
+
+ if err := enc.Close(); err != nil {
+ return nil, err
+ }
+
+ return []byte(buf.String()), nil
+}
+
+func diff(before, after []string) (added, removed []string) {
+ inBefore := make(map[string]struct{}, len(before))
+ for _, prefix := range before {
+ inBefore[prefix] = struct{}{}
+ }
+
+ inAfter := make(map[string]struct{}, len(after))
+ for _, prefix := range after {
+ inAfter[prefix] = struct{}{}
+ }
+
+ for _, prefix := range after {
+ if _, ok := inBefore[prefix]; !ok {
+ added = append(added, prefix)
+ }
+ }
+
+ for _, prefix := range before {
+ if _, ok := inAfter[prefix]; !ok {
+ removed = append(removed, prefix)
+ }
+ }
+
+ return added, removed
+}
diff --git a/utils/cmd/botgenerate/main_test.go b/utils/cmd/botgenerate/main_test.go
new file mode 100644
index 0000000..0badf69
--- /dev/null
+++ b/utils/cmd/botgenerate/main_test.go
@@ -0,0 +1,586 @@
+package main
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "gopkg.in/yaml.v3"
+)
+
+func TestParsePrefixes(t *testing.T) {
+ t.Parallel()
+
+ for _, tt := range []struct {
+ name string
+ input string
+ want []string
+ err error
+ }{
+ {
+ name: "ipv4 and ipv6",
+ input: `{"prefixes":[{"ipv4Prefix":"192.0.2.0/24"},{"ipv6Prefix":"2001:db8::/32"}]}`,
+ want: []string{"192.0.2.0/24", "2001:db8::/32"},
+ },
+ {
+ name: "ignores unrelated fields",
+ input: `{"creationTime":"2026-08-31T14:46:46.000000","notes":"hi","prefixes":[{"ipv4Prefix":"192.0.2.0/24"}]}`,
+ want: []string{"192.0.2.0/24"},
+ },
+ {
+ name: "no prefixes",
+ input: `{"prefixes":[]}`,
+ err: ErrNoPrefixes,
+ },
+ {
+ name: "empty prefix entry",
+ input: `{"prefixes":[{"ipv4Prefix":"192.0.2.0/24"},{}]}`,
+ },
+ {
+ name: "bare address is not a prefix",
+ input: `{"prefixes":[{"ipv4Prefix":"192.0.2.1"}]}`,
+ },
+ {
+ name: "garbage prefix",
+ input: `{"prefixes":[{"ipv4Prefix":"not-an-ip/24"}]}`,
+ },
+ {
+ name: "not json",
+ input: `go away`,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ got, err := parsePrefixes(strings.NewReader(tt.input))
+
+ if tt.want == nil {
+ if err == nil {
+ t.Logf("got: %v", got)
+ t.Fatal("wanted an error but parsing succeeded")
+ }
+
+ if tt.err != nil && !errors.Is(err, tt.err) {
+ t.Logf("want: %v", tt.err)
+ t.Logf("got: %v", err)
+ t.Error("got wrong error")
+ }
+
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("can't parse prefix list: %v", err)
+ }
+
+ if !slices.Equal(got, tt.want) {
+ t.Logf("want: %v", tt.want)
+ t.Logf("got: %v", got)
+ t.Error("got wrong prefixes")
+ }
+ })
+ }
+}
+
+func TestSetRemoteAddresses(t *testing.T) {
+ t.Parallel()
+
+ for _, tt := range []struct {
+ name string
+ input string
+ rule string
+ want []string
+ wantOld []string
+ err error
+ }{
+ {
+ name: "block style rule",
+ input: `- name: googlebot
+ user_agent_regex: \+http\://www\.google\.com/bot\.html
+ action: ALLOW
+ remote_addresses:
+ - 192.0.2.0/24
+`,
+ rule: "googlebot",
+ want: []string{"198.51.100.0/24"},
+ wantOld: []string{"192.0.2.0/24"},
+ },
+ {
+ name: "picks the right rule in a multi rule file",
+ input: `- name: first
+ action: ALLOW
+ remote_addresses: ["192.0.2.0/24"]
+- name: second
+ action: ALLOW
+ remote_addresses: ["203.0.113.0/24"]
+`,
+ rule: "second",
+ want: []string{"198.51.100.0/24"},
+ wantOld: []string{"203.0.113.0/24"},
+ },
+ {
+ name: "rule is missing",
+ input: `- name: googlebot
+ action: ALLOW
+ remote_addresses: ["192.0.2.0/24"]
+`,
+ rule: "bingbot",
+ err: ErrRuleNotFound,
+ },
+ {
+ name: "rule has no remote_addresses",
+ input: `- name: yandexbot
+ action: ALLOW
+`,
+ rule: "yandexbot",
+ err: ErrNoRemoteAddresses,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ var root yaml.Node
+ if err := yaml.Unmarshal([]byte(tt.input), &root); err != nil {
+ t.Fatalf("can't parse test fixture: %v", err)
+ }
+
+ old, err := setRemoteAddresses(&root, tt.rule, tt.want)
+
+ if tt.err != nil {
+ if !errors.Is(err, tt.err) {
+ t.Logf("want: %v", tt.err)
+ t.Logf("got: %v", err)
+ t.Error("got wrong error")
+ }
+
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("can't set remote addresses: %v", err)
+ }
+
+ if !slices.Equal(old, tt.wantOld) {
+ t.Logf("want: %v", tt.wantOld)
+ t.Logf("got: %v", old)
+ t.Error("got wrong previous addresses")
+ }
+
+ data, err := marshal(&root)
+ if err != nil {
+ t.Fatalf("can't serialize result: %v", err)
+ }
+
+ var rules []struct {
+ Name string `yaml:"name"`
+ RemoteAddr []string `yaml:"remote_addresses"`
+ }
+ if err := yaml.Unmarshal(data, &rules); err != nil {
+ t.Fatalf("can't reparse result: %v", err)
+ }
+
+ idx := slices.IndexFunc(rules, func(r struct {
+ Name string `yaml:"name"`
+ RemoteAddr []string `yaml:"remote_addresses"`
+ }) bool {
+ return r.Name == tt.rule
+ })
+ if idx == -1 {
+ t.Fatalf("rule %s vanished from the result:\n%s", tt.rule, data)
+ }
+
+ if !slices.Equal(rules[idx].RemoteAddr, tt.want) {
+ t.Logf("want: %v", tt.want)
+ t.Logf("got: %v", rules[idx].RemoteAddr)
+ t.Error("got wrong addresses in output")
+ }
+ })
+ }
+}
+
+func TestSetRemoteAddressesKeepsComments(t *testing.T) {
+ t.Parallel()
+
+ const input = `# Indexing for search and Siri
+# https://support.apple.com/en-us/119829
+- name: applebot
+ user_agent_regex: Applebot
+ action: ALLOW
+ # https://search.developer.apple.com/applebot.json
+ remote_addresses: ["17.241.208.160/27"]
+ # trailing note
+`
+
+ var root yaml.Node
+ if err := yaml.Unmarshal([]byte(input), &root); err != nil {
+ t.Fatalf("can't parse test fixture: %v", err)
+ }
+
+ if _, err := setRemoteAddresses(&root, "applebot", []string{"192.0.2.0/24"}); err != nil {
+ t.Fatalf("can't set remote addresses: %v", err)
+ }
+
+ data, err := marshal(&root)
+ if err != nil {
+ t.Fatalf("can't serialize result: %v", err)
+ }
+
+ for _, want := range []string{
+ "# Indexing for search and Siri",
+ "# https://support.apple.com/en-us/119829",
+ "# https://search.developer.apple.com/applebot.json",
+ "# trailing note",
+ "user_agent_regex: Applebot",
+ } {
+ if !strings.Contains(string(data), want) {
+ t.Logf("want to find: %q", want)
+ t.Logf("got:\n%s", data)
+ t.Error("output lost part of the original file")
+ }
+ }
+}
+func TestSetRemoteAddressesKeepsStyle(t *testing.T) {
+ t.Parallel()
+
+ for _, tt := range []struct {
+ name string
+ input string
+ want string
+ }{
+ {
+ name: "flow style quotes every prefix",
+ input: "- name: applebot\n remote_addresses: [\"192.0.2.0/24\"]\n",
+ want: `remote_addresses: ["198.51.100.0/24", "2001:db8::/32"]`,
+ },
+ {
+ name: "block style leaves prefixes bare",
+ input: "- name: applebot\n remote_addresses:\n - 192.0.2.0/24\n",
+ want: "remote_addresses:\n - 198.51.100.0/24\n - 2001:db8::/32",
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ var root yaml.Node
+ if err := yaml.Unmarshal([]byte(tt.input), &root); err != nil {
+ t.Fatalf("can't parse test fixture: %v", err)
+ }
+
+ if _, err := setRemoteAddresses(&root, "applebot", []string{"198.51.100.0/24", "2001:db8::/32"}); err != nil {
+ t.Fatalf("can't set remote addresses: %v", err)
+ }
+
+ data, err := marshal(&root)
+ if err != nil {
+ t.Fatalf("can't serialize result: %v", err)
+ }
+
+ if !strings.Contains(string(data), tt.want) {
+ t.Logf("want to find:\n%s", tt.want)
+ t.Logf("got:\n%s", data)
+ t.Error("wrote the prefixes in the wrong style")
+ }
+ })
+ }
+}
+
+func TestSelectSources(t *testing.T) {
+ t.Parallel()
+
+ for _, tt := range []struct {
+ name string
+ input []string
+ want []string
+ err error
+ }{
+ {
+ name: "no arguments selects everything",
+ input: nil,
+ want: allSourceNames(),
+ },
+ {
+ name: "by name",
+ input: []string{"googlebot", "bingbot"},
+ want: []string{"googlebot", "bingbot"},
+ },
+ {
+ name: "unknown crawler",
+ input: []string{"googlebot", "clippy"},
+ err: ErrNoSuchCrawler,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ got, err := selectSources(tt.input)
+
+ if tt.err != nil {
+ if !errors.Is(err, tt.err) {
+ t.Logf("want: %v", tt.err)
+ t.Logf("got: %v", err)
+ t.Error("got wrong error")
+ }
+
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("can't select sources: %v", err)
+ }
+
+ var names []string
+ for _, src := range got {
+ names = append(names, src.Name())
+ }
+
+ if !slices.Equal(names, tt.want) {
+ t.Logf("want: %v", tt.want)
+ t.Logf("got: %v", names)
+ t.Error("selected the wrong crawlers")
+ }
+ })
+ }
+}
+
+func TestSourcesMatchDataFiles(t *testing.T) {
+ t.Parallel()
+
+ const dir = "../../../data/crawlers"
+
+ for _, src := range sources {
+ t.Run(src.Name(), func(t *testing.T) {
+ t.Parallel()
+
+ data, err := os.ReadFile(filepath.Join(dir, src.File))
+ if err != nil {
+ t.Fatalf("can't read policy file: %v", err)
+ }
+
+ var rules []struct {
+ Name string `yaml:"name"`
+ RemoteAddr []string `yaml:"remote_addresses"`
+ }
+ if err := yaml.Unmarshal(data, &rules); err != nil {
+ t.Fatalf("can't parse policy file: %v", err)
+ }
+
+ for _, rule := range rules {
+ if rule.Name != src.Rule {
+ continue
+ }
+
+ if len(rule.RemoteAddr) == 0 {
+ t.Errorf("rule %s has no remote_addresses to update", src.Rule)
+ }
+
+ return
+ }
+
+ t.Errorf("%s declares no rule named %q", src.File, src.Rule)
+ })
+ }
+}
+
+func TestUpdate(t *testing.T) {
+ t.Parallel()
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("User-Agent"); got != "test-agent" {
+ t.Errorf("wanted User-Agent test-agent, got: %s", got)
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ writePrefixes(t, w)
+ }))
+ t.Cleanup(srv.Close)
+
+ dir := t.TempDir()
+ fname := filepath.Join(dir, "googlebot.yaml")
+
+ const input = `- name: googlebot
+ action: ALLOW
+ # source of truth
+ remote_addresses:
+ - 192.0.2.0/24
+`
+
+ if err := os.WriteFile(fname, []byte(input), 0o644); err != nil {
+ t.Fatalf("can't write test fixture: %v", err)
+ }
+
+ src := Source{File: "googlebot.yaml", Rule: "googlebot", URL: srv.URL}
+
+ t.Run("dry run leaves the file alone", func(t *testing.T) {
+ u := &updater{cli: srv.Client(), dataDir: dir, dryRun: true, userAgent: "test-agent"}
+
+ if err := u.update(src); err != nil {
+ t.Fatalf("can't update: %v", err)
+ }
+
+ got, err := os.ReadFile(fname)
+ if err != nil {
+ t.Fatalf("can't read file back: %v", err)
+ }
+
+ if string(got) != input {
+ t.Logf("want:\n%s", input)
+ t.Logf("got:\n%s", got)
+ t.Error("dry run wrote to the file")
+ }
+ })
+
+ t.Run("writes the new prefixes", func(t *testing.T) {
+ u := &updater{cli: srv.Client(), dataDir: dir, userAgent: "test-agent"}
+
+ if err := u.update(src); err != nil {
+ t.Fatalf("can't update: %v", err)
+ }
+
+ got, err := os.ReadFile(fname)
+ if err != nil {
+ t.Fatalf("can't read file back: %v", err)
+ }
+
+ for _, want := range []string{"198.51.100.0/24", "2001:db8::/32", "# source of truth"} {
+ if !strings.Contains(string(got), want) {
+ t.Logf("want to find: %q", want)
+ t.Logf("got:\n%s", got)
+ t.Error("output is missing something")
+ }
+ }
+
+ if strings.Contains(string(got), "192.0.2.0/24") {
+ t.Logf("got:\n%s", got)
+ t.Error("stale prefix survived the update")
+ }
+ })
+}
+
+func TestUpdateRejectsBadFeed(t *testing.T) {
+ t.Parallel()
+
+ for _, tt := range []struct {
+ name string
+ status int
+ body string
+ wantErr error
+ }{
+ {name: "server error", status: http.StatusInternalServerError, body: "nope", wantErr: ErrUnexpectedStatus},
+ {name: "empty feed", status: http.StatusOK, body: `{"prefixes":[]}`, wantErr: ErrNoPrefixes},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(tt.status)
+ if _, err := w.Write([]byte(tt.body)); err != nil {
+ t.Errorf("can't write response: %v", err)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ dir := t.TempDir()
+ fname := filepath.Join(dir, "googlebot.yaml")
+
+ const input = "- name: googlebot\n action: ALLOW\n remote_addresses:\n - 192.0.2.0/24\n"
+ if err := os.WriteFile(fname, []byte(input), 0o644); err != nil {
+ t.Fatalf("can't write test fixture: %v", err)
+ }
+
+ u := &updater{cli: srv.Client(), dataDir: dir, userAgent: "test-agent"}
+
+ err := u.update(Source{File: "googlebot.yaml", Rule: "googlebot", URL: srv.URL})
+ if !errors.Is(err, tt.wantErr) {
+ t.Logf("want: %v", tt.wantErr)
+ t.Logf("got: %v", err)
+ t.Error("got wrong error")
+ }
+
+ got, err := os.ReadFile(fname)
+ if err != nil {
+ t.Fatalf("can't read file back: %v", err)
+ }
+
+ if string(got) != input {
+ t.Logf("got:\n%s", got)
+ t.Error("a failed fetch must not touch the policy file")
+ }
+ })
+ }
+}
+
+func TestDiff(t *testing.T) {
+ t.Parallel()
+
+ for _, tt := range []struct {
+ name string
+ old, cur []string
+ wantAdded []string
+ wantRemoved []string
+ }{
+ {
+ name: "no change",
+ old: []string{"192.0.2.0/24"},
+ cur: []string{"192.0.2.0/24"},
+ },
+ {
+ name: "reordering is not a change",
+ old: []string{"192.0.2.0/24", "198.51.100.0/24"},
+ cur: []string{"198.51.100.0/24", "192.0.2.0/24"},
+ wantAdded: nil,
+ },
+ {
+ name: "added and removed",
+ old: []string{"192.0.2.0/24", "203.0.113.0/24"},
+ cur: []string{"192.0.2.0/24", "198.51.100.0/24"},
+ wantAdded: []string{"198.51.100.0/24"},
+ wantRemoved: []string{"203.0.113.0/24"},
+ },
+ {
+ name: "first run",
+ cur: []string{"192.0.2.0/24"},
+ wantAdded: []string{"192.0.2.0/24"},
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ added, removed := diff(tt.old, tt.cur)
+
+ if !slices.Equal(added, tt.wantAdded) {
+ t.Logf("want: %v", tt.wantAdded)
+ t.Logf("got: %v", added)
+ t.Error("got wrong added prefixes")
+ }
+
+ if !slices.Equal(removed, tt.wantRemoved) {
+ t.Logf("want: %v", tt.wantRemoved)
+ t.Logf("got: %v", removed)
+ t.Error("got wrong removed prefixes")
+ }
+ })
+ }
+}
+
+func allSourceNames() []string {
+ var names []string
+ for _, src := range sources {
+ names = append(names, src.Name())
+ }
+ return names
+}
+
+func writePrefixes(t *testing.T, w http.ResponseWriter) {
+ t.Helper()
+
+ const body = `{"prefixes":[{"ipv4Prefix":"198.51.100.0/24"},{"ipv6Prefix":"2001:db8::/32"}]}`
+
+ if _, err := w.Write([]byte(body)); err != nil {
+ t.Errorf("can't write response: %v", err)
+ }
+}
diff --git a/utils/cmd/iplist2rule/blocklist.go b/utils/cmd/iplist2rule/blocklist.go
index 72bb47d..9c60673 100644
--- a/utils/cmd/iplist2rule/blocklist.go
+++ b/utils/cmd/iplist2rule/blocklist.go
@@ -7,26 +7,19 @@ import (
"net/http"
"net/netip"
"strings"
+
+ "github.com/TecharoHQ/anubis/internal/iplist"
)
-// FetchBlocklist reads the blocklist over HTTP and returns every non-commented
+// ParseBlocklist reads a plain-text blocklist and returns every non-commented
// line parsed as an IP address in CIDR notation. IPv4 addresses are returned as
// /32, IPv6 addresses as /128.
//
// This function was generated with GLM 4.7.
-func FetchBlocklist(url string) ([]string, error) {
- resp, err := http.Get(url)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
+func ParseBlocklist(list io.Reader) ([]string, error) {
+ var addrs []string
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status)
- }
-
- var lines []string
- scanner := bufio.NewScanner(resp.Body)
+ scanner := bufio.NewScanner(list)
for scanner.Scan() {
line := scanner.Text()
// Skip empty lines and comments (lines starting with #)
@@ -46,12 +39,52 @@ func FetchBlocklist(url string) ([]string, error) {
} else {
cidr = fmt.Sprintf("%s/128", addr.String())
}
- lines = append(lines, cidr)
+ addrs = append(addrs, cidr)
}
- if err := scanner.Err(); err != nil && err != io.EOF {
+ if err := scanner.Err(); err != nil {
return nil, err
}
- return lines, nil
+ return addrs, nil
+}
+
+// FetchBlocklist fetches url over HTTP and parses the response body as a
+// blocklist. JSON responses (detected via the Content-Type header or a
+// ".json" URL suffix) are parsed with ParsePrefixList; everything else is
+// treated as a plain-text list and parsed with ParseBlocklist.
+func FetchBlocklist(url string) ([]string, error) {
+ resp, err := http.Get(url)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close() //nolint:errcheck
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status)
+ }
+
+ if isJSONBlocklist(url, resp.Header.Get("Content-Type")) {
+ return ParsePrefixList(resp.Body)
+ }
+
+ return ParseBlocklist(resp.Body)
+}
+
+func isJSONBlocklist(url, contentType string) bool {
+ if contentType == "json" {
+ return true
+ }
+
+ return strings.HasSuffix(strings.ToLower(url), ".json")
+}
+
+// ParsePrefixList decodes a JSON document read from list in the Google/OpenAI
+// bot IP range format and returns every IPv4 and IPv6 prefix it contains.
+func ParsePrefixList(list io.Reader) ([]string, error) {
+ pl, err := iplist.Parse(list)
+ if err != nil {
+ return nil, err
+ }
+ return pl.CIDRs(), nil
}
diff --git a/utils/cmd/iplist2rule/main.go b/utils/cmd/iplist2rule/main.go
index db49d1a..df3dbd1 100644
--- a/utils/cmd/iplist2rule/main.go
+++ b/utils/cmd/iplist2rule/main.go
@@ -90,14 +90,21 @@ func main() {
if err != nil {
log.Fatalf("can't create output file %q: %v", foutName, err)
}
- defer fout.Close()
- fmt.Fprintf(fout, "# Generated by %s on %s from %s\n\n", filepath.Base(os.Args[0]), time.Now().Format(time.RFC3339), blocklistURL)
+ if _, err := fmt.Fprintf(fout, "# Generated by %s on %s from %s\n\n", filepath.Base(os.Args[0]), time.Now().Format(time.RFC3339), blocklistURL); err != nil {
+ log.Fatalf("can't write signature line: %v", err)
+ }
data, err := yaml.Marshal([]*Rule{result})
if err != nil {
- log.Fatalf("can't marshal yaml")
+ log.Fatalf("can't marshal yaml: %v", err)
}
- fout.Write(data)
+ if _, err := fout.Write(data); err != nil {
+ log.Fatalf("can't write data: %v", err)
+ }
+
+ if err := fout.Close(); err != nil {
+ log.Fatalf("can't close file: %v", err)
+ }
}
diff --git a/utils/cmd/wazero-exec/main.go b/utils/cmd/wazero-exec/main.go
new file mode 100644
index 0000000..da87f1b
--- /dev/null
+++ b/utils/cmd/wazero-exec/main.go
@@ -0,0 +1,108 @@
+package main
+
+import (
+ "context"
+ "errors"
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/tetratelabs/wazero"
+ "github.com/tetratelabs/wazero/api"
+ "github.com/tetratelabs/wazero/experimental"
+ "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
+ "github.com/tetratelabs/wazero/sys"
+)
+
+func defaultCacheDir() string {
+ dir, err := os.UserCacheDir()
+ if err != nil {
+ path := filepath.Join(os.Getenv("HOME"), ".cache", "techaro.lol", "anubis", "wazero-exec")
+ _ = os.MkdirAll(path, 0755)
+ return path
+ }
+
+ path := filepath.Join(dir, "techaro.lol", "anubis", "wazero-exec")
+ _ = os.MkdirAll(path, 0755)
+ return path
+}
+
+var (
+ cacheDir = flag.String("cache-dir", defaultCacheDir(), "default compilation cache folder")
+)
+
+func main() {
+ flag.Parse()
+
+ if flag.NArg() == 0 {
+ fmt.Fprintf(os.Stderr, "usage: %s [args]\n\n", filepath.Base(os.Args[0]))
+ flag.Usage()
+ os.Exit(2)
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ if err := run(ctx, flag.Arg(0), flag.Args()); err != nil {
+ fmt.Fprintf(os.Stderr, "can't run program %s: %v\n", flag.Arg(0), err)
+
+ var exitErr *sys.ExitError
+ if errors.As(err, &exitErr) && exitErr.ExitCode() != 0 {
+ os.Exit(int(exitErr.ExitCode()))
+ }
+
+ os.Exit(1)
+ }
+}
+
+func run(ctx context.Context, fname string, args []string) error {
+ cache, err := wazero.NewCompilationCacheWithDir(*cacheDir)
+ if err != nil {
+ return fmt.Errorf("can't open cache folder %q: %w", *cacheDir, err)
+ }
+
+ cfg := wazero.NewRuntimeConfig().
+ WithCompilationCache(cache).
+ WithCoreFeatures(api.CoreFeaturesV2 | experimental.CoreFeaturesExceptionHandling | experimental.CoreFeaturesExtendedConst | experimental.CoreFeaturesTailCall)
+
+ runtime := wazero.NewRuntimeWithConfig(ctx, cfg)
+ wasi_snapshot_preview1.MustInstantiate(ctx, runtime)
+
+ bin, err := os.ReadFile(fname)
+ if err != nil {
+ return fmt.Errorf("can't read file %s: %w", fname, err)
+ }
+
+ compiled, err := runtime.CompileModule(ctx, bin)
+ if err != nil {
+ return fmt.Errorf("can't compile binary %s: %w", fname, err)
+ }
+
+ cwd, err := os.Getwd()
+ if err != nil {
+ return fmt.Errorf("[unexpected] can't get cwd: %w", err)
+ }
+
+ fsConfig := wazero.NewFSConfig().WithDirMount(cwd, "/")
+
+ config := wazero.NewModuleConfig().
+ WithStdin(os.Stdin).WithStdout(os.Stdout).WithStderr(os.Stderr).
+ WithArgs(args...).WithName(filepath.Base(fname)).WithFSConfig(fsConfig).
+ WithSysNanosleep().WithSysNanotime().WithSysWalltime()
+
+ for _, kp := range os.Environ() {
+ kv := strings.SplitN(kp, "=", 2)
+ config = config.WithEnv(kv[0], kv[1])
+ }
+
+ mod, err := runtime.InstantiateModule(ctx, compiled, config)
+ if err != nil {
+ return fmt.Errorf("can't instantiate module: %w", err)
+ }
+ if err := mod.Close(ctx); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/utils/wasm/wasm2js/README.md b/utils/wasm/wasm2js/README.md
new file mode 100644
index 0000000..182adad
--- /dev/null
+++ b/utils/wasm/wasm2js/README.md
@@ -0,0 +1,15 @@
+# Pre-built wasm2js binaries
+
+The existience of this folder is a bit of a crime. Let me elaborate.
+
+Anubis uses WebAssembly based checks so that it can have the proof of work run as _efficiently as possible_. This includes using the simd128 extension in WebAssembly so that clients take maximum possible advantage of their hardware. The goal of this is to make Anubis _go away as fast as it can_ so people don't see it for too long and complain.
+
+However, many "privacy browsers", iOS Lockdown Mode, and other "enhanced web privacy" configuration guides tell people to disable WebAssembly. This would mean that clients that can't/won't execute WebAssembly are de-facto blocked from the service Anubis protects.
+
+As a middle ground, the WebAssembly modules are compiled down to JavaScript a-la [Metal in The Birth and Death of JavaScript](https://www.destroyallsoftware.com/talks/the-birth-and-death-of-javascript). This will at least let the check logic run on client machines. It won't run efficiently as most of the configurations that disable WebAssembly also disable browser JIT engines, but it will _eventually_ finish.
+
+The catch that makes this folder need to exist is that the tool that's being used for this, [wasm2js from binaryen](https://github.com/WebAssembly/binaryen), is packaged in distro repositories. The downside of the distro packaging is that it is _woefully_ out of date compared to what is required to actually compile the WebAssembly to JavaScript. This leaves us in a bit of a pickle.
+
+The middle path here is to use WebAssembly to ship _the known working version_ of wasm2js in the git repo as well as the [build.sh](./build.sh) script used to build it. The build scripts will use this version of wasm2js as much as possible. These builds are known to be byte-for-byte reproducible as of [wasi-sdk v34.0-rc.2](https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-34-rc.2).
+
+Hopefully this will be robust enough to survive reality, but this is the kind of thing you only learn the efficacy of the hard way.
diff --git a/utils/wasm/wasm2js/build.sh b/utils/wasm/wasm2js/build.sh
new file mode 100755
index 0000000..1000faa
--- /dev/null
+++ b/utils/wasm/wasm2js/build.sh
@@ -0,0 +1,248 @@
+#!/usr/bin/env bash
+#
+# CW(Xe): Script was generated by Claude after I tried to do this manually and
+# gave up.
+#
+# Build binaryen tools (wasm2js, wasm-opt) as WASI preview 1 WebAssembly
+# modules. See the TOOLS array below to add or remove targets.
+#
+# Output: ./_.wasm
+# (default wasm2js_130.wasm, wasm-opt_130.wasm)
+#
+# Dependencies are fetched automatically if missing: wasi-sdk is downloaded
+# from its GitHub release and binaryen is git-cloned at the requested tag.
+# Pin versions with the WASI_SDK_VERSION and BINARYEN_VERSION env vars.
+#
+# How it works / notable decisions:
+#
+# * Toolchain: we use the wasi-sdk CMake toolchain file `wasi-sdk-p1.cmake`,
+# which targets `wasm32-wasip1` and points CMake at the bundled clang/lld.
+#
+# * Static binary: WASI has no dynamic linker, so libbinaryen is built as a
+# static archive (-DBUILD_SHARED_LIBS=OFF) and statically linked into the
+# final module. This is the only thing that links on WASI.
+#
+# * C++ exceptions: binaryen's parser and tools use `throw`, so we cannot
+# build with -fno-exceptions. wasi-sdk ships two libc++ flavors: the default
+# `noeh` (no exceptions) and an `eh` variant. Passing `-fwasm-exceptions`
+# makes the clang driver select the `eh` include/lib dirs. We also link
+# `-lunwind` to satisfy the `_Unwind_*` / exception-tag symbols.
+#
+# * EH encoding: by default LLVM emits the *legacy* wasm exception-handling
+# opcodes (`try`/`catch`), which modern runtimes (e.g. wasmtime >= ~45) no
+# longer accept. `-mllvm -wasm-use-legacy-eh=false` makes it emit the
+# standardized exnref-based EH (`try_table`) instead, so the module runs on
+# current runtimes with the exceptions proposal enabled.
+#
+# * Threads: binaryen calls find_package(Threads) and links pthread (wasi-libc
+# provides stubs). At runtime ThreadPool::getNumCores() returns 1 on wasip1,
+# so no threads are ever spawned and it runs single-threaded.
+#
+# * Reproducibility: the goal is a byte-for-byte identical module on any
+# machine. Ninja invokes clang with absolute source paths, so __FILE__
+# (used all over binaryen via WASM_UNREACHABLE) would otherwise bake the
+# build machine's checkout path into the module's data segments. We rewrite
+# that prefix to a stable token with -ffile-prefix-map so the output does
+# not depend on where the tree lives. Everything else feeding the module is
+# already pinned (wasi-sdk version, binaryen tag, compile/link flags), and
+# the wasm format carries no build timestamp, so the raw clang/lld output is
+# deterministic. We deliberately do NOT post-process with wasm-opt: its
+# availability and version vary per machine, which would defeat the
+# guarantee. Note this takes an explicit flag: clang's wasm driver runs
+# `wasm-opt -O3` on its own whenever a wasm-opt is on PATH and optimization
+# is on, so we pass --no-wasm-opt at link time to suppress it (see the
+# REPRO_LINK_FLAGS note below).
+#
+# * Clean build: cmake/ninja are incremental, so re-running over an existing
+# build tree only recompiles what changed and leaves stale object files
+# behind. If those objects were produced by an older revision of this script
+# (different flags), they leak into the final module and the output is no
+# longer a function of the current inputs alone. We therefore wipe the build
+# directory before configuring so every run is a full, flag-consistent build
+# from scratch.
+#
+# * Stripping: the linker emits ~2.5 MB of DWARF (.debug_*), a multi-megabyte
+# `name` section, and a `producers` section that records the exact clang
+# revision. The producers string in particular would tie the bytes to one
+# wasi-sdk build, and the debug/name sections only bloat a module we run
+# headless. We strip all of them with the wasi-sdk's OWN `llvm-strip`
+# (--strip-all), which is pinned by WASI_SDK_VERSION just like the compiler,
+# so the strip step is as deterministic as the rest of the toolchain. This
+# is NOT wasm-opt: llvm-strip ships in the sdk we already pin, so it adds no
+# new floating dependency. `target_features` is intentionally preserved --
+# it advertises the proposals (exceptions, etc.) the module needs and
+# --strip-all keeps it.
+#
+# * ASLR: the wasi-sdk clang that compiles binaryen has address-sensitive
+# ordering in its WebAssembly exception-handling codegen -- pointer values
+# leak into the iteration order of a few passes, which shuffles a handful of
+# try_table basic blocks and their branch labels. With address-space layout
+# randomization on, the same source compiles to ~29 differing bytes from one
+# run to the next. We pin pointer layout by re-exec'ing the whole build under
+# `setarch -R` (ADDR_NO_RANDOMIZE), which is inherited by cmake/ninja/clang.
+# This is Linux-only; see the re-exec guard below.
+#
+# CAVEAT -- same architecture only. setarch fixes ASLR within one host, but
+# the underlying ordering is keyed on raw pointer VALUES (clang's
+# WebAssemblyCFGStackify iterates DenseMap in
+# pointer-hash order). The x86_64 and arm64 wasi-sdk clang binaries hand out
+# different pointers, so the two arches still produce ~29 differing bytes (a
+# few reordered try_table blocks) even though every section is otherwise
+# identical. This is an upstream LLVM determinism bug, not something we can
+# pin from here; fixing it needs LLVM to sort those EH pads by block number.
+# The committed modules are the x86_64 build; CI records the expected
+# checksums for both architectures (shasums.x86_64 / shasums.arm64) and
+# accepts a match against either, so each runner verifies its own arch.
+#
+# To run the resulting module, the host runtime must enable the exceptions
+# proposal and grant filesystem access, e.g.:
+#
+# wasmtime run -W exceptions=y --dir . ./wasm2js_130.wasm input.wasm -o out.js
+#
+set -euo pipefail
+
+# Pin any timestamp a tool in the chain might embed. Nothing in the current
+# toolchain consumes this (the wasm format has no build-time field and we emit
+# no debug info), but exporting it keeps the build deterministic if a future
+# wasi-sdk or binaryen starts honoring it. Fixed constant, not "now".
+export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-1700000000}"
+
+# Resolve the directory this script lives in so it works from anywhere.
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+cd "$SCRIPT_DIR"
+
+# --- Versions (override via the environment) -------------------------------
+# wasi-sdk: full release version, e.g. 33.0. The GitHub release tag uses only
+# the major component (wasi-sdk-33) while the tarball uses the full version.
+WASI_SDK_VERSION="${WASI_SDK_VERSION:-34.0}"
+# binaryen: the numeric release, used both for the git tag (version_130) and
+# the output filename (wasm2js_130.wasm).
+BINARYEN_VERSION="${BINARYEN_VERSION:-130}"
+
+# Map the host's uname onto wasi-sdk's - asset naming.
+case "$(uname -s)" in
+Darwin) WASI_SDK_OS="macos" ;;
+Linux) WASI_SDK_OS="linux" ;;
+*)
+ echo "error: unsupported OS $(uname -s); set WASI_SDK to a prebuilt sdk" >&2
+ exit 1
+ ;;
+esac
+case "$(uname -m)" in
+x86_64 | amd64) WASI_SDK_ARCH="x86_64" ;;
+arm64 | aarch64) WASI_SDK_ARCH="arm64" ;;
+*)
+ echo "error: unsupported arch $(uname -m); set WASI_SDK to a prebuilt sdk" >&2
+ exit 1
+ ;;
+esac
+
+WASI_SDK_MAJOR="${WASI_SDK_VERSION%%.*}"
+WASI_SDK_DIRNAME="wasi-sdk-${WASI_SDK_VERSION}-${WASI_SDK_ARCH}-${WASI_SDK_OS}"
+WASI_SDK_URL="https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_SDK_MAJOR}/${WASI_SDK_DIRNAME}.tar.gz"
+BINARYEN_TAG="version_${BINARYEN_VERSION}"
+BINARYEN_URL="https://github.com/WebAssembly/binaryen.git"
+
+# All build inputs live under ./var; outputs land in the script directory.
+VAR_DIR="$SCRIPT_DIR/var"
+
+WASI_SDK="${WASI_SDK:-$VAR_DIR/$WASI_SDK_DIRNAME}"
+BINARYEN_SRC="$VAR_DIR/binaryen"
+BUILD_DIR="$BINARYEN_SRC/build-wasi"
+
+TOOLCHAIN="$WASI_SDK/share/cmake/wasi-sdk-p1.cmake"
+# llvm-strip from the same pinned wasi-sdk; used to drop debug/name/producers.
+STRIP="$WASI_SDK/bin/llvm-strip"
+
+mkdir -p "$VAR_DIR"
+
+# --- Fetch wasi-sdk ---------------------------------------------------------
+if [[ ! -f "$TOOLCHAIN" ]]; then
+ echo ">> Downloading wasi-sdk $WASI_SDK_VERSION"
+ echo " $WASI_SDK_URL"
+ tmp_tarball="$(mktemp "$VAR_DIR/.wasi-sdk.XXXXXX.tar.gz")"
+ trap 'rm -f "$tmp_tarball"' EXIT
+ curl -fL --retry 3 -o "$tmp_tarball" "$WASI_SDK_URL"
+ # The tarball unpacks to $WASI_SDK_DIRNAME/ in the destination directory.
+ tar -xzf "$tmp_tarball" -C "$VAR_DIR"
+ rm -f "$tmp_tarball"
+ trap - EXIT
+fi
+
+if [[ ! -f "$TOOLCHAIN" ]]; then
+ echo "error: wasi-sdk toolchain not found at $TOOLCHAIN" >&2
+ echo " set WASI_SDK to the wasi-sdk install prefix" >&2
+ exit 1
+fi
+
+# --- Fetch binaryen ---------------------------------------------------------
+if [[ ! -d "$BINARYEN_SRC/.git" ]]; then
+ echo ">> Cloning binaryen at $BINARYEN_TAG"
+ git clone --depth 1 --branch "$BINARYEN_TAG" --recurse-submodules \
+ "$BINARYEN_URL" "$BINARYEN_SRC"
+fi
+
+# Flags that enable standardized wasm exception handling against wasi-sdk's
+# `eh` libc++ variant. Needed at both compile and link time.
+EH_COMPILE_FLAGS="-fwasm-exceptions -mllvm -wasm-use-legacy-eh=false"
+EH_LINK_FLAGS="-fwasm-exceptions -lunwind"
+
+# Reproducibility: strip the absolute checkout path out of every __FILE__ so the
+# module is identical regardless of where binaryen was cloned. BUILD_DIR lives
+# under BINARYEN_SRC, so generated-source paths are normalized by the same map.
+REPRO_COMPILE_FLAGS="-ffile-prefix-map=$BINARYEN_SRC=."
+
+# Reproducibility: clang's wasm driver silently runs `wasm-opt -O3` on the
+# linked module whenever an optimization level is set (Release => -O3) AND a
+# wasm-opt happens to be on PATH. That makes the bytes depend on whichever
+# wasm-opt is installed -- and an old one (e.g. the binaryen 108 that ships in
+# some distros) cannot even parse the exnref exception handling we emit, so the
+# link dies with "[parse exception: Bad type form -1] / error parsing wasm".
+# Disable the auto-pass so the module is purely the linker's deterministic
+# output (this is what the wasm-opt note in the header is really about).
+REPRO_LINK_FLAGS="--no-wasm-opt"
+
+# Reproducibility: start from a pristine build tree. cmake/ninja only rebuild
+# changed objects, so a stale tree from an earlier (differently-flagged) run
+# would silently contaminate the output. Wiping it guarantees the module is a
+# function of the current inputs alone.
+echo ">> Wiping build directory for a clean build"
+rm -rf "$BUILD_DIR"
+
+echo ">> Configuring (wasm32-wasip1, static, exceptions=exnref)"
+cmake -S "$BINARYEN_SRC" -B "$BUILD_DIR" -G Ninja \
+ -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" \
+ -DWASI_SDK_PREFIX="$WASI_SDK" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DBUILD_TESTS=OFF \
+ -DBUILD_SHARED_LIBS=OFF \
+ -DENABLE_WERROR=OFF \
+ -DINSTALL_LIBS=OFF \
+ -DCMAKE_C_FLAGS="$EH_COMPILE_FLAGS $REPRO_COMPILE_FLAGS" \
+ -DCMAKE_CXX_FLAGS="$EH_COMPILE_FLAGS $REPRO_COMPILE_FLAGS" \
+ -DCMAKE_EXE_LINKER_FLAGS="$EH_LINK_FLAGS $REPRO_LINK_FLAGS"
+
+# Tools to build, as binaryen CMake target names. Each is emitted to
+# ./_.wasm.
+TOOLS=(wasm2js wasm-opt)
+
+echo ">> Building: ${TOOLS[*]}"
+cmake --build "$BUILD_DIR" --target "${TOOLS[@]}"
+
+# Install the stripped linker output. We intentionally skip any wasm-opt pass:
+# optimizing here would make the result depend on whichever wasm-opt happens to
+# be installed, which is exactly the non-determinism we are eliminating. The
+# only post-processing is llvm-strip from the pinned wasi-sdk (see header note);
+# combined with the pinned toolchain and the -ffile-prefix-map applied above,
+# the module is reproducible.
+BUILD_BIN="$BUILD_DIR/bin"
+
+for tool in "${TOOLS[@]}"; do
+ out="./${tool}_${BINARYEN_VERSION}.wasm"
+ echo ">> Installing $tool -> $out (stripped)"
+ "$STRIP" --strip-all "$BUILD_BIN/$tool" -o "$out"
+ ls -l "$out" | awk '{print " size:", $5, "bytes"}'
+done
+
+echo ">> Done. Outputs in $SCRIPT_DIR:"
+ls -1 ./*_"${BINARYEN_VERSION}".wasm
diff --git a/utils/wasm/wasm2js/var/.gitignore b/utils/wasm/wasm2js/var/.gitignore
new file mode 100644
index 0000000..c96a04f
--- /dev/null
+++ b/utils/wasm/wasm2js/var/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
\ No newline at end of file
diff --git a/utils/wasm/wasm2js/wasm-opt_130.wasm b/utils/wasm/wasm2js/wasm-opt_130.wasm
new file mode 100755
index 0000000..33b5ad9
Binary files /dev/null and b/utils/wasm/wasm2js/wasm-opt_130.wasm differ
diff --git a/utils/wasm/wasm2js/wasm2js_130.wasm b/utils/wasm/wasm2js/wasm2js_130.wasm
new file mode 100755
index 0000000..1eb7772
Binary files /dev/null and b/utils/wasm/wasm2js/wasm2js_130.wasm differ
diff --git a/wasm/anubis/Cargo.toml b/wasm/anubis/Cargo.toml
new file mode 100644
index 0000000..e55fb21
--- /dev/null
+++ b/wasm/anubis/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "anubis"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+wee_alloc = "0.4"
diff --git a/wasm/anubis/src/lib.rs b/wasm/anubis/src/lib.rs
new file mode 100644
index 0000000..710492f
--- /dev/null
+++ b/wasm/anubis/src/lib.rs
@@ -0,0 +1,60 @@
+use std::sync::{LazyLock, Mutex};
+
+extern crate wee_alloc;
+
+#[global_allocator]
+static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
+
+#[cfg(target_arch = "wasm32")]
+mod hostimport {
+ use crate::{DATA_BUFFER, DATA_LENGTH};
+
+ #[link(wasm_import_module = "anubis")]
+ unsafe extern "C" {
+ /// The runtime expects this function to be defined. It is called whenever the Anubis check
+ /// worker processes about 1024 hashes. This can be a no-op if you want.
+ fn anubis_update_nonce(nonce: u32);
+ }
+
+ /// Safe wrapper to `anubis_update_nonce`.
+ pub fn update_nonce(nonce: u32) {
+ unsafe {
+ anubis_update_nonce(nonce);
+ }
+ }
+
+ #[unsafe(no_mangle)]
+ pub extern "C" fn data_ptr() -> *const u8 {
+ let challenge = &DATA_BUFFER;
+ challenge.as_ptr()
+ }
+
+ #[unsafe(no_mangle)]
+ pub extern "C" fn set_data_length(len: u32) {
+ let mut data_length = DATA_LENGTH.lock().unwrap();
+ *data_length = len as usize;
+ }
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+mod hostimport {
+ pub fn update_nonce(_nonce: u32) {
+ // This is intentionally blank
+ }
+}
+
+/// The data buffer is a bit weird in that it doesn't have an explicit length as it can
+/// and will change depending on the challenge input that was sent by the server.
+/// However, it can only fit 4096 bytes of data (one amd64 machine page). This is
+/// slightly overkill for the purposes of an Anubis check, but it's fine to assume
+/// that the browser can afford this much ram usage.
+///
+/// Callers should fetch the base data pointer, write up to 4096 bytes, and then
+/// `set_data_length` the number of bytes they have written
+///
+/// This is also functionally a write-only buffer, so it doesn't really matter that
+/// the length of this buffer isn't exposed.
+pub static DATA_BUFFER: LazyLock<[u8; 4096]> = LazyLock::new(|| [0; 4096]);
+pub static DATA_LENGTH: LazyLock> = LazyLock::new(|| Mutex::new(0));
+
+pub use hostimport::update_nonce;
diff --git a/wasm/pow/argon2id/Cargo.toml b/wasm/pow/argon2id/Cargo.toml
new file mode 100644
index 0000000..b96b293
--- /dev/null
+++ b/wasm/pow/argon2id/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "argon2id"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+argon2 = "0.5"
+
+anubis = { path = "../../anubis" }
+
+[lints.clippy]
+nursery = { level = "warn", priority = -1 }
+pedantic = { level = "warn", priority = -1 }
+unwrap_used = "warn"
+uninlined_format_args = "allow"
+missing_panics_doc = "allow"
+missing_errors_doc = "allow"
+cognitive_complexity = "allow"
diff --git a/wasm/pow/argon2id/src/lib.rs b/wasm/pow/argon2id/src/lib.rs
new file mode 100644
index 0000000..4eb6e9c
--- /dev/null
+++ b/wasm/pow/argon2id/src/lib.rs
@@ -0,0 +1,171 @@
+use anubis::{DATA_BUFFER, DATA_LENGTH, update_nonce};
+use argon2::Argon2;
+use std::sync::{LazyLock, Mutex};
+
+/// Argon2id result and verification hashes are 32 bytes (256 bits). These are stored in
+/// static buffers due to the fact that you cannot easily pass data from host space to
+/// WebAssembly space.
+pub static RESULT_HASH: LazyLock> = LazyLock::new(|| Mutex::new([0; 32]));
+
+pub static VERIFICATION_HASH: LazyLock> = LazyLock::new(|| Mutex::new([0; 32]));
+
+/// Core validation function. Compare each bit in the hash by progressively masking bits until
+/// some are found to not be matching.
+///
+/// There are probably more clever ways to do this, likely involving lookup tables or something
+/// really fun like that. However in my testing this lets us get up to 200 kilohashes per second
+/// on my Ryzen 7950x3D, up from about 50 kilohashes per second in JavaScript.
+fn validate(hash: &[u8], difficulty: u32) -> bool {
+ let mut remaining = difficulty;
+ for &byte in hash {
+ // If we're out of bits to check, exit. This is all good.
+ if remaining == 0 {
+ break;
+ }
+
+ // If there are more than 8 bits remaining, the entire byte should be a
+ // zero. This fast-path compares the byte to 0 and if it matches, subtract
+ // 8 bits.
+ if remaining >= 8 {
+ if byte != 0 {
+ return false;
+ }
+ remaining -= 8;
+ } else {
+ // Otherwise mask off individual bits and check against them.
+ let mask = 0xFF << (8 - remaining);
+ if (byte & mask) != 0 {
+ return false;
+ }
+ remaining = 0;
+ }
+ }
+ true
+}
+
+/// Computes the Argon2id hash for the given nonce.
+///
+/// The challenge bytes are used directly as the Argon2id password and the nonce is used as
+/// the salt, rather than hashing a hex-formatted `challenge || nonce` string as the
+/// JavaScript implementation does. Operating on the raw challenge bytes avoids the
+/// formatting round-trip.
+///
+/// The nonce is also randomly encoded in either big or little endian depending on the last
+/// byte of the data buffer in an effort to make it more annoying to automate with GPUs.
+fn compute_hash(nonce: u32) -> [u8; 32] {
+ let data = &DATA_BUFFER;
+ let data_len = *DATA_LENGTH.lock().unwrap();
+ let data_slice: &[u8] = &data[..data_len];
+ let use_le = data_slice.last().copied().unwrap_or(0) >= 128;
+ let mut result = [0u8; 32];
+
+ let nonce = nonce as u64;
+
+ let nonce = if use_le {
+ nonce.to_le_bytes()
+ } else {
+ nonce.to_be_bytes()
+ };
+
+ let argon2 = Argon2::default();
+ argon2
+ .hash_password_into(&data_slice, &nonce, &mut result)
+ .unwrap();
+ result
+}
+
+/// This function is the main entrypoint for the Anubis proof of work implementation.
+///
+/// This expects `DATA_BUFFER` to be prepopulated with the challenge value as "raw bytes".
+/// The definition of what goes in the data buffer is an exercise for the implementor, but
+/// for Argon2id we store the challenge as "raw bytes". The data buffer is intentionally
+/// oversized so that the challenge value can be expanded in the future.
+///
+/// `difficulty` is the number of leading bits that must match `0` in order for the
+/// challenge to be successfully passed. This will be validated by the server.
+///
+/// `initial_nonce` is the initial value of the nonce (number used once). This nonce will be
+/// appended to the challenge value in order to find a hash matching the specified
+/// difficulty.
+///
+/// `iterand` (noun form of iterate) is the amount that the nonce should be increased by
+/// every iteration of the proof of work loop. This will vary by how many threads are
+/// running the proof-of-work check, and also functions as a thread ID. This prevents
+/// wasting CPU time retrying a hash+nonce pair that likely won't work.
+#[unsafe(no_mangle)]
+pub extern "C" fn anubis_work(difficulty: u32, initial_nonce: u32, iterand: u32) -> u32 {
+ let mut nonce = initial_nonce;
+
+ loop {
+ let hash = compute_hash(nonce);
+
+ if validate(&hash, difficulty) {
+ // If the challenge worked, copy the bytes into `RESULT_HASH` so the runtime
+ // can pick it up.
+ let mut result = RESULT_HASH.lock().unwrap();
+ result.copy_from_slice(&hash);
+ return nonce;
+ }
+
+ let old_nonce = nonce;
+ nonce = nonce.wrapping_add(iterand);
+
+ // Report progress each time the search crosses into a new 1024-value window of the
+ // nonce space, i.e. roughly every 1024 nonce values. The reported nonce approximates
+ // the total work done across all worker threads, which the client turns into a
+ // progress bar and hashrate. Comparing the shifted window (rather than the original
+ // `nonce > old_nonce + 1023`) reports correctly for any `iterand` and stays correct
+ // across the u32 wraparound. (Only the nonce-0 worker's callback is live; the caller
+ // silences the rest.)
+ if (nonce >> 10) != (old_nonce >> 10) {
+ update_nonce(nonce);
+ }
+ }
+}
+
+/// This function is called by the server in order to validate a proof-of-work challenge.
+/// This expects `DATA_BUFFER` to be set to the challenge value and `VERIFICATION_HASH` to
+/// be set to the "raw bytes" of the SHA-256 hash that the client calculated.
+///
+/// If everything is good, it returns true. Otherwise, it returns false.
+///
+/// XXX(Xe): this could probably return an error code for what step fails, but this is fine
+/// for now.
+#[unsafe(no_mangle)]
+pub extern "C" fn anubis_validate(nonce: u32, difficulty: u32) -> bool {
+ let computed = compute_hash(nonce);
+ let valid = validate(&computed, difficulty);
+ if !valid {
+ return false;
+ }
+
+ let verification = VERIFICATION_HASH.lock().unwrap();
+ computed == *verification
+}
+
+// These functions exist to give pointers and lengths to the runtime around the Anubis
+// checks, this allows JavaScript and Go to safely manipulate the memory layout that Rust
+// has statically allocated at compile time without having to assume how the Rust compiler
+// is going to lay it out.
+
+#[unsafe(no_mangle)]
+pub extern "C" fn result_hash_ptr() -> *const u8 {
+ let challenge = RESULT_HASH.lock().unwrap();
+ challenge.as_ptr()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn result_hash_size() -> usize {
+ RESULT_HASH.lock().unwrap().len()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn verification_hash_ptr() -> *const u8 {
+ let verification = VERIFICATION_HASH.lock().unwrap();
+ verification.as_ptr()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn verification_hash_size() -> usize {
+ VERIFICATION_HASH.lock().unwrap().len()
+}
diff --git a/wasm/pow/hashx/Cargo.toml b/wasm/pow/hashx/Cargo.toml
new file mode 100644
index 0000000..4459c38
--- /dev/null
+++ b/wasm/pow/hashx/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "hashx"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+equix = "0.6"
+hashx = "0.8"
+
+anubis = { path = "../../anubis" }
+
+[lints.clippy]
+nursery = { level = "warn", priority = -1 }
+pedantic = { level = "warn", priority = -1 }
+unwrap_used = "warn"
+uninlined_format_args = "allow"
+missing_panics_doc = "allow"
+missing_errors_doc = "allow"
+cognitive_complexity = "allow"
diff --git a/wasm/pow/hashx/src/lib.rs b/wasm/pow/hashx/src/lib.rs
new file mode 100644
index 0000000..a256e4f
--- /dev/null
+++ b/wasm/pow/hashx/src/lib.rs
@@ -0,0 +1,172 @@
+use anubis::{DATA_BUFFER, DATA_LENGTH, update_nonce};
+use hashx::HashX;
+use std::sync::{LazyLock, Mutex};
+
+/// HashX result and verification hashes are 32 bytes (256 bits). These are stored in static
+/// buffers due to the fact that you cannot easily pass data from host space to WebAssembly
+/// space.
+pub static RESULT_HASH: LazyLock> = LazyLock::new(|| Mutex::new([0; 32]));
+
+pub static VERIFICATION_HASH: LazyLock> = LazyLock::new(|| Mutex::new([0; 32]));
+
+/// Core validation function. Compare each bit in the hash by progressively masking bits until
+/// some are found to not be matching.
+///
+/// There are probably more clever ways to do this, likely involving lookup tables or something
+/// really fun like that. However in my testing this lets us get up to 200 kilohashes per second
+/// on my Ryzen 7950x3D, up from about 50 kilohashes per second in JavaScript.
+fn validate(hash: &[u8], difficulty: u32) -> bool {
+ let mut remaining = difficulty;
+ for &byte in hash {
+ // If we're out of bits to check, exit. This is all good.
+ if remaining == 0 {
+ break;
+ }
+
+ // If there are more than 8 bits remaining, the entire byte should be a
+ // zero. This fast-path compares the byte to 0 and if it matches, subtract
+ // 8 bits.
+ if remaining >= 8 {
+ if byte != 0 {
+ return false;
+ }
+ remaining -= 8;
+ } else {
+ // Otherwise mask off individual bits and check against them.
+ let mask = 0xFF << (8 - remaining);
+ if (byte & mask) != 0 {
+ return false;
+ }
+ remaining = 0;
+ }
+ }
+ true
+}
+
+/// Build a `HashX` instance for the current challenge.
+///
+/// HashX rejects a small fraction of seeds (`Error::ProgramConstraints`). Rather than trap
+/// on those, derive a usable instance deterministically: the overwhelmingly common case is
+/// that the challenge bytes are accepted as-is, but if they are rejected we append an
+/// incrementing little-endian counter to the challenge until `HashX::new` accepts the seed.
+/// The client and server run this identical code, so they always agree on which seed ā and
+/// therefore which program ā is in use. The probability of needing even one retry is well
+/// under a percent, so the common path is unchanged on the wire.
+fn make_hashx() -> HashX {
+ let data = &DATA_BUFFER;
+ let data_len = *DATA_LENGTH.lock().unwrap();
+ let data_slice: &[u8] = &data[..data_len];
+
+ if let Ok(h) = HashX::new(data_slice) {
+ return h;
+ }
+
+ let mut seed = Vec::with_capacity(data_slice.len() + 4);
+ let mut counter: u32 = 0;
+ loop {
+ seed.clear();
+ seed.extend_from_slice(data_slice);
+ seed.extend_from_slice(&counter.to_le_bytes());
+ if let Ok(h) = HashX::new(&seed) {
+ return h;
+ }
+ counter = counter.wrapping_add(1);
+ }
+}
+
+/// This function is the main entrypoint for the Anubis proof of work implementation.
+///
+/// This expects `DATA_BUFFER` to be prepopulated with the challenge value as "raw bytes".
+/// The definition of what goes in the data buffer is an exercise for the implementor, but
+/// for SHA-256 we store the hash as "raw bytes". The data buffer is intentionally oversized
+/// so that the challenge value can be expanded in the future.
+///
+/// `difficulty` is the number of leading bits that must match `0` in order for the
+/// challenge to be successfully passed. This will be validated by the server.
+///
+/// `initial_nonce` is the initial value of the nonce (number used once). This nonce will be
+/// appended to the challenge value in order to find a hash matching the specified
+/// difficulty.
+///
+/// `iterand` (noun form of iterate) is the amount that the nonce should be increased by
+/// every iteration of the proof of work loop. This will vary by how many threads are
+/// running the proof-of-work check, and also functions as a thread ID. This prevents
+/// wasting CPU time retrying a hash+nonce pair that likely won't work.
+#[unsafe(no_mangle)]
+pub extern "C" fn anubis_work(difficulty: u32, initial_nonce: u32, iterand: u32) -> u32 {
+ let h = make_hashx();
+ let mut nonce: u32 = initial_nonce;
+
+ loop {
+ let hash = h.hash_to_bytes(nonce as u64);
+
+ if validate(&hash, difficulty) {
+ // If the challenge worked, copy the bytes into `RESULT_HASH` so the runtime
+ // can pick it up.
+ let mut result = RESULT_HASH.lock().unwrap();
+ result.copy_from_slice(&hash);
+ return nonce;
+ }
+
+ let old_nonce = nonce;
+ nonce = nonce.wrapping_add(iterand);
+
+ // Report progress each time the search crosses into a new 1024-value window of the
+ // nonce space, i.e. roughly every 1024 nonce values. The reported nonce approximates
+ // the total work done across all worker threads, which the client turns into a
+ // progress bar and hashrate. Comparing the shifted window reports correctly for any
+ // `iterand` and stays correct across the u32 wraparound. (Only the nonce-0 worker's
+ // callback is live; the caller silences the rest.)
+ if (nonce >> 10) != (old_nonce >> 10) {
+ update_nonce(nonce);
+ }
+ }
+}
+
+/// This function is called by the server in order to validate a proof-of-work challenge.
+/// This expects `DATA_BUFFER` to be set to the challenge value and `VERIFICATION_HASH` to
+/// be set to the "raw bytes" of the SHA-256 hash that the client calculated.
+///
+/// If everything is good, it returns true. Otherwise, it returns false.
+///
+/// XXX(Xe): this could probably return an error code for what step fails, but this is fine
+/// for now.
+#[unsafe(no_mangle)]
+pub extern "C" fn anubis_validate(nonce: u32, difficulty: u32) -> bool {
+ let h = make_hashx();
+ let computed = h.hash_to_bytes(nonce as u64);
+ let valid = validate(&computed, difficulty);
+ if !valid {
+ return false;
+ }
+
+ let verification = VERIFICATION_HASH.lock().unwrap();
+ computed == *verification
+}
+
+// These functions exist to give pointers and lengths to the runtime around the Anubis
+// checks, this allows JavaScript and Go to safely manipulate the memory layout that Rust
+// has statically allocated at compile time without having to assume how the Rust compiler
+// is going to lay it out.
+
+#[unsafe(no_mangle)]
+pub extern "C" fn result_hash_ptr() -> *const u8 {
+ let challenge = RESULT_HASH.lock().unwrap();
+ challenge.as_ptr()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn result_hash_size() -> usize {
+ RESULT_HASH.lock().unwrap().len()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn verification_hash_ptr() -> *const u8 {
+ let verification = VERIFICATION_HASH.lock().unwrap();
+ verification.as_ptr()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn verification_hash_size() -> usize {
+ VERIFICATION_HASH.lock().unwrap().len()
+}
diff --git a/wasm/pow/sha256/Cargo.toml b/wasm/pow/sha256/Cargo.toml
new file mode 100644
index 0000000..fcc8d18
--- /dev/null
+++ b/wasm/pow/sha256/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "sha256"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+sha2 = "0.11"
+
+anubis = { path = "../../anubis" }
+
+[lints.clippy]
+nursery = { level = "warn", priority = -1 }
+pedantic = { level = "warn", priority = -1 }
+unwrap_used = "warn"
+uninlined_format_args = "allow"
+missing_panics_doc = "allow"
+missing_errors_doc = "allow"
+cognitive_complexity = "allow"
diff --git a/wasm/pow/sha256/src/lib.rs b/wasm/pow/sha256/src/lib.rs
new file mode 100644
index 0000000..e123140
--- /dev/null
+++ b/wasm/pow/sha256/src/lib.rs
@@ -0,0 +1,168 @@
+use anubis::{DATA_BUFFER, DATA_LENGTH, update_nonce};
+use sha2::{Digest, Sha256};
+use std::sync::{LazyLock, Mutex};
+
+/// SHA-256 hashes are 32 bytes (256 bits). These are stored in static buffers due to the
+/// fact that you cannot easily pass data from host space to WebAssembly space.
+pub static RESULT_HASH: LazyLock> = LazyLock::new(|| Mutex::new([0; 32]));
+
+pub static VERIFICATION_HASH: LazyLock> = LazyLock::new(|| Mutex::new([0; 32]));
+
+/// Core validation function. Compare each bit in the hash by progressively masking bits until
+/// some are found to not be matching.
+///
+/// There are probably more clever ways to do this, likely involving lookup tables or something
+/// really fun like that. However in my testing this lets us get up to 200 kilohashes per second
+/// on my Ryzen 7950x3D, up from about 50 kilohashes per second in JavaScript.
+fn validate(hash: &[u8], difficulty: u32) -> bool {
+ let mut remaining = difficulty;
+ for &byte in hash {
+ // If we're out of bits to check, exit. This is all good.
+ if remaining == 0 {
+ break;
+ }
+
+ // If there are more than 8 bits remaining, the entire byte should be a
+ // zero. This fast-path compares the byte to 0 and if it matches, subtract
+ // 8 bits.
+ if remaining >= 8 {
+ if byte != 0 {
+ return false;
+ }
+ remaining -= 8;
+ } else {
+ // Otherwise mask off individual bits and check against them.
+ let mask = 0xFF << (8 - remaining);
+ if (byte & mask) != 0 {
+ return false;
+ }
+ remaining = 0;
+ }
+ }
+ true
+}
+
+/// Computes hash for given nonce.
+///
+/// This differs from the JavaScript implementations by constructing the hash differently. In
+/// JavaScript implementations, the SHA-256 input is the result of appending the nonce as an
+/// integer to the hex-formatted challenge, eg:
+///
+/// sha256(`${challenge}${nonce}`);
+///
+/// This **does work**, however I think that this can be done a bit better by operating on the
+/// challenge bytes _directly_ and treating the nonce as a salt.
+///
+/// The nonce is also randomly encoded in either big or little endian depending on the last
+/// byte of the data buffer in an effort to make it more annoying to automate with GPUs.
+fn compute_hash(nonce: u32) -> [u8; 32] {
+ let data = &DATA_BUFFER;
+ let data_len = *DATA_LENGTH.lock().unwrap();
+ let data_slice: &[u8] = &data[..data_len];
+ let use_le = data_slice.last().copied().unwrap_or(0) >= 128;
+
+ let mut hasher = Sha256::new();
+ hasher.update(data_slice);
+ hasher.update(if use_le {
+ nonce.to_le_bytes()
+ } else {
+ nonce.to_be_bytes()
+ });
+ hasher.finalize().into()
+}
+
+/// This function is the main entrypoint for the Anubis proof of work implementation.
+///
+/// This expects `DATA_BUFFER` to be prepopulated with the challenge value as "raw bytes".
+/// The definition of what goes in the data buffer is an exercise for the implementor, but
+/// for SHA-256 we store the hash as "raw bytes". The data buffer is intentionally oversized
+/// so that the challenge value can be expanded in the future.
+///
+/// `difficulty` is the number of leading bits that must match `0` in order for the
+/// challenge to be successfully passed. This will be validated by the server.
+///
+/// `initial_nonce` is the initial value of the nonce (number used once). This nonce will be
+/// appended to the challenge value in order to find a hash matching the specified
+/// difficulty.
+///
+/// `iterand` (noun form of iterate) is the amount that the nonce should be increased by
+/// every iteration of the proof of work loop. This will vary by how many threads are
+/// running the proof-of-work check, and also functions as a thread ID. This prevents
+/// wasting CPU time retrying a hash+nonce pair that likely won't work.
+#[unsafe(no_mangle)]
+pub extern "C" fn anubis_work(difficulty: u32, initial_nonce: u32, iterand: u32) -> u32 {
+ let mut nonce = initial_nonce;
+
+ loop {
+ let hash = compute_hash(nonce);
+
+ if validate(&hash, difficulty) {
+ // If the challenge worked, copy the bytes into `RESULT_HASH` so the runtime
+ // can pick it up.
+ let mut result = RESULT_HASH.lock().unwrap();
+ result.copy_from_slice(&hash);
+ return nonce;
+ }
+
+ let old_nonce = nonce;
+ nonce = nonce.wrapping_add(iterand);
+
+ // Report progress each time the search crosses into a new 1024-value window of the
+ // nonce space, i.e. roughly every 1024 nonce values. The reported nonce approximates
+ // the total work done across all worker threads, which the client turns into a
+ // progress bar and hashrate. Comparing the shifted window (rather than the original
+ // `nonce > old_nonce + 1023`) reports correctly for any `iterand` and stays correct
+ // across the u32 wraparound. (Only the nonce-0 worker's callback is live; the caller
+ // silences the rest.)
+ if (nonce >> 10) != (old_nonce >> 10) {
+ update_nonce(nonce);
+ }
+ }
+}
+
+/// This function is called by the server in order to validate a proof-of-work challenge.
+/// This expects `DATA_BUFFER` to be set to the challenge value and `VERIFICATION_HASH` to
+/// be set to the "raw bytes" of the SHA-256 hash that the client calculated.
+///
+/// If everything is good, it returns true. Otherwise, it returns false.
+///
+/// XXX(Xe): this could probably return an error code for what step fails, but this is fine
+/// for now.
+#[unsafe(no_mangle)]
+pub extern "C" fn anubis_validate(nonce: u32, difficulty: u32) -> bool {
+ let computed = compute_hash(nonce);
+ let valid = validate(&computed, difficulty);
+ if !valid {
+ return false;
+ }
+
+ let verification = VERIFICATION_HASH.lock().unwrap();
+ computed == *verification
+}
+
+// These functions exist to give pointers and lengths to the runtime around the Anubis
+// checks, this allows JavaScript and Go to safely manipulate the memory layout that Rust
+// has statically allocated at compile time without having to assume how the Rust compiler
+// is going to lay it out.
+
+#[unsafe(no_mangle)]
+pub extern "C" fn result_hash_ptr() -> *const u8 {
+ let challenge = RESULT_HASH.lock().unwrap();
+ challenge.as_ptr()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn result_hash_size() -> usize {
+ RESULT_HASH.lock().unwrap().len()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn verification_hash_ptr() -> *const u8 {
+ let verification = VERIFICATION_HASH.lock().unwrap();
+ verification.as_ptr()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn verification_hash_size() -> usize {
+ VERIFICATION_HASH.lock().unwrap().len()
+}
diff --git a/wasm/scripts/build_wasm.sh b/wasm/scripts/build_wasm.sh
new file mode 100755
index 0000000..b5dcce4
--- /dev/null
+++ b/wasm/scripts/build_wasm.sh
@@ -0,0 +1,116 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+shopt -s nullglob
+
+source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
+
+src_dirs=(./wasm/pow ./wasm/anubis)
+dst_dirs=(./web/static/wasm/simd128 ./web/static/wasm/baseline)
+
+# rustc enables reference-types, multivalue and friends by default for
+# wasm32-unknown-unknown. With reference-types on, LLVM encodes the call_indirect
+# table index as an overlong LEB128 (80 80 80 80 00) rather than the MVP's single
+# reserved 0x00 byte. Engines predating the proposal read one byte, see 0x80, and
+# refuse to compile the module:
+#
+# CompileError: expected table index 0, found 128
+#
+# Clearing the features with -Ctarget-feature is not enough, because the shipped
+# std rlibs are already encoded that way; fixing it at the source would mean
+# rebuilding std on nightly. Instead each module is round-tripped through wasm-opt
+# against the feature set that its oldest supported browser actually implements.
+# That re-emits the MVP call_indirect encoding, and makes wasm-opt reject the
+# module outright if it ever picks up a feature not on the list, so a toolchain
+# upgrade becomes a loud build failure rather than a browser that cannot start.
+#
+# Keep this a pure decode/re-encode with no optimization passes: the wasm build of
+# wasm-opt exhausts its stack on -O2, and we would rather not have an optimizer
+# rewriting proof-of-work code.
+#
+# Chrome shipped sign-ext and mutable-globals in 74, bulk-memory and
+# nontrapping-fptoint in 75, multivalue in 85 and simd in 91.
+baseline_features="-mvp --enable-sign-ext --enable-mutable-globals --enable-bulk-memory --enable-nontrapping-float-to-int"
+simd128_features="${baseline_features} --enable-multivalue --enable-simd"
+
+run_wasm_opt() {
+ if command -v wasm-opt 2>&1 >/dev/null; then
+ wasm-opt "$@"
+ elif command -v wasmtime 2>&1 >/dev/null; then
+ wasmtime run -W exceptions=y --dir . ./utils/wasm/wasm2js/wasm-opt_130.wasm "$@"
+ elif node_runs_wasm; then
+ node --no-warnings ./wasm/scripts/execer.mjs ./utils/wasm/wasm2js/wasm-opt_130.wasm "$@"
+ else
+ go run ./utils/cmd/wazero-exec ./utils/wasm/wasm2js/wasm-opt_130.wasm "$@"
+ fi
+}
+
+copy_modules() {
+ local src="${1}" dst="${2}"
+
+ local files=("${src}"/*.wasm)
+ if [ "${#files[@]}" -eq 0 ]; then
+ echo "cargo built no modules in ${src}" >&2
+ exit 1
+ fi
+
+ cp -vf "${files[@]}" "${dst}"
+}
+
+# reencode DIR FEATURE_FLAGS... rewrites every module in DIR against FEATURE_FLAGS.
+reencode() {
+ local dir="${1}"
+ shift
+
+ local files=("${dir}"/*.wasm)
+ if [ "${#files[@]}" -eq 0 ]; then
+ echo "no modules to re-encode in ${dir}" >&2
+ exit 1
+ fi
+
+ local out err
+ for fname in "${files[@]}"; do
+ out="$(mktemp "${fname}.XXXXXX")"
+ err="$(mktemp)"
+ # stderr is held back because wasm-opt warns on every module that no passes
+ # were specified.
+ if ! run_wasm_opt "$@" "${fname}" -o "${out}" 2>"${err}"; then
+ cat "${err}" >&2
+ rm -f "${out}" "${err}"
+ echo "wasm-opt rejected ${fname}" >&2
+ exit 1
+ fi
+ rm -f "${err}"
+ mv -f "${out}" "${fname}"
+ done
+}
+
+# Newest source file timestamp (unix seconds).
+newest_src="$(mtimes "${src_dirs[@]}" -type f | sort -n | tail -1)"
+
+# Oldest destination file timestamp (unix seconds). Empty if no outputs exist yet
+# (e.g. the output dirs haven't been created, in which case find would error out).
+oldest_dst="$(mtimes "${dst_dirs[@]}" -type f -name '*.wasm' 2>/dev/null | sort -n | head -1 || true)"
+
+if all_populated '*.wasm' "${dst_dirs[@]}" && [ -n "$oldest_dst" ] && awk "BEGIN { exit !($newest_src <= $oldest_dst) }"; then
+ echo "wasm artifacts are up to date, skipping build"
+ exit 0
+fi
+
+mkdir -p ./web/static/wasm/{simd128,baseline}
+
+cargo clean --quiet
+
+# With simd128
+RUSTFLAGS='-C target-feature=+simd128' cargo build --quiet --release --target wasm32-unknown-unknown
+copy_modules ./target/wasm32-unknown-unknown/release ./web/static/wasm/simd128
+reencode ./web/static/wasm/simd128 ${simd128_features}
+
+cargo clean --quiet
+
+# Without simd128
+cargo build --quiet --release --target wasm32-unknown-unknown
+copy_modules ./target/wasm32-unknown-unknown/release ./web/static/wasm/baseline
+reencode ./web/static/wasm/baseline ${baseline_features}
+
+cargo clean --quiet
diff --git a/wasm/scripts/build_wasm2js.sh b/wasm/scripts/build_wasm2js.sh
new file mode 100755
index 0000000..8e0db27
--- /dev/null
+++ b/wasm/scripts/build_wasm2js.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+shopt -s nullglob
+
+source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
+
+WASM2JS_VERSION="130"
+WASM2JS_FLAGS="-all --strip-debug --rse --rereloop --optimize-for-js --flatten --dce --dfo --fpcast-emu --denan --dealign --remove-imports --remove-unused-names --remove-unused-brs --reorder-functions --reorder-locals --strip-target-features --untee --vacuum -s 4 -ffm -lmu -tnh -iit -n"
+src_dirs=(./web/static/wasm/baseline)
+dst_dirs=(./web/js/gen/wasm2js)
+
+# Newest source file timestamp (unix seconds).
+newest_src="$(mtimes "${src_dirs[@]}" -type f | sort -n | tail -1)"
+
+# Oldest destination file timestamp (unix seconds). Empty if no outputs exist yet
+# (e.g. the output dirs haven't been created, in which case find would error out).
+oldest_dst="$(mtimes "${dst_dirs[@]}" -type f -name '*.wasm.js' 2>/dev/null | sort -n | head -1 || true)"
+
+if all_populated '*.wasm.js' "${dst_dirs[@]}" && [ -n "$oldest_dst" ] && awk "BEGIN { exit !($newest_src <= $oldest_dst) }"; then
+ echo "wasm2js artifacts are up to date, skipping build"
+ exit 0
+fi
+
+run_wasm2js() {
+ if command -v wasm2js 2>&1 >/dev/null; then
+ echo ">> wasm2js (sys) ${*}"
+ wasm2js $WASM2JS_FLAGS $*
+ elif command -v wasmtime 2>&1 >/dev/null; then
+ echo ">> wasm2js (wasmtime) ${*}"
+ wasmtime run -W exceptions=y --dir . ./utils/wasm/wasm2js/wasm2js_130.wasm $WASM2JS_FLAGS $*
+ elif node_runs_wasm; then
+ echo ">> node execer.mjs ${*}"
+ node --no-warnings ./wasm/scripts/execer.mjs ./utils/wasm/wasm2js/wasm2js_130.wasm $WASM2JS_FLAGS $*
+ else
+ echo ">> wasm2js (wazero-exec, slow) ${*}"
+ go run ./utils/cmd/wazero-exec ./utils/wasm/wasm2js/wasm2js_130.wasm $WASM2JS_FLAGS $*
+ fi
+}
+
+mkdir -p ./web/js/gen/wasm2js
+
+srcs=(./web/static/wasm/baseline/*.wasm)
+if [ "${#srcs[@]}" -eq 0 ]; then
+ echo "no modules in ./web/static/wasm/baseline, run wasm/scripts/build_wasm.sh first" >&2
+ exit 1
+fi
+
+for fname in "${srcs[@]}"; do
+ output="./web/js/gen/wasm2js/$(basename "${fname}").js"
+ run_wasm2js "${fname}" -o "${output}"
+ # wasm2js emits an import of the anubis host module on line 1; replace it with
+ # a stub. Rewriting through a temp file rather than sed -i because BSD sed
+ # reads the next argument as a mandatory backup suffix and GNU sed does not.
+ tmp="$(mktemp)"
+ sed '1s$.*$const anubis = { anubis_update_nonce: (_ignored) => { } };$' "${output}" >"${tmp}"
+ mv -f "${tmp}" "${output}"
+done
diff --git a/wasm/scripts/execer.mjs b/wasm/scripts/execer.mjs
new file mode 100644
index 0000000..214f45a
--- /dev/null
+++ b/wasm/scripts/execer.mjs
@@ -0,0 +1,27 @@
+import { readFile } from "node:fs/promises";
+import { WASI } from "node:wasi";
+import { argv, cwd, env, exit } from "node:process";
+
+const [wasmBinName, ...wasmArgs] = argv.slice(2);
+
+if (!wasmBinName) {
+ console.error("usage: node execer.mjs [args...]");
+ exit(2);
+}
+
+const wasi = new WASI({
+ version: "preview1",
+ args: [wasmBinName, ...wasmArgs],
+ env,
+ preopens: {
+ "/": cwd(),
+ },
+ returnOnExit: true,
+});
+
+const wasm = await WebAssembly.compile(
+ await readFile(wasmBinName),
+);
+const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
+
+exit(wasi.start(instance));
\ No newline at end of file
diff --git a/wasm/scripts/lib.sh b/wasm/scripts/lib.sh
new file mode 100644
index 0000000..9341666
--- /dev/null
+++ b/wasm/scripts/lib.sh
@@ -0,0 +1,38 @@
+# shellcheck shell=bash
+
+# BSD `find` has no `-printf` flag, so you have to get file timestamps from
+# `stat`. Beautifully, both `stat` implementations differ in how these
+# timestamps are extracted. Figure out which flag you need with a small test
+# because people can run BSD coreutils (or busybox?).
+if stat -f '%m' . >/dev/null 2>&1; then
+ stat_mtime_args=(-f '%m')
+else
+ stat_mtime_args=(-c '%Y')
+fi
+
+# Implements the subset of `find -printf` that's actually needed here.
+mtimes() {
+ find "$@" -exec stat "${stat_mtime_args[@]}" {} +
+}
+
+# all_populated PATTERN DIR... succeeds when every DIR holds at least one file
+# matching PATTERN. Timestamps alone can't answer "are the artifacts there?":
+# a run that dies partway through leaves one output directory filled and the
+# next one empty, and every source file is older than whatever that run managed
+# to write. Check that the files exist before believing the clock.
+all_populated() {
+ local pattern="${1}"
+ shift
+
+ local dir
+ for dir in "$@"; do
+ compgen -G "${dir}/${pattern}" >/dev/null || return 1
+ done
+}
+
+# node_runs_wasm succeeds when node is installed and can be trusted to run the
+# binaryen modules. On the riscv64 CI host (isa rv64imafdcsu) it cannot: node
+# dies with SIGILL partway through wasm-opt, every time.
+node_runs_wasm() {
+ command -v node >/dev/null 2>&1 && [ "$(uname -m)" != "riscv64" ]
+}
diff --git a/wasm/verification_limit_test.go b/wasm/verification_limit_test.go
new file mode 100644
index 0000000..9858902
--- /dev/null
+++ b/wasm/verification_limit_test.go
@@ -0,0 +1,39 @@
+package wasm
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+func TestVerificationLimit(t *testing.T) {
+ releases := make([]func(), 0, 4)
+ for range 4 {
+ release, err := acquireVerification(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ releases = append(releases, release)
+ }
+ t.Cleanup(func() {
+ for _, release := range releases {
+ release()
+ }
+ })
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
+ defer cancel()
+ if release, err := acquireVerification(ctx); !errors.Is(err, context.DeadlineExceeded) {
+ if release != nil {
+ release()
+ }
+ t.Fatalf("fifth verification not bounded: %v", err)
+ }
+ releases[0]()
+ releases = releases[1:]
+ release, err := acquireVerification(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ releases = append(releases, release)
+}
diff --git a/wasm/wasm.go b/wasm/wasm.go
new file mode 100644
index 0000000..c621bbb
--- /dev/null
+++ b/wasm/wasm.go
@@ -0,0 +1,338 @@
+package wasm
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "strconv"
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
+ "github.com/tetratelabs/wazero"
+ "github.com/tetratelabs/wazero/api"
+)
+
+var (
+ validationTime = promauto.NewHistogramVec(prometheus.HistogramOpts{
+ Name: "anubis_wasm_validation_time",
+ Help: "The time taken for the validation function to run per checker (nanoseconds)",
+ Buckets: prometheus.ExponentialBucketsRange(1, math.Pow(2, 31), 32),
+ }, []string{"fname"})
+
+ validationCount = promauto.NewCounterVec(prometheus.CounterOpts{
+ Name: "anubis_wasm_validation",
+ Help: "The number of times the validation logic has been run and its success rate",
+ }, []string{"fname", "success"})
+
+ ErrNotEnoughData = errors.New("wasm: not enough data being written")
+ ErrTooMuchData = errors.New("wasm: too much data being written")
+)
+
+var verificationSlots = make(chan struct{}, 4)
+
+func acquireVerification(ctx context.Context) (func(), error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ select {
+ case verificationSlots <- struct{}{}:
+ return func() { <-verificationSlots }, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+}
+
+const pageSize = 65536
+
+type Runner struct {
+ r wazero.Runtime
+ code wazero.CompiledModule
+ fname string
+}
+
+func NewRunner(ctx context.Context, fname string, fin io.ReadCloser) (*Runner, error) {
+ data, err := io.ReadAll(fin)
+ if err != nil {
+ return nil, fmt.Errorf("wasm: can't read from fin: %w", err)
+ }
+
+ cfg := wazero.NewRuntimeConfig().WithMemoryLimitPages(512)
+
+ r := wazero.NewRuntimeWithConfig(ctx, cfg)
+
+ _, err = r.NewHostModuleBuilder("anubis").
+ NewFunctionBuilder().
+ WithFunc(func(context.Context, uint32) {}).
+ Export("anubis_update_nonce").
+ Instantiate(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("wasm: can't export anubis_update_nonce: %w", err)
+ }
+
+ code, err := r.CompileModule(ctx, data)
+ if err != nil {
+ return nil, fmt.Errorf("wasm: can't compile module: %w", err)
+ }
+
+ result := &Runner{
+ r: r,
+ code: code,
+ fname: fname,
+ }
+
+ return result, nil
+}
+
+func (r *Runner) checkExports(module api.Module) error {
+ funcs := []string{
+ "anubis_work",
+ "anubis_validate",
+ "data_ptr",
+ "set_data_length",
+ "result_hash_ptr",
+ "result_hash_size",
+ "verification_hash_ptr",
+ "verification_hash_size",
+ }
+
+ var errs []error
+
+ for _, fun := range funcs {
+ if module.ExportedFunction(fun) == nil {
+ errs = append(errs, fmt.Errorf("function %s is not defined", fun))
+ }
+ }
+
+ if len(errs) != 0 {
+ return errors.Join(errs...)
+ }
+
+ return nil
+}
+
+func (r *Runner) anubisWork(ctx context.Context, module api.Module, difficulty, initialNonce, iterand uint32) (uint32, error) {
+ results, err := module.ExportedFunction("anubis_work").Call(ctx, uint64(difficulty), uint64(initialNonce), uint64(iterand))
+ if err != nil {
+ return 0, err
+ }
+
+ return uint32(results[0]), nil
+}
+
+func (r *Runner) anubisValidate(ctx context.Context, module api.Module, nonce, difficulty uint32) (bool, error) {
+ results, err := module.ExportedFunction("anubis_validate").Call(ctx, uint64(nonce), uint64(difficulty))
+ if err != nil {
+ return false, err
+ }
+
+ // Rust booleans are 1 if true
+ return results[0] == 1, nil
+}
+
+func (r *Runner) dataPtr(ctx context.Context, module api.Module) (uint32, error) {
+ results, err := module.ExportedFunction("data_ptr").Call(ctx)
+ if err != nil {
+ return 0, err
+ }
+
+ return uint32(results[0]), nil
+}
+
+func (r *Runner) setDataLength(ctx context.Context, module api.Module, length uint32) error {
+ _, err := module.ExportedFunction("set_data_length").Call(ctx, uint64(length))
+ return err
+}
+
+func (r *Runner) resultHashPtr(ctx context.Context, module api.Module) (uint32, error) {
+ results, err := module.ExportedFunction("result_hash_ptr").Call(ctx)
+ if err != nil {
+ return 0, err
+ }
+
+ return uint32(results[0]), nil
+}
+
+func (r *Runner) resultHashSize(ctx context.Context, module api.Module) (uint32, error) {
+ results, err := module.ExportedFunction("result_hash_size").Call(ctx)
+ if err != nil {
+ return 0, err
+ }
+
+ return uint32(results[0]), nil
+}
+
+func (r *Runner) verificationHashPtr(ctx context.Context, module api.Module) (uint32, error) {
+ results, err := module.ExportedFunction("verification_hash_ptr").Call(ctx)
+ if err != nil {
+ return 0, err
+ }
+
+ return uint32(results[0]), nil
+}
+
+func (r *Runner) verificationHashSize(ctx context.Context, module api.Module) (uint32, error) {
+ results, err := module.ExportedFunction("verification_hash_size").Call(ctx)
+ if err != nil {
+ return 0, err
+ }
+
+ return uint32(results[0]), nil
+}
+
+func (r *Runner) writeData(ctx context.Context, module api.Module, data []byte) error {
+ if len(data) == 0 {
+ return ErrNotEnoughData
+ }
+
+ if len(data) > 4096 {
+ return ErrTooMuchData
+ }
+
+ length := uint32(len(data))
+
+ dataPtr, err := r.dataPtr(ctx, module)
+ if err != nil {
+ return fmt.Errorf("can't read data pointer: %w", err)
+ }
+
+ if !module.Memory().Write(dataPtr, data) {
+ return fmt.Errorf("[unexpected] can't write memory, is data out of range??")
+ }
+
+ if err := r.setDataLength(ctx, module, length); err != nil {
+ return fmt.Errorf("can't set data length: %w", err)
+ }
+
+ return nil
+}
+
+func (r *Runner) readResult(ctx context.Context, module api.Module) ([]byte, error) {
+ length, err := r.resultHashSize(ctx, module)
+ if err != nil {
+ return nil, fmt.Errorf("can't get result hash size: %w", err)
+ }
+
+ ptr, err := r.resultHashPtr(ctx, module)
+ if err != nil {
+ return nil, fmt.Errorf("can't get result hash pointer: %w", err)
+ }
+
+ buf, ok := module.Memory().Read(ptr, length)
+ if !ok {
+ return nil, fmt.Errorf("[unexpected] can't read from memory, is something out of range??")
+ }
+
+ return buf, nil
+}
+
+func (r *Runner) run(ctx context.Context, data []byte, difficulty, initialNonce, iterand uint32) (uint32, []byte, api.Module, error) {
+ mod, err := r.r.InstantiateModule(ctx, r.code, wazero.NewModuleConfig().WithName(r.fname))
+ if err != nil {
+ return 0, nil, nil, fmt.Errorf("can't instantiate module: %w", err)
+ }
+
+ if err := r.checkExports(mod); err != nil {
+ return 0, nil, mod, err
+ }
+
+ if err := r.writeData(ctx, mod, data); err != nil {
+ return 0, nil, mod, err
+ }
+
+ nonce, err := r.anubisWork(ctx, mod, difficulty, initialNonce, iterand)
+ if err != nil {
+ return 0, nil, mod, fmt.Errorf("can't run work function: %w", err)
+ }
+
+ hash, err := r.readResult(ctx, mod)
+ if err != nil {
+ return 0, nil, mod, fmt.Errorf("can't read result: %w", err)
+ }
+
+ return nonce, hash, mod, nil
+}
+
+func (r *Runner) Run(ctx context.Context, data []byte, difficulty, initialNonce, iterand uint32) (uint32, []byte, error) {
+ nonce, hash, mod, err := r.run(ctx, data, difficulty, initialNonce, iterand)
+ if mod != nil {
+ if err := mod.Close(ctx); err != nil {
+ return 0, nil, fmt.Errorf("can't close wasm module: %w", err)
+ }
+ }
+ if err != nil {
+ return 0, nil, fmt.Errorf("can't run %s: %w", r.fname, err)
+ }
+
+ return nonce, hash, nil
+}
+
+func (r *Runner) verify(ctx context.Context, data, verify []byte, nonce, difficulty uint32) (bool, api.Module, error) {
+ // Verify permits multiple in-flight calls, so each transient module must be anonymous.
+ // wazero rejects a second live module registered under the same non-empty name.
+ mod, err := r.r.InstantiateModule(ctx, r.code, wazero.NewModuleConfig().WithName(""))
+ if err != nil {
+ return false, nil, fmt.Errorf("can't instantiate module: %w", err)
+ }
+
+ if err := r.checkExports(mod); err != nil {
+ return false, mod, err
+ }
+
+ if err := r.writeData(ctx, mod, data); err != nil {
+ return false, mod, err
+ }
+
+ if err := r.writeVerification(ctx, mod, verify); err != nil {
+ return false, mod, err
+ }
+
+ ok, err := r.anubisValidate(ctx, mod, nonce, difficulty)
+ if err != nil {
+ return false, mod, fmt.Errorf("can't validate hash %x from challenge %x, nonce %d and difficulty %d: %w", verify, data, nonce, difficulty, err)
+ }
+
+ return ok, mod, nil
+}
+
+func (r *Runner) Verify(ctx context.Context, data, verify []byte, nonce, difficulty uint32) (bool, error) {
+ release, err := acquireVerification(ctx)
+ if err != nil {
+ return false, err
+ }
+ defer release()
+ t0 := time.Now()
+ ok, mod, err := r.verify(ctx, data, verify, nonce, difficulty)
+ if mod != nil {
+ if err := mod.Close(ctx); err != nil {
+ return false, fmt.Errorf("can't close wasm module: %w", err)
+ }
+ }
+ validationTime.WithLabelValues(r.fname).Observe(float64(time.Since(t0)))
+ validationCount.WithLabelValues(r.fname, strconv.FormatBool(ok)).Inc()
+ return ok, err
+}
+
+func (r *Runner) writeVerification(ctx context.Context, module api.Module, data []byte) error {
+ length, err := r.verificationHashSize(ctx, module)
+ if err != nil {
+ return fmt.Errorf("can't get verification hash size: %w", err)
+ }
+
+ if length != uint32(len(data)) {
+ return fmt.Errorf("data is too big, want %d bytes, got: %d", length, len(data))
+ }
+
+ ptr, err := r.verificationHashPtr(ctx, module)
+ if err != nil {
+ return fmt.Errorf("can't get verification hash pointer: %w", err)
+ }
+
+ if !module.Memory().Write(ptr, data) {
+ return fmt.Errorf("[unexpected] can't write memory, is data out of range??")
+ }
+
+ return nil
+}
diff --git a/wasm/wasm_test.go b/wasm/wasm_test.go
new file mode 100644
index 0000000..c2cff86
--- /dev/null
+++ b/wasm/wasm_test.go
@@ -0,0 +1,288 @@
+package wasm
+
+import (
+ "context"
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "io/fs"
+ "runtime"
+ "testing"
+ "time"
+
+ "github.com/TecharoHQ/anubis/web"
+ "github.com/tetratelabs/wazero"
+)
+
+func abiTest(t testing.TB, kind, fname string, difficulty uint32) {
+ fin, err := web.Static.Open("static/wasm/" + kind + "/" + fname)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer fin.Close() //nolint:errcheck
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ t.Cleanup(cancel)
+
+ runner, err := NewRunner(ctx, fname, fin)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ h := sha256.New()
+ fmt.Fprint(h, t.Name()) //nolint:errcheck
+ data := h.Sum(nil)
+
+ nonce, hash, mod, err := runner.run(ctx, data, difficulty, 0, 1)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := runner.writeVerification(ctx, mod, hash); err != nil {
+ t.Fatalf("can't write verification: %v", err)
+ }
+
+ ok, err := runner.anubisValidate(ctx, mod, nonce, difficulty)
+ if err != nil {
+ t.Fatalf("can't run validation: %v", err)
+ }
+
+ if !ok {
+ t.Error("validation failed")
+ }
+
+ t.Logf("used %d pages of wasm memory (%d bytes)", mod.Memory().Size()/pageSize, mod.Memory().Size())
+}
+
+func TestAlgos(t *testing.T) {
+ fnames, err := fs.ReadDir(web.Static, "static/wasm/baseline")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, kind := range []string{"baseline", "simd128"} {
+ for _, fname := range fnames {
+ t.Run(kind+"/"+fname.Name(), func(t *testing.T) {
+ if testing.Short() && fname.Name() == "argon2id.wasm" && runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
+ t.Skipf("skipping argon2id on %s in short mode because wazero has no compiler for it and the interpreter is too slow", runtime.GOARCH)
+ }
+ abiTest(t, kind, fname.Name(), 4)
+ })
+ }
+ }
+}
+
+func bench(b *testing.B, kind, fname string, difficulties []uint32) {
+ b.Helper()
+
+ fin, err := web.Static.Open("static/wasm/" + kind + "/" + fname)
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer fin.Close() //nolint:errcheck
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ b.Cleanup(cancel)
+
+ runner, err := NewRunner(ctx, fname, fin)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ h := sha256.New()
+ fmt.Fprint(h, "This is an example value that exists only to test the system.") //nolint:errcheck
+ data := h.Sum(nil)
+
+ _, _, mod, err := runner.run(ctx, data, 0, 0, 1)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ for _, difficulty := range difficulties {
+ b.Run(fmt.Sprintf("difficulty/%d", difficulty), func(b *testing.B) {
+ for b.Loop() {
+ difficulty := difficulty
+ _, err := runner.anubisWork(ctx, mod, difficulty, 0, 1)
+ if err != nil {
+ b.Fatalf("can't do test work run: %v", err)
+ }
+ }
+ })
+ }
+}
+
+func BenchmarkArgon2ID(b *testing.B) {
+ for _, kind := range []string{"baseline", "simd128"} {
+ b.Run(kind, func(b *testing.B) {
+ bench(b, kind, "argon2id.wasm", []uint32{4, 6, 8})
+ })
+ }
+}
+
+func BenchmarkHashX(b *testing.B) {
+ for _, kind := range []string{"baseline", "simd128"} {
+ b.Run(kind, func(b *testing.B) {
+ bench(b, kind, "hashx.wasm", []uint32{4, 6, 8})
+ })
+ }
+}
+
+func BenchmarkSHA256(b *testing.B) {
+ for _, kind := range []string{"baseline", "simd128"} {
+ b.Run(kind, func(b *testing.B) {
+ bench(b, kind, "sha256.wasm", []uint32{4, 6, 8, 10, 12, 14, 16})
+ })
+ }
+}
+
+func TestRunnerConcurrentVerify(t *testing.T) {
+ fin, err := web.Static.Open("static/wasm/simd128/hashx.wasm")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer fin.Close() //nolint:errcheck
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ t.Cleanup(cancel)
+ runner, err := NewRunner(ctx, "hashx.wasm", fin)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ sum := sha256.Sum256([]byte("concurrent HashX verification regression"))
+ nonce, hash, err := runner.Run(ctx, sum[:], 1, 0, 1)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ const workers = 16
+ start := make(chan struct{})
+ errs := make(chan error, workers)
+ for range workers {
+ go func() {
+ <-start
+ ok, err := runner.Verify(ctx, sum[:], hash, nonce, 1)
+ if err == nil && !ok {
+ err = errors.New("valid HashX proof was rejected")
+ }
+ errs <- err
+ }()
+ }
+ close(start)
+ for range workers {
+ if err := <-errs; err != nil {
+ t.Error(err)
+ }
+ }
+}
+
+func BenchmarkValidate(b *testing.B) {
+ fnames, err := fs.ReadDir(web.Static, "static/wasm/simd128")
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ h := sha256.New()
+ fmt.Fprint(h, "This is an example value that exists only to test the system.") //nolint:errcheck
+ data := h.Sum(nil)
+
+ for _, fname := range fnames {
+ fname := fname.Name()
+
+ difficulty := uint32(1)
+
+ switch fname {
+ case "sha256.wasm":
+ difficulty = 16
+ }
+
+ b.Run(fname, func(b *testing.B) {
+ fin, err := web.Static.Open("static/wasm/simd128/" + fname)
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer fin.Close() //nolint:errcheck
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ b.Cleanup(cancel)
+
+ runner, err := NewRunner(ctx, fname, fin)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ nonce, hash, mod, err := runner.run(ctx, data, difficulty, 0, 1)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ if err := runner.writeVerification(ctx, mod, hash); err != nil {
+ b.Fatalf("can't write verification: %v", err)
+ }
+
+ for b.Loop() {
+ _, err := runner.anubisValidate(ctx, mod, nonce, difficulty)
+ if err != nil {
+ b.Fatalf("can't run validation: %v", err)
+ }
+ }
+ })
+ }
+}
+
+func TestRunnerDataHardening(t *testing.T) {
+ fnames, err := fs.ReadDir(web.Static, "static/wasm/simd128")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, fname := range fnames {
+ fname := fname.Name()
+ t.Run(fname, func(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ data []byte
+ err error
+ }{
+ {
+ name: "simple okay",
+ data: make([]byte, 4096),
+ err: nil,
+ },
+ {
+ name: "not enough",
+ data: make([]byte, 0),
+ err: ErrNotEnoughData,
+ },
+ {
+ name: "too much",
+ data: make([]byte, 8192),
+ err: ErrTooMuchData,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ fin, err := web.Static.Open("static/wasm/simd128/" + fname)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer fin.Close() //nolint:errcheck
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ t.Cleanup(cancel)
+
+ runner, err := NewRunner(ctx, fname, fin)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mod, err := runner.r.InstantiateModule(ctx, runner.code, wazero.NewModuleConfig().WithName(runner.fname))
+ if err != nil {
+ t.Fatalf("can't instantiate module: %v", err)
+ }
+
+ if err := runner.writeData(t.Context(), mod, tt.data); !errors.Is(err, tt.err) {
+ t.Logf("wanted error: %v", tt.err)
+ t.Logf("got error: %v", err)
+ t.Error()
+ }
+ })
+ }
+ })
+ }
+}
diff --git a/web/build.sh b/web/build.sh
index d0818e0..9e650f0 100755
--- a/web/build.sh
+++ b/web/build.sh
@@ -41,16 +41,16 @@ cp ../lib/localization/locales/*.json static/locales/
shopt -s nullglob globstar
-for file in js/**/*.ts js/**/*.mjs; do
- out="static/${file}"
- if [[ "$file" == *.ts ]]; then
- out="static/${file%.ts}.mjs"
- fi
+for file in js/*.ts js/worker/*.ts; do
+ out="static/${file}"
+ if [[ "$file" == *.ts ]]; then
+ out="static/${file%.ts}.mjs"
+ fi
- mkdir -p "$(dirname "$out")"
+ mkdir -p "$(dirname "$out")"
- esbuild "$file" --sourcemap --bundle --minify --outfile="$out" --banner:js="$LICENSE"
- gzip -f -k -n "$out"
- zstd -f -k --ultra -22 "$out"
- brotli -fZk "$out"
+ esbuild "$file" --sourcemap --bundle --minify --target=chrome66 --outfile="$out" --banner:js="$LICENSE"
+ gzip -f -k -n "$out"
+ zstd -f -k --ultra -22 "$out"
+ brotli -fZk "$out"
done
diff --git a/web/index.go b/web/index.go
index 6220d2e..01af9fb 100644
--- a/web/index.go
+++ b/web/index.go
@@ -3,6 +3,7 @@ package web
import (
"context"
"fmt"
+ "html"
"io"
"github.com/a-h/templ"
@@ -12,12 +13,12 @@ import (
"github.com/TecharoHQ/anubis/lib/localization"
)
-func Base(title string, body templ.Component, impressum *config.Impressum, localizer *localization.SimpleLocalizer) templ.Component {
- return base(title, body, impressum, nil, nil, localizer)
+func Base(title string, body templ.Component, impressum *config.Impressum, honeypot *config.Honeypot, localizer *localization.SimpleLocalizer) templ.Component {
+ return base(title, body, impressum, honeypot, nil, nil, localizer)
}
-func BaseWithChallengeAndOGTags(title string, body templ.Component, impressum *config.Impressum, challenge *challenge.Challenge, rules *config.ChallengeRules, ogTags map[string]string, localizer *localization.SimpleLocalizer) templ.Component {
- return base(title, body, impressum, struct {
+func BaseWithChallengeAndOGTags(title string, body templ.Component, impressum *config.Impressum, honeypot *config.Honeypot, challenge *challenge.Challenge, rules *config.ChallengeRules, ogTags map[string]string, localizer *localization.SimpleLocalizer) templ.Component {
+ return base(title, body, impressum, honeypot, struct {
Rules *config.ChallengeRules `json:"rules"`
Challenge any `json:"challenge"`
}{
@@ -36,7 +37,9 @@ func Bench(localizer *localization.SimpleLocalizer) templ.Component {
func honeypotLink(href string) templ.Component {
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
- fmt.Fprintf(w, ``, href)
+ if _, err := fmt.Fprintf(w, ``, html.EscapeString(href)); err != nil {
+ return err
+ }
return nil
})
}
diff --git a/web/index.templ b/web/index.templ
index 7fc3a97..2155e1a 100644
--- a/web/index.templ
+++ b/web/index.templ
@@ -9,7 +9,7 @@ import (
"github.com/google/uuid"
)
-templ base(title string, body templ.Component, impressum *config.Impressum, challenge any, ogTags map[string]string, localizer *localization.SimpleLocalizer) {
+templ base(title string, body templ.Component, impressum *config.Impressum, honeypot *config.Honeypot, challenge any, ogTags map[string]string, localizer *localization.SimpleLocalizer) {
@@ -64,7 +64,9 @@ templ base(title string, body templ.Component, impressum *config.Impressum, chal
@templ.JSONScript("anubis_public_url", anubis.PublicUrl)
- @honeypotLink(anubis.BasePrefix + fmt.Sprintf("%shoneypot/%s/init", anubis.APIPrefix, uuid.NewString()))
+ if honeypot != nil && honeypot.Enabled {
+ @honeypotLink(anubis.BasePrefix + fmt.Sprintf("%shoneypot/%s/init", anubis.APIPrefix, uuid.NewString()))
+ }