mathiasandClaude Opus 5 3257364f23
CI / Lint / Test / Vet (push) Successful in 5s
fix(auth): a validator whose issuer is down at boot is built anyway
Closes #4. Closes gitea-mcp#57.

Filed 2026-07-17, filed again 2026-09-07, recurred 2026-09-14. Each occurrence
ended with a human running `kubectl rollout restart`; the last one ran for six
days and was found by chance while gathering context for unrelated work.

THE BUG

NewMultiJWTValidator resolved OIDC discovery eagerly and returned (nil, err) if
the issuer was not answering. BearerMiddleware reads a nil validator as "this
server does not do JWT auth", so it fell through to the static-token comparison
and rejected every Authentik JWT:

    WARN mcp auth rejected reason=static_token_mismatch token_type=jwt status=401

Two states collapsed into one nil:

    static-token-only by design      -> nil   correct
    JWT required, IdP down at boot   -> nil   wrong, and permanent

Permanent because discovery was attempted exactly once, at construction.

WHY THE FIX IS SMALL

Everything downstream was already right. Validate distinguishes ErrUnavailable
(issuer unreachable -> 503, client retries) from a definitive rejection (-> 401),
and BearerMiddleware already honours that — gitea-mcp#6 got it right. That path
was simply unreachable when the validator was never built.

So: build it anyway. jwks_uri now resolves lazily on first use and re-resolves on
failure, no sooner than WithRetryInterval apart (default 30s) so a down issuer
costs one discovery request per interval, not one per request. Until it resolves,
Validate returns ErrUnavailable and the existing machinery does the rest. The
constructor still warms discovery eagerly on a healthy start; it just no longer
fails on it.

Ready(ctx) reports whether every issuer resolved, and attempts resolution for any
that have not. That makes a readiness probe the retry loop — no background
goroutine, no context to leak, and the platform's own cadence drives recovery.
A nil validator is Ready: "JWT auth disabled" is a configuration, not a fault.

WHAT DID NOT CHANGE

No issuer configured still returns (nil, nil). That is the one case where nil is
not a lie, and collapsing it would turn every static-only server into a JWT
server. Pinned by TestNewMultiJWTValidator_NoIssuer_StillReturnsNilNil.

ONE EXISTING TEST CHANGED ITS MECHANISM, NOT ITS CLAIM

TestNewMultiJWTValidator_UsesPerIssuerHTTPClientForAuthedFetch asserted that the
constructor ERRORS when discovery 401s without the fetch credential. It cannot,
now, by design. Rewritten to assert the property that actually mattered, and
more directly than before: without the credential the validator is not Ready AND
a correctly-minted token from that very issuer is refused as ErrUnavailable. The
old test only checked that a constructor returned an error.

Written test-first: jwt_bootrace_test.go red (API absent), then green. Also red
in the behavioural sense — the constructor-errors assertion above had to be
rewritten precisely because the semantics genuinely changed.

Verified: golangci-lint 0 issues; go vet clean; go test -race -count=1 ./... ok.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 20:03:50 +02:00

mcp-chassis

Shared Go library for Mathias-owned MCP servers. Provides the auth + middleware primitives that every MCP server needs.

Why

By 2026-05-22 there were three+ MCP servers (gitea-mcp, brain-mcp / ingestion, future ones from template-go-agent) each carrying their own near-identical:

  • Dex JWT validator (~80 LOC, identical jwx/v2 plumbing)
  • Bearer middleware (~50 LOC, dual-mode static + JWT)
  • RFC 9728 protected-resource metadata handler (~25 LOC)

The homelab architecture review's spike S3 (see gitea.d-ma.be/mathias/infra/docs/superpowers/handoffs/2026-05-22-mcp-chassis-spike.md) concluded a thin shared lib pays for itself within the first migration. This is that lib.

Non-goals

  • Replacing each MCP's tool registration / handler logic — that is per-domain.
  • Solving HTTP routing — consumers keep their own http.ServeMux.
  • Solving observability — see gitea.d-ma.be/mathias/hyperguild/ingestion/internal/metrics for the hand-rolled Prometheus pattern. May absorb a metrics subpackage here later, once a second consumer needs it.

Packages

auth

  • JWTValidator — Dex OIDC JWT validation. nil is a valid value meaning "JWT auth disabled".
  • BearerMiddleware — static-Bearer-or-Dex-JWT gate. Static wins first; only emits WWW-Authenticate: Bearer ... resource_metadata=... on 401 when resourceMetadataURL is non-empty (claude.ai OAuth discovery).
  • ProtectedResourceHandler — RFC 9728 metadata document for GET /.well-known/oauth-protected-resource.

Usage

package main

import (
	"context"
	"net/http"
	"os"

	"git.d-ma.be/mathias/mcp-chassis/auth"
)

func main() {
	staticToken := os.Getenv("BRAIN_MCP_TOKEN")
	dexIssuer := os.Getenv("DEX_ISSUER_URL")
	audience := os.Getenv("MCP_AUDIENCE")
	resourceURL := os.Getenv("MCP_RESOURCE_URL")

	validator, err := auth.NewJWTValidator(context.Background(), dexIssuer, audience)
	if err != nil {
		panic(err)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /.well-known/oauth-protected-resource",
		auth.ProtectedResourceHandler(resourceURL, dexIssuer))
	mux.Handle("/mcp", auth.BearerMiddleware(
		staticToken,
		validator,
		"brain",
		resourceURL+"/.well-known/oauth-protected-resource",
		mcpHandler(),
	))

	_ = http.ListenAndServe(":3300", mux)
}

func mcpHandler() http.Handler { /* per-domain */ return nil }

Versioning

Trunk-based development on main. Tagged with semver. Consumers pin specific tags (go.mod require git.d-ma.be/mathias/mcp-chassis v0.x.y) and bump deliberately.

Migrations are documented per-consumer in the consumer's CHANGELOG / commits.

Dependencies

  • github.com/lestrrat-go/jwx/v2 — JWKS cache + JWT parsing. Same dep every MCP already had; no new transitive cost when adopting the chassis.
  • github.com/stretchr/testify — tests only.

stdlib otherwise.

S
Description
Shared Go library for Mathias-owned MCP servers — Dex JWT validator + Bearer middleware + RFC 9728 protected-resource metadata. Hand-rolled (stdlib + lestrrat-go/jwx) per the homelab architecture review.
Readme
101 KiB
Languages
Go 100%