Update to Anubis v1.28.2 (#1)

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

## Approach

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

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

## Customizations kept

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

## Deploy notes

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

## Verification

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

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

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

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

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

No files matched your search

+14 -7
View File
@@ -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)
}
+80
View File
@@ -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)
}
}
+56
View File
@@ -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)
}
+152
View File
@@ -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)
}
})
}
}
+407
View File
@@ -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)
}
+39
View File
@@ -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")
}
}
+1 -1
View File
@@ -271,4 +271,4 @@ func BenchmarkClampIP(b *testing.B) {
ClampIP(ipv4mapped)
}
})
}
}
+31
View File
@@ -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 `<Condition>` 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}`;
});
```
+201
View File
@@ -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
}
+92
View File
@@ -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)
}
})
}
}
+146
View File
@@ -0,0 +1,146 @@
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"fmt"
"io"
"strings"
)
// rewriteDirectoryIDs replaces wixl-heat's randomized dir<HEX> 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<HEX> and fil<HEX> IDs are already stable, derived from
// each component's and file's relative path. Only its dir<HEX> IDs are
// random: running wixl-heat twice over an identical tree produces two
// completely disjoint sets of directory IDs (verified empirically). Each
// dir<HEX> 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<HEX> 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<HEX> shape wixl-heat itself uses for cmp<HEX> and fil<HEX>: 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]))
}
+735
View File
@@ -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 <arch> 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: <WixVariable Id="WixUIBannerBmp">,
// 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 <Property Id="SecureCustomProperties"> 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)
}
+805
View File
@@ -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))
}
}
}
+151
View File
@@ -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<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-pre(?P<pre>\d+))?(?:-(?P<commits>\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
}
+138
View File
@@ -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)
}
}
+2 -2
View File
@@ -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)
}
+30 -24
View File
@@ -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.
+9 -9
View File
@@ -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 {
+82
View File
@@ -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)
}
})
}
}
+24
View File
@@ -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)
}
})
}
}
+9 -3
View File
@@ -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
}
+1 -1
View File
@@ -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 {
+44 -5
View File
@@ -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)
+146
View File
@@ -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)
}
})
}
+2 -3
View File
@@ -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
+4 -3
View File
@@ -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)
}
+15 -10
View File
@@ -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 = ""
@@ -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)
}
})
}
}
+111 -31
View File
@@ -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()
+35
View File
@@ -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)
}
})
}
}
+1 -1
View File
@@ -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.
+15
View File
@@ -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,
}
}
+59
View File
@@ -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:
}
}
+47
View File
@@ -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
}
+107
View File
@@ -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)
}
}
+7 -1
View File
@@ -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)
})
}
+22
View File
@@ -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)
}
+2 -2
View File
@@ -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
}
}
+1 -1
View File
@@ -76,4 +76,4 @@ func TestListOr_UnmarshalJSON(t *testing.T) {
t.Errorf("Expected [1, 2, 3], got %v", lo)
}
})
}
}
+1 -1
View File
@@ -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"),
)
}
+1 -1
View File
@@ -3,5 +3,5 @@ package internal
import "mime"
func init() {
mime.AddExtensionType(".mjs", "text/javascript")
_ = mime.AddExtensionType(".mjs", "text/javascript")
}
+140
View File
@@ -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 }
+151
View File
@@ -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))
}
+1
View File
@@ -0,0 +1 @@
- name: foo
+1
View File
@@ -0,0 +1 @@
- name: bar
+5
View File
@@ -0,0 +1,5 @@
[
{
"name": "foo"
}
]
+1
View File
@@ -0,0 +1 @@
- name: boz
+1
View File
@@ -0,0 +1 @@
name: toplevel
+5 -19
View File
@@ -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
}
+8 -4
View File
@@ -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(`
<!DOCTYPE html>
<html>
@@ -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(`
<!DOCTYPE html>
<html>
+25 -8
View File
@@ -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
}
+63 -2
View File
@@ -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(`<html><head><meta property="og:title" content="ok"></head></html>`)) //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)
}
})
}
}
+1
View File
@@ -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")
+2 -2
View File
@@ -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)
}
+3 -2
View File
@@ -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{
+6 -11
View File
@@ -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 {
+5 -1
View File
@@ -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, `<!DOCTYPE html><html><head><meta property="og:title" content="Unix Socket Test" /></head><body>Test</body></html>`)
@@ -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, `<!DOCTYPE html><html><head><meta property="og:title" content="HostOverride" /></head><body>ok</body></html>`)
}))
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, `<!DOCTYPE html><html><head><meta property="og:title" content="Self-Signed" /></head><body>hello</body></html>`)
})
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)
})
+3 -4
View File
@@ -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
+55
View File
@@ -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(`<meta property="og:title" content="secret">`)); 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(`<meta property="og:title" content="safe">`)); 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)
}
}
})
}
}
+10 -2
View File
@@ -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
+23
View File
@@ -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))
}
}
+57
View File
@@ -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()
}
+44
View File
@@ -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)
}
})
}
}
+92
View File
@@ -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
}
+180
View File
@@ -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))
}
}
})
}
}
+235
View File
@@ -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, "<html><body><span id=anubis-test>%d</span></body></html>", 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
}
+34 -70
View File
@@ -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("<loopback>"),
})
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("<loopback>"),
})
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("<loopback>"),
})
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, "<html><body><span id=anubis-test>%d</span></body></html>", 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, "")
}
+24
View File
@@ -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)
}
}
+9
View File
@@ -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
+9
View File
@@ -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
+9
View File
@@ -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
+1 -1
View File
@@ -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()
}
}