anchorage v1.0 initial tree

Greenfield Go multi-tenant IPFS Pinning Service wire-compatible with the
IPFS Pinning Services API spec. Paired 1:1 with Kubo over localhost RPC,
clustered via embedded NATS JetStream, Postgres source-of-truth with
RLS-enforced tenancy, Fiber + huma v2 for the HTTP surface, Authentik
OIDC for session login with kid-rotated HS256 JWT API tokens.

Feature-complete against the 22-milestone build plan, including the
ship-it v1.0 gap items:

  * admin CLIs: drain/uncordon, maintenance, mint-token, rotate-key,
    prune-denylist, rebalance --dry-run, cache-stats, cluster-presences
  * TTL leader election via NATS KV, fence tokens, JetStream dedup
  * rebalancer (plan/apply split), reconciler, requeue sweeper
  * ristretto caches with NATS-backed cross-node invalidation
    (placements live-nodes + token denylist)
  * maintenance watchdog for stuck cluster-pause flag
  * Prometheus /metrics with CIDR ACL, HTTP/pin/scheduler/cache gauges
  * rate limiting: session (10/min) + anonymous global (120/min)
  * integration tests: rebalance, refcount multi-org, RLS belt
  * goreleaser (tar + deb/rpm/apk + Alpine Docker) targeting Gitea

Stack: Cobra/Viper, Fiber v2 + huma v2, embedded NATS JetStream,
pgx/sqlc/golang-migrate, ristretto, TypeID, prometheus/client_golang,
testcontainers-go.
This commit is contained in:
57_Wolve committed 2026-04-16 18:13:36 -05:00
commit 12bf35caf8
112 files changed
+16884

No files matched your search

+166
View File
@@ -0,0 +1,166 @@
// Package auth is the thin JWT/session middleware that gates every
// anchorage API call.
//
// It covers both halves of the auth story: authentication (who are
// you — parsed Bearer token) and authorization (are you allowed — role
// + scope + org checks via Require*). The JWT cryptography itself lives
// in internal/pkg/token.
//
// The middleware extracts the Bearer token, populates a ClientContext,
// and attaches it to context.Context (huma handlers read via FromContext)
// and Fiber Locals (WebSocket handlers read via FromLocals).
package auth
import (
"context"
"errors"
"strings"
"github.com/gofiber/fiber/v2"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/token"
)
// ClientContext describes the authenticated client attached to a request.
type ClientContext struct {
Org ids.OrgID
User ids.UserID
Role string
Scopes []string
// TokenJTI is set only for API-token auth (not session cookies).
TokenJTI *ids.TokenID
}
// contextKey is unexported so callers must round-trip through FromContext.
type contextKey struct{}
// WithClient returns ctx with cc attached.
func WithClient(ctx context.Context, cc *ClientContext) context.Context {
return context.WithValue(ctx, contextKey{}, cc)
}
// FromContext recovers the client, if any. Returns nil when unauthenticated.
func FromContext(ctx context.Context) *ClientContext {
cc, _ := ctx.Value(contextKey{}).(*ClientContext)
return cc
}
// ErrUnauthorized is returned when a request lacks or fails authentication.
var ErrUnauthorized = errors.New("auth: unauthorized")
// SessionCookieName is the cookie anchorage issues for logged-in web
// users after POST /v1/auth/session succeeds. Exported so the session
// handler and the logout handler can agree on it without a constant
// drift.
const SessionCookieName = "anchorage_session"
// BearerMiddleware validates the request's authentication token — either
// an `Authorization: Bearer <jwt>` header (API clients) or an
// `anchorage_session=<jwt>` cookie (web UI after POST /v1/auth/session).
// On success it attaches a ClientContext to both context.Context and
// Fiber Locals.
//
// Precedence: if both a bearer header and a session cookie are present,
// the header wins — API clients tend to be more deliberate and we don't
// want a stale cookie to silently shadow a freshly-minted token.
//
// Missing tokens are NOT rejected here; handlers that need auth call
// Require(ctx). Leaving unauthenticated requests un-annotated lets
// /health, /ready, /docs and /openapi.json respond without ceremony.
func BearerMiddleware(signer *token.Signer) fiber.Handler {
return func(c *fiber.Ctx) error {
raw, source, err := extractToken(c)
if err != nil {
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
}
if raw == "" {
return c.Next()
}
claims, err := signer.Parse(c.UserContext(), raw)
if err != nil {
// Cookie-based auth errors should clear the bad cookie so the
// browser stops sending it on every retry. Header-based auth
// errors just bubble up.
if source == sourceCookie {
c.Cookie(expiringCookie())
}
return fiber.NewError(fiber.StatusUnauthorized, "auth: "+err.Error())
}
jti, _ := ids.ParseToken(claims.ID)
cc := &ClientContext{
Org: claims.Org,
User: claims.User,
Role: claims.Role,
Scopes: claims.Scopes,
TokenJTI: &jti,
}
c.SetUserContext(WithClient(c.UserContext(), cc))
c.Locals(localsKey, cc)
return c.Next()
}
}
type tokenSource int
const (
sourceNone tokenSource = iota
sourceHeader
sourceCookie
)
// extractToken pulls a JWT off the Authorization header first, then the
// session cookie. Returns ("", sourceNone, nil) when neither is present
// so the middleware can let unauthenticated requests through.
func extractToken(c *fiber.Ctx) (string, tokenSource, error) {
if h := c.Get(fiber.HeaderAuthorization); h != "" {
parts := strings.SplitN(h, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return "", sourceNone, errors.New("auth: malformed Authorization header")
}
return strings.TrimSpace(parts[1]), sourceHeader, nil
}
if v := c.Cookies(SessionCookieName); v != "" {
return v, sourceCookie, nil
}
return "", sourceNone, nil
}
// expiringCookie returns a Set-Cookie that immediately clears the
// session cookie on the client. Used on logout and on a bad-cookie
// 401 so stale JWTs don't keep round-tripping.
func expiringCookie() *fiber.Cookie {
return &fiber.Cookie{
Name: SessionCookieName,
Value: "",
Path: "/",
HTTPOnly: true,
Secure: true,
SameSite: fiber.CookieSameSiteLaxMode,
MaxAge: -1,
}
}
// localsKey is the Fiber Locals key where BearerMiddleware parks the
// authenticated ClientContext for downstream handlers that can't reach
// UserContext — notably the /v1/events WebSocket upgrade.
const localsKey = "anchorage.auth.client"
// FromLocals recovers a ClientContext stored on a Fiber request by
// BearerMiddleware. Returns nil when unauthenticated.
func FromLocals(locals func(key string) interface{}) *ClientContext {
v := locals(localsKey)
cc, _ := v.(*ClientContext)
return cc
}
// Require asserts that the request is authenticated. Handlers call this
// as the first line of their body.
func Require(ctx context.Context) (*ClientContext, error) {
cc := FromContext(ctx)
if cc == nil {
return nil, ErrUnauthorized
}
return cc, nil
}
+134
View File
@@ -0,0 +1,134 @@
package auth
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
"github.com/MicahParks/keyfunc/v3"
"github.com/golang-jwt/jwt/v5"
)
// OIDCClaims is the subset of an Authentik ID token anchorage cares about.
//
// Standard OIDC claims (sub, email, name) land directly; custom claims
// added via Authentik property mappings (like the `groups` claim from
// docs/authentik-setup.md §4) ride along too.
type OIDCClaims struct {
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name,omitempty"`
PreferredName string `json:"preferred_username,omitempty"`
Groups []string `json:"groups,omitempty"`
jwt.RegisteredClaims
}
// DisplayName picks the best human-readable name from the claims — preferring
// `name`, falling back to `preferred_username`, then email. Never empty.
func (c *OIDCClaims) DisplayName() string {
switch {
case c.Name != "":
return c.Name
case c.PreferredName != "":
return c.PreferredName
default:
return c.Email
}
}
// OIDCVerifier validates ID tokens against a single Authentik provider.
//
// JWKS are fetched from <issuer>/jwks/ on construction and auto-refreshed
// by keyfunc/v3 (default interval ~1h). Revocation of the signing key is
// therefore picked up without an anchorage restart.
type OIDCVerifier struct {
issuer string
audience string
jwks keyfunc.Keyfunc
}
// OIDCVerifierOptions configures NewOIDCVerifier.
type OIDCVerifierOptions struct {
// Issuer is the full OIDC issuer URL (must match the ID token's
// `iss` claim byte-for-byte).
Issuer string
// Audience is the expected `aud` claim value — typically the
// OAuth2 client ID as configured in Authentik.
Audience string
// JWKSURL overrides the default <issuer>/jwks/ derivation. Leave
// empty in production; useful for tests pointing at httptest.
JWKSURL string
}
// NewOIDCVerifier fetches the JWKS for the given issuer once, then
// relies on keyfunc's background refresh to track cert rotations.
//
// The initial JWKS fetch is bounded by ctx — pass a deadline to avoid
// hanging app startup if Authentik is unreachable at boot.
func NewOIDCVerifier(ctx context.Context, opts OIDCVerifierOptions) (*OIDCVerifier, error) {
if opts.Issuer == "" {
return nil, errors.New("auth: OIDC Issuer is required")
}
if opts.Audience == "" {
return nil, errors.New("auth: OIDC Audience is required")
}
jwksURL := opts.JWKSURL
if jwksURL == "" {
jwksURL = strings.TrimRight(opts.Issuer, "/") + "/jwks/"
}
if _, err := url.Parse(jwksURL); err != nil {
return nil, fmt.Errorf("auth: parse jwks url: %w", err)
}
k, err := keyfunc.NewDefaultCtx(ctx, []string{jwksURL})
if err != nil {
return nil, fmt.Errorf("auth: init jwks client for %s: %w", jwksURL, err)
}
return &OIDCVerifier{
issuer: opts.Issuer,
audience: opts.Audience,
jwks: k,
}, nil
}
// Verify validates an Authentik-issued ID token end-to-end: signature via
// JWKS, issuer / audience / expiry / not-before clock checks, and a
// minimum shape check (sub + email required).
//
// Returns the parsed claims on success.
func (v *OIDCVerifier) Verify(_ context.Context, idToken string) (*OIDCClaims, error) {
if v == nil {
return nil, errors.New("auth: nil OIDCVerifier")
}
if strings.TrimSpace(idToken) == "" {
return nil, errors.New("auth: empty id token")
}
claims := &OIDCClaims{}
tok, err := jwt.ParseWithClaims(idToken, claims, v.jwks.Keyfunc,
jwt.WithIssuer(v.issuer),
jwt.WithAudience(v.audience),
// Allow a small clock skew — Authentik and anchorage are on
// different hosts, NTP is imperfect.
jwt.WithLeeway(60*time.Second),
)
if err != nil {
return nil, fmt.Errorf("auth: verify id token: %w", err)
}
if !tok.Valid {
return nil, errors.New("auth: id token invalid")
}
if claims.Sub == "" {
return nil, errors.New("auth: id token missing sub claim")
}
if claims.Email == "" {
return nil, errors.New("auth: id token missing email claim — add `email` to the Authentik scope mappings")
}
return claims, nil
}
+227
View File
@@ -0,0 +1,227 @@
package auth_test
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"math/big"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"anchorage/internal/pkg/auth"
)
// fakeAuthentik simulates the small surface of Authentik anchorage
// actually touches: a JWKS endpoint and a helper to mint ID tokens.
type fakeAuthentik struct {
server *httptest.Server
priv *rsa.PrivateKey
kid string
issuer string
audience string
}
func newFakeAuthentik(t *testing.T, audience string) *fakeAuthentik {
t.Helper()
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate key: %v", err)
}
mux := http.NewServeMux()
kid := "test-kid-1"
fk := &fakeAuthentik{priv: priv, kid: kid, audience: audience}
mux.HandleFunc("/jwks/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"keys": []map[string]string{
{
"kty": "RSA",
"use": "sig",
"alg": "RS256",
"kid": kid,
"n": base64urlBigInt(priv.N),
"e": base64urlBigInt(big.NewInt(int64(priv.E))),
},
},
})
})
fk.server = httptest.NewServer(mux)
// Authentik-style per-app issuer. The verifier derives JWKS URL as
// <issuer>/jwks/ so our mux handles "/jwks/" under the issuer path.
fk.issuer = fk.server.URL + "/"
return fk
}
func (fk *fakeAuthentik) close() { fk.server.Close() }
// mintIDToken mints an RS256-signed ID token with optional overrides.
func (fk *fakeAuthentik) mintIDToken(t *testing.T, overrides func(c *auth.OIDCClaims)) string {
t.Helper()
now := time.Now().UTC()
c := &auth.OIDCClaims{
Sub: "hashed-authentik-sub-123",
Email: "alice@example.com",
Name: "Alice Example",
RegisteredClaims: jwt.RegisteredClaims{
Issuer: fk.issuer,
Audience: jwt.ClaimStrings{fk.audience},
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(5 * time.Minute)),
},
}
if overrides != nil {
overrides(c)
}
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, c)
tok.Header["kid"] = fk.kid
signed, err := tok.SignedString(fk.priv)
if err != nil {
t.Fatalf("sign: %v", err)
}
return signed
}
func base64urlBigInt(i *big.Int) string {
return base64.RawURLEncoding.EncodeToString(i.Bytes())
}
// ---------------------------------------------------------------------------
func TestOIDCVerifierAcceptsWellFormedToken(t *testing.T) {
fk := newFakeAuthentik(t, "anchorage-web")
defer fk.close()
v, err := auth.NewOIDCVerifier(context.Background(), auth.OIDCVerifierOptions{
Issuer: fk.issuer,
Audience: fk.audience,
})
if err != nil {
t.Fatalf("NewOIDCVerifier: %v", err)
}
raw := fk.mintIDToken(t, nil)
claims, err := v.Verify(context.Background(), raw)
if err != nil {
t.Fatalf("Verify: %v", err)
}
if claims.Sub != "hashed-authentik-sub-123" {
t.Errorf("Sub = %q", claims.Sub)
}
if claims.Email != "alice@example.com" {
t.Errorf("Email = %q", claims.Email)
}
if claims.DisplayName() != "Alice Example" {
t.Errorf("DisplayName = %q", claims.DisplayName())
}
}
func TestOIDCVerifierRejectsWrongAudience(t *testing.T) {
fk := newFakeAuthentik(t, "anchorage-web")
defer fk.close()
v, _ := auth.NewOIDCVerifier(context.Background(), auth.OIDCVerifierOptions{
Issuer: fk.issuer,
Audience: "anchorage-web",
})
raw := fk.mintIDToken(t, func(c *auth.OIDCClaims) {
c.Audience = jwt.ClaimStrings{"some-other-client"}
})
if _, err := v.Verify(context.Background(), raw); err == nil {
t.Error("expected verify to fail on wrong audience")
}
}
func TestOIDCVerifierRejectsWrongIssuer(t *testing.T) {
fk := newFakeAuthentik(t, "anchorage-web")
defer fk.close()
v, _ := auth.NewOIDCVerifier(context.Background(), auth.OIDCVerifierOptions{
Issuer: fk.issuer,
Audience: "anchorage-web",
})
raw := fk.mintIDToken(t, func(c *auth.OIDCClaims) {
c.Issuer = "https://evil.example.com/"
})
if _, err := v.Verify(context.Background(), raw); err == nil {
t.Error("expected verify to fail on wrong issuer")
}
}
func TestOIDCVerifierRejectsExpired(t *testing.T) {
fk := newFakeAuthentik(t, "anchorage-web")
defer fk.close()
v, _ := auth.NewOIDCVerifier(context.Background(), auth.OIDCVerifierOptions{
Issuer: fk.issuer,
Audience: "anchorage-web",
})
raw := fk.mintIDToken(t, func(c *auth.OIDCClaims) {
c.ExpiresAt = jwt.NewNumericDate(time.Now().Add(-5 * time.Minute))
c.IssuedAt = jwt.NewNumericDate(time.Now().Add(-10 * time.Minute))
})
if _, err := v.Verify(context.Background(), raw); err == nil {
t.Error("expected verify to fail on expired token")
}
}
func TestOIDCVerifierRejectsMissingEmail(t *testing.T) {
fk := newFakeAuthentik(t, "anchorage-web")
defer fk.close()
v, _ := auth.NewOIDCVerifier(context.Background(), auth.OIDCVerifierOptions{
Issuer: fk.issuer,
Audience: "anchorage-web",
})
raw := fk.mintIDToken(t, func(c *auth.OIDCClaims) {
c.Email = ""
})
_, err := v.Verify(context.Background(), raw)
if err == nil {
t.Fatal("expected verify to reject token with empty email")
}
if !strings.Contains(err.Error(), "email") {
t.Errorf("error should mention email; got %v", err)
}
}
func TestNewOIDCVerifierRequiresIssuerAndAudience(t *testing.T) {
if _, err := auth.NewOIDCVerifier(context.Background(), auth.OIDCVerifierOptions{}); err == nil {
t.Error("expected error for empty options")
}
if _, err := auth.NewOIDCVerifier(context.Background(), auth.OIDCVerifierOptions{Issuer: "https://x/"}); err == nil {
t.Error("expected error for missing audience")
}
}
// TestDisplayNameFallbacks locks in the Name → PreferredName → Email
// fallback chain so a user without a configured display_name in
// Authentik still gets a human-readable label in the anchorage UI.
func TestDisplayNameFallbacks(t *testing.T) {
tests := []struct {
in auth.OIDCClaims
want string
}{
{auth.OIDCClaims{Name: "Alice"}, "Alice"},
{auth.OIDCClaims{PreferredName: "alice"}, "alice"},
{auth.OIDCClaims{Email: "alice@example.com"}, "alice@example.com"},
}
for _, tt := range tests {
got := tt.in.DisplayName()
if got != tt.want {
t.Errorf("DisplayName(%+v) = %q, want %q", tt.in, got, tt.want)
}
}
}