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

+91
View File
@@ -0,0 +1,91 @@
package token
import (
"errors"
"fmt"
"log/slog"
"os"
"strings"
)
// DevOnlySigningKey is the in-memory fallback anchorage uses when no
// signing keys are configured. It is long enough to satisfy the 32-byte
// minimum but trivially predictable — intentionally so, so operators
// notice the loud warning in logs and replace it.
//
// Never use this key in any environment that touches real data.
const DevOnlySigningKey = "dev-only-do-not-use-in-production-0123456789abcdef"
// readKeyFile reads a key file, strips a trailing newline, and enforces
// the 32-byte minimum. Kept unexported — callers use LoadSigningKeys.
//
// Trailing newline handling means `openssl rand -base64 48 > jwt.key`
// works without ceremony.
func readKeyFile(path string) ([]byte, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read signing key %s: %w", path, err)
}
key := []byte(strings.TrimRight(string(raw), "\r\n"))
if len(key) < 32 {
return nil, errors.New("signing key " + path + " is too short (need >= 32 bytes)")
}
return key, nil
}
// KeyFileSpec names a single signing key file on disk. Mirrors
// config.SigningKeyConfig in a shape the token package can depend on
// without importing config.
type KeyFileSpec struct {
Path string
ID string
Primary bool
}
// LoadSigningKeys validates and loads the rotation key set.
//
// - An empty slice returns a dev-only fallback (kid=DevKeyID, primary)
// with a loud warning so operators notice they haven't configured
// real keys.
// - A non-empty slice is validated (unique non-empty IDs, exactly one
// primary, 32-byte minimum on each file) and returned.
//
// Never returns an empty slice on success.
func LoadSigningKeys(rotation []KeyFileSpec) ([]SigningKey, error) {
if len(rotation) == 0 {
slog.Warn("token: no signing keys configured — using the built-in dev key. DO NOT use in production.")
return []SigningKey{{
ID: DevKeyID,
Key: []byte(DevOnlySigningKey),
Primary: true,
}}, nil
}
out := make([]SigningKey, 0, len(rotation))
seen := map[string]bool{}
primaries := 0
for i, spec := range rotation {
if spec.ID == "" {
return nil, fmt.Errorf("token: signingKeys[%d].id is required", i)
}
if spec.Path == "" {
return nil, fmt.Errorf("token: signingKeys[%d].path is required", i)
}
if seen[spec.ID] {
return nil, fmt.Errorf("token: duplicate signingKey id %q", spec.ID)
}
seen[spec.ID] = true
key, err := readKeyFile(spec.Path)
if err != nil {
return nil, fmt.Errorf("token: signingKeys[%d] (%q): %w", i, spec.ID, err)
}
out = append(out, SigningKey{ID: spec.ID, Key: key, Primary: spec.Primary})
if spec.Primary {
primaries++
}
}
if primaries != 1 {
return nil, fmt.Errorf("token: exactly one signingKey must be marked primary (got %d)", primaries)
}
return out, nil
}
@@ -0,0 +1,115 @@
package token_test
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/token"
)
// TestLoadSigningKeyRoundTrip mirrors the CLI → server handshake:
// an operator runs `anchorage admin mint-token` (which reads the key
// via LoadSigningKeys + NewSigner + Mint), hands the JWT to an IPFS
// client, which then hits a running anchorage whose Signer was built
// from the same config. Both signers must accept the token.
func TestLoadSigningKeyRoundTrip(t *testing.T) {
dir := t.TempDir()
keyPath := filepath.Join(dir, "jwt.key")
// 48-byte key with a trailing newline, matching what
// `openssl rand -base64 48 > jwt.key` writes.
if err := os.WriteFile(keyPath, []byte("0123456789abcdef0123456789abcdef0123456789abcdef\n"), 0o600); err != nil {
t.Fatalf("write key: %v", err)
}
spec := []token.KeyFileSpec{
{ID: "test-kid", Path: keyPath, Primary: true},
}
mintKeys, err := token.LoadSigningKeys(spec)
if err != nil {
t.Fatalf("LoadSigningKeys (mint): %v", err)
}
verifyKeys, err := token.LoadSigningKeys(spec)
if err != nil {
t.Fatalf("LoadSigningKeys (verify): %v", err)
}
mintSigner, err := token.NewSigner(mintKeys, "https://anchorage.test/", "anchorage", nil)
if err != nil {
t.Fatalf("NewSigner (mint): %v", err)
}
jwt, claims, err := mintSigner.Mint(
context.Background(),
ids.MustNewOrg(), ids.MustNewUser(),
"sysadmin", []string{"pin:write"},
365*24*time.Hour+30*24*time.Hour, // 1y + 30d
)
if err != nil {
t.Fatalf("Mint: %v", err)
}
if claims.Role != "sysadmin" {
t.Errorf("claims.Role = %q", claims.Role)
}
verifySigner, err := token.NewSigner(verifyKeys, "https://anchorage.test/", "anchorage", nil)
if err != nil {
t.Fatalf("NewSigner (verify): %v", err)
}
parsed, err := verifySigner.Parse(context.Background(), jwt)
if err != nil {
t.Fatalf("Parse: %v", err)
}
if parsed.ID != claims.ID {
t.Errorf("jti drift: minted=%q parsed=%q", claims.ID, parsed.ID)
}
if parsed.Role != "sysadmin" {
t.Errorf("parsed.Role = %q, want sysadmin", parsed.Role)
}
}
func TestLoadSigningKeysRejectsMissingFile(t *testing.T) {
_, err := token.LoadSigningKeys([]token.KeyFileSpec{
{ID: "x", Path: "/does/not/exist/anywhere", Primary: true},
})
if err == nil {
t.Error("expected error for missing file")
}
}
func TestLoadSigningKeysRejectsShortKey(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "short.key")
_ = os.WriteFile(p, []byte("tooshort"), 0o600)
_, err := token.LoadSigningKeys([]token.KeyFileSpec{
{ID: "x", Path: p, Primary: true},
})
if err == nil {
t.Error("expected error for short key")
}
}
// TestLoadSigningKeysEmptyReturnsDevKey covers the zero-config path —
// no signingKeys entries → built-in dev key with kid=DevKeyID. A loud
// warning fires in logs; tests don't assert on that, just on the shape.
func TestLoadSigningKeysEmptyReturnsDevKey(t *testing.T) {
keys, err := token.LoadSigningKeys(nil)
if err != nil {
t.Fatalf("empty should not error: %v", err)
}
if len(keys) != 1 {
t.Fatalf("want 1 key, got %d", len(keys))
}
if keys[0].ID != token.DevKeyID {
t.Errorf("dev key ID = %q, want %q", keys[0].ID, token.DevKeyID)
}
if !keys[0].Primary {
t.Error("dev key must be marked primary")
}
if string(keys[0].Key) != token.DevOnlySigningKey {
t.Error("dev key bytes drift")
}
}
+267
View File
@@ -0,0 +1,267 @@
package token_test
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
jwtPkg "github.com/golang-jwt/jwt/v5"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/token"
)
// keyBytes produces a deterministic 32-byte key. Using fmt'd values
// rather than crypto/rand keeps the test reproducible.
func keyBytes(seed byte) []byte {
b := make([]byte, 48)
for i := range b {
b[i] = seed
}
return b
}
const (
issuer = "https://anchorage.test/"
aud = "anchorage"
)
// TestRotationOverlap walks the canonical rotation procedure:
//
// 1. Start with signer_A (key_A primary).
// 2. Add key_B as secondary → signer_A+B (A primary, B loaded).
// 3. Flip primary to B → signer_A+B (B primary, A retained).
// 4. Drop key_A → signer_B (only B).
//
// Tokens minted at each stage must keep verifying at least until their
// minting key is dropped, and new mints must use the primary key's
// kid.
func TestRotationOverlap(t *testing.T) {
keyA := keyBytes(0xA0)
keyB := keyBytes(0xB0)
makeSigner := func(t *testing.T, keys []token.SigningKey) *token.Signer {
t.Helper()
s, err := token.NewSigner(keys, issuer, aud, nil)
if err != nil {
t.Fatalf("NewSigner: %v", err)
}
return s
}
mintHere := func(t *testing.T, s *token.Signer) string {
t.Helper()
raw, _, err := s.Mint(context.Background(), ids.MustNewOrg(), ids.MustNewUser(), "member", nil, time.Hour)
if err != nil {
t.Fatalf("Mint: %v", err)
}
return raw
}
parseOK := func(t *testing.T, s *token.Signer, raw, label string) {
t.Helper()
if _, err := s.Parse(context.Background(), raw); err != nil {
t.Errorf("%s should parse: %v", label, err)
}
}
parseFail := func(t *testing.T, s *token.Signer, raw, label string) {
t.Helper()
if _, err := s.Parse(context.Background(), raw); err == nil {
t.Errorf("%s should NOT parse", label)
}
}
// --- stage 1: only A ---
stage1 := makeSigner(t, []token.SigningKey{
{ID: "A", Key: keyA, Primary: true},
})
tokenA := mintHere(t, stage1)
if stage1.PrimaryKeyID() != "A" {
t.Fatalf("stage1 primary = %q", stage1.PrimaryKeyID())
}
// --- stage 2: A primary, B added as secondary ---
stage2 := makeSigner(t, []token.SigningKey{
{ID: "A", Key: keyA, Primary: true},
{ID: "B", Key: keyB},
})
parseOK(t, stage2, tokenA, "stage2: old A-minted token")
tokenA2 := mintHere(t, stage2)
// Both stage2 tokens are still A-minted (primary unchanged).
parseOK(t, stage2, tokenA2, "stage2: new mint still on key A")
// --- stage 3: B primary, A retained ---
stage3 := makeSigner(t, []token.SigningKey{
{ID: "A", Key: keyA},
{ID: "B", Key: keyB, Primary: true},
})
parseOK(t, stage3, tokenA, "stage3: A-era token still verifies")
tokenB := mintHere(t, stage3)
parseOK(t, stage3, tokenB, "stage3: new B-minted token")
if stage3.PrimaryKeyID() != "B" {
t.Fatalf("stage3 primary = %q", stage3.PrimaryKeyID())
}
// --- stage 4: drop A ---
stage4 := makeSigner(t, []token.SigningKey{
{ID: "B", Key: keyB, Primary: true},
})
parseFail(t, stage4, tokenA, "stage4: key A dropped → A-minted tokens rejected")
parseOK(t, stage4, tokenB, "stage4: B-minted still verifies")
}
// TestRotationRejectsUnknownKid confirms an attacker who knows the
// mint algorithm can't trick anchorage into accepting a kid that isn't
// configured. Silent "try all keys" would defeat the whole feature.
func TestRotationRejectsUnknownKid(t *testing.T) {
s, _ := token.NewSigner([]token.SigningKey{
{ID: "real-key", Key: keyBytes(0x11), Primary: true},
}, issuer, aud, nil)
// Mint a token with a signer that happens to use the same bytes but
// a DIFFERENT kid. Verification against the first signer must fail.
attacker, _ := token.NewSigner([]token.SigningKey{
{ID: "attacker-key", Key: keyBytes(0x11), Primary: true},
}, issuer, aud, nil)
raw, _, err := attacker.Mint(context.Background(), ids.MustNewOrg(), ids.MustNewUser(), "sysadmin", nil, time.Hour)
if err != nil {
t.Fatalf("attacker mint: %v", err)
}
_, err = s.Parse(context.Background(), raw)
if err == nil {
t.Fatal("expected unknown-kid token to be rejected")
}
if !strings.Contains(err.Error(), "unknown kid") {
t.Errorf("error should mention unknown kid, got: %v", err)
}
}
// TestRotationRejectsMissingKid confirms that a token without a `kid`
// header is rejected outright. anchorage is new software — there is
// no pre-rotation token population to accept via a fallback.
func TestRotationRejectsMissingKid(t *testing.T) {
s, err := token.NewSigner([]token.SigningKey{
{ID: "A", Key: keyBytes(0xAA), Primary: true},
}, issuer, aud, nil)
if err != nil {
t.Fatalf("NewSigner: %v", err)
}
// Hand-craft a JWT signed with the right bytes but no `kid` header.
raw := jwtNoKid(t, keyBytes(0xAA))
_, err = s.Parse(context.Background(), raw)
if err == nil {
t.Fatal("expected missing-kid token to be rejected")
}
if !strings.Contains(err.Error(), "kid") {
t.Errorf("error should mention kid, got: %v", err)
}
}
// jwtNoKid mints a minimally-valid HS256 JWT without a `kid` header,
// used by TestRotationRejectsMissingKid to prove Parse rejects the
// pre-rotation shape.
func jwtNoKid(t *testing.T, key []byte) string {
t.Helper()
tok := jwtPkg.NewWithClaims(jwtPkg.SigningMethodHS256, &token.Claims{
RegisteredClaims: jwtPkg.RegisteredClaims{
ID: ids.MustNewToken().String(),
Issuer: issuer,
Audience: jwtPkg.ClaimStrings{aud},
IssuedAt: jwtPkg.NewNumericDate(time.Now()),
NotBefore: jwtPkg.NewNumericDate(time.Now()),
ExpiresAt: jwtPkg.NewNumericDate(time.Now().Add(time.Hour)),
},
})
// Deliberately do NOT set tok.Header["kid"].
signed, err := tok.SignedString(key)
if err != nil {
t.Fatalf("sign: %v", err)
}
return signed
}
// TestNewSignerRejectsInvalidConfig covers the validation surface.
func TestNewSignerRejectsInvalidConfig(t *testing.T) {
tests := []struct {
name string
keys []token.SigningKey
}{
{"empty", nil},
{"no-primary", []token.SigningKey{{ID: "A", Key: keyBytes(0xAA)}}},
{"two-primaries", []token.SigningKey{
{ID: "A", Key: keyBytes(0xAA), Primary: true},
{ID: "B", Key: keyBytes(0xBB), Primary: true},
}},
{"duplicate-id", []token.SigningKey{
{ID: "A", Key: keyBytes(0xAA), Primary: true},
{ID: "A", Key: keyBytes(0xBB)},
}},
{"empty-id", []token.SigningKey{
{ID: "", Key: keyBytes(0xAA), Primary: true},
}},
{"short-key", []token.SigningKey{
{ID: "A", Key: []byte("too-short"), Primary: true},
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if _, err := token.NewSigner(tt.keys, issuer, aud, nil); err == nil {
t.Error("expected error")
}
})
}
}
// TestLoadSigningKeysEmptyReturnsDevFallback confirms zero-config runs
// land on the built-in dev key.
func TestLoadSigningKeysEmptyReturnsDevFallback(t *testing.T) {
keys, err := token.LoadSigningKeys(nil)
if err != nil {
t.Fatalf("LoadSigningKeys: %v", err)
}
if len(keys) != 1 || keys[0].ID != token.DevKeyID || !keys[0].Primary {
t.Fatalf("empty load should produce single primary DevKeyID entry, got %+v", keys)
}
}
// TestLoadSigningKeysRotation verifies multi-key loading from config.
func TestLoadSigningKeysRotation(t *testing.T) {
dir := t.TempDir()
writeKey := func(name string, seed byte) string {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, keyBytes(seed), 0o600); err != nil {
t.Fatalf("write %s: %v", name, err)
}
return p
}
pathA := writeKey("jwt.a.key", 0xAA)
pathB := writeKey("jwt.b.key", 0xBB)
keys, err := token.LoadSigningKeys([]token.KeyFileSpec{
{ID: "2025-10", Path: pathA},
{ID: "2026-04", Path: pathB, Primary: true},
})
if err != nil {
t.Fatalf("LoadSigningKeys: %v", err)
}
if len(keys) != 2 {
t.Fatalf("want 2 keys, got %d", len(keys))
}
if keys[1].ID != "2026-04" || !keys[1].Primary {
t.Errorf("primary entry mis-marked: %+v", keys)
}
}
// TestLoadSigningKeysRejectsNoPrimary makes sure a malformed config
// can't silently produce a signer that can't mint.
func TestLoadSigningKeysRejectsNoPrimary(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "k")
_ = os.WriteFile(p, keyBytes(0x55), 0o600)
if _, err := token.LoadSigningKeys([]token.KeyFileSpec{
{ID: "A", Path: p}, {ID: "B", Path: p},
}); err == nil {
t.Error("expected error when no primary is set")
}
}
+295
View File
@@ -0,0 +1,295 @@
// Package token mints and verifies anchorage API tokens.
//
// Tokens are short-lived JWTs signed with a symmetric HMAC key at v1
// (the plan leaves ed25519/RS256 as a future open item). The jti claim
// is a TypeID (tok_*) so revocation, logs, and audit rows can reference
// it directly.
//
// Every token carries a `kid` header that names the key that signed
// it. Tokens without a `kid` are rejected — anchorage is new software
// so there is no pre-rotation token population to carry forward.
//
// Rotation: Signer accepts multiple keys. Exactly one is flagged as
// Primary — Mint always signs with it and puts its ID in the JWT
// `kid` header. Parse reads `kid` and picks the matching key from the
// full set, so tokens signed with a retiring key keep verifying while
// the retiring key is still loaded. See deploy/README.md for the
// operational procedure.
package token
import (
"context"
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/store"
)
// DevKeyID is the stable kid used by the built-in dev-fallback key.
// It appears ONLY when the operator has not configured any keys and
// anchorage is running against its insecure dev default — the loud
// warning in LoadSigningKeys fires then. Never assume a token with
// kid=DevKeyID is legitimate outside a local dev environment.
const DevKeyID = "dev"
// Claims is anchorage's JWT payload.
type Claims struct {
Org ids.OrgID `json:"org"`
User ids.UserID `json:"sub_id"`
Role string `json:"role"`
Scopes []string `json:"scopes,omitempty"`
jwt.RegisteredClaims
}
// SigningKey binds an HMAC key to a stable identifier. Exactly one key
// in a Signer's set is flagged Primary — it's the one Mint uses.
type SigningKey struct {
// ID is the stable label emitted as the JWT `kid` header and used
// by Parse to look up which key verified a given token. Treat like
// a version tag: "2026-04", "prod-v2", anything stable.
ID string
// Key is the raw HMAC bytes (>= 32 bytes).
Key []byte
// Primary marks the key used for minting. Exactly one key in the
// set must have this set.
Primary bool
}
// DenyCache is the minimal surface the Signer needs from a cache layer
// to speed up denylist lookups. *cache.Cache[string,bool] satisfies it
// implicitly; tests can also pass a fake. nil = no caching, every
// Parse hits the TokenStore.
type DenyCache interface {
Get(key string) (bool, bool)
Set(key string, v bool, cost int64, ttl time.Duration) bool
Delete(key string)
}
// Signer mints + parses JWTs and checks the Postgres-backed denylist.
type Signer struct {
keys map[string][]byte
primaryID string
issuer string
audience string
tokens store.TokenStore
// denyCache is an optional jti → isDenied short-TTL cache. Cuts
// the per-authenticated-request DB hit for the 99.99% of tokens
// that aren't revoked. Cross-node invalidation is the caller's
// responsibility — typically via cache.WatchEntity("token", cache.Delete).
denyCache DenyCache
onRevoke RevokeHook
}
// SetDenyCache attaches a cache implementation for denylist lookups.
// Safe to call once at construction time before the Signer starts
// serving requests; not safe to swap at runtime.
func (s *Signer) SetDenyCache(c DenyCache) { s.denyCache = c }
// RevokeHook is called with the revoked jti after every successful
// Revoke. Typical hook publishes a NATS `cache.invalidate.token.<jti>`
// so peer nodes drop their local denylist cache entries.
type RevokeHook func(jti string)
// SetRevokeHook installs a post-Revoke callback. Nil to clear.
func (s *Signer) SetRevokeHook(h RevokeHook) { s.onRevoke = h }
// NewSigner constructs a Signer with one or more keys for overlap-style
// rotation. Exactly one key must be flagged Primary; all IDs must be
// unique and non-empty; all keys must be >= 32 bytes.
func NewSigner(keys []SigningKey, issuer, audience string, tokens store.TokenStore) (*Signer, error) {
if len(keys) == 0 {
return nil, errors.New("token: at least one signing key is required")
}
s := &Signer{
keys: make(map[string][]byte, len(keys)),
issuer: issuer,
audience: audience,
tokens: tokens,
}
for _, k := range keys {
if k.ID == "" {
return nil, errors.New("token: SigningKey.ID must not be empty")
}
if _, dup := s.keys[k.ID]; dup {
return nil, fmt.Errorf("token: duplicate kid %q", k.ID)
}
if len(k.Key) < 32 {
return nil, fmt.Errorf("token: key %q is too short (need >= 32 bytes)", k.ID)
}
s.keys[k.ID] = k.Key
if k.Primary {
if s.primaryID != "" {
return nil, fmt.Errorf("token: multiple primary keys (%q and %q)", s.primaryID, k.ID)
}
s.primaryID = k.ID
}
}
if s.primaryID == "" {
return nil, errors.New("token: exactly one key must be flagged Primary")
}
return s, nil
}
// PrimaryKeyID returns the kid of the current minting key. Useful for
// tests and for the admin rotation CLI.
func (s *Signer) PrimaryKeyID() string { return s.primaryID }
// AcceptsKey reports whether kid would verify incoming tokens.
func (s *Signer) AcceptsKey(kid string) bool {
_, ok := s.keys[kid]
return ok
}
// Mint signs a new JWT with the given claims. jti is generated if empty;
// ttl <= 0 falls back to 24h. The primary key's ID is written into the
// JWT `kid` header.
func (s *Signer) Mint(ctx context.Context, orgID ids.OrgID, userID ids.UserID, role string, scopes []string, ttl time.Duration) (string, *Claims, error) {
if ttl <= 0 {
ttl = 24 * time.Hour
}
jti, err := ids.NewToken()
if err != nil {
return "", nil, err
}
now := time.Now().UTC()
c := &Claims{
Org: orgID,
User: userID,
Role: role,
Scopes: scopes,
RegisteredClaims: jwt.RegisteredClaims{
ID: jti.String(),
Issuer: s.issuer,
Audience: jwt.ClaimStrings{s.audience},
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
NotBefore: jwt.NewNumericDate(now),
},
}
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
tok.Header["kid"] = s.primaryID
signed, err := tok.SignedString(s.keys[s.primaryID])
if err != nil {
return "", nil, fmt.Errorf("sign jwt: %w", err)
}
return signed, c, nil
}
// Parse validates the JWT signature, expiry, and denylist status.
//
// The verifying key is chosen by the token's `kid` header. Tokens
// without a `kid`, or pointing at a kid that isn't loaded in this
// Signer's key set, are rejected — silently trying every key would
// defeat the point of rotation.
func (s *Signer) Parse(ctx context.Context, raw string) (*Claims, error) {
c := &Claims{}
tok, err := jwt.ParseWithClaims(raw, c, s.keyfunc,
jwt.WithAudience(s.audience),
jwt.WithIssuer(s.issuer),
)
if err != nil {
return nil, err
}
if !tok.Valid {
return nil, errors.New("token: invalid")
}
if c.ID == "" {
return nil, errors.New("token: missing jti")
}
jti, err := ids.ParseToken(c.ID)
if err != nil {
return nil, fmt.Errorf("token: parse jti: %w", err)
}
if s.tokens != nil {
denied, err := s.isDeniedCached(ctx, jti)
if err != nil {
return nil, fmt.Errorf("token: denylist check: %w", err)
}
if denied {
return nil, errors.New("token: revoked")
}
}
return c, nil
}
// isDeniedCached wraps TokenStore.IsDenied with a short-TTL cache
// keyed on the jti string. 5 minutes strikes a balance: a freshly
// revoked jti stops verifying within (at most) 5 minutes without
// explicit invalidation, but cross-node invalidation via
// cache.invalidate.token.<jti> usually drops stale entries within
// one NATS RTT.
//
// Both true and false outcomes are cached. A false (not-denied) hit
// is the common case and the reason this cache exists; a true hit
// still short-circuits the DB call until TTL expires.
func (s *Signer) isDeniedCached(ctx context.Context, jti ids.TokenID) (bool, error) {
key := jti.String()
if s.denyCache != nil {
if v, ok := s.denyCache.Get(key); ok {
return v, nil
}
}
denied, err := s.tokens.IsDenied(ctx, jti)
if err != nil {
return false, err
}
if s.denyCache != nil {
s.denyCache.Set(key, denied, 1, 5*time.Minute)
}
return denied, nil
}
// keyfunc selects the HMAC key matching the token's kid. Kept as a
// method (not a closure inside Parse) for testability + clarity.
func (s *Signer) keyfunc(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method %q", t.Header["alg"])
}
kid, _ := t.Header["kid"].(string)
if kid == "" {
return nil, errors.New("token: missing kid header")
}
key, ok := s.keys[kid]
if !ok {
return nil, fmt.Errorf("token: unknown kid %q", kid)
}
return key, nil
}
// Revoke marks the jti as denied until its natural expiry. Idempotent.
// Drops the local cache entry immediately so the revoking node sees
// the change without waiting for TTL; cross-node consistency is the
// caller's responsibility — typically via cache.Invalidator.Emit on
// the "token" entity, which other nodes pick up through
// cache.WatchEntity subscribers that call s.InvalidateDenyCache.
func (s *Signer) Revoke(ctx context.Context, jti ids.TokenID, expiresAt time.Time, reason string) error {
if s.tokens == nil {
return nil
}
if err := s.tokens.Revoke(ctx, jti); err != nil && !errors.Is(err, store.ErrNotFound) {
return err
}
if err := s.tokens.AddDenylist(ctx, jti, expiresAt, reason); err != nil {
return err
}
s.InvalidateDenyCache(jti.String())
if s.onRevoke != nil {
s.onRevoke(jti.String())
}
return nil
}
// InvalidateDenyCache drops a single jti from the local denylist cache.
// Exported so the cross-node invalidation subscriber (see
// internal/pkg/cache.WatchEntity) can plug into the Signer without
// reaching into unexported state. A no-op when no cache is attached.
func (s *Signer) InvalidateDenyCache(jti string) {
if s.denyCache == nil {
return
}
s.denyCache.Delete(jti)
}
+105
View File
@@ -0,0 +1,105 @@
package token_test
import (
"context"
"testing"
"time"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/store"
"anchorage/internal/pkg/store/memstore"
"anchorage/internal/pkg/token"
)
func newSigner(t *testing.T) (*token.Signer, *memstore.Store) {
t.Helper()
s := memstore.New()
sg, err := token.NewSigner(
[]token.SigningKey{{
ID: "test-kid",
Key: []byte("0123456789abcdef0123456789abcdef"),
Primary: true,
}},
"https://anchorage.test/",
"anchorage",
s.Tokens(),
)
if err != nil {
t.Fatalf("NewSigner: %v", err)
}
return sg, s
}
func TestMintAndParseRoundTrip(t *testing.T) {
sg, _ := newSigner(t)
orgID := ids.MustNewOrg()
userID := ids.MustNewUser()
raw, claims, err := sg.Mint(context.Background(), orgID, userID, "orgadmin", []string{"pin:write"}, time.Hour)
if err != nil {
t.Fatalf("Mint: %v", err)
}
if claims.Org != orgID || claims.User != userID {
t.Errorf("claims org/user mismatch")
}
if claims.Role != "orgadmin" {
t.Errorf("role = %q", claims.Role)
}
parsed, err := sg.Parse(context.Background(), raw)
if err != nil {
t.Fatalf("Parse: %v", err)
}
if parsed.Org != orgID {
t.Errorf("parsed.Org = %v", parsed.Org)
}
if parsed.ID != claims.ID {
t.Errorf("jti changed during round-trip")
}
}
func TestParseRejectsExpired(t *testing.T) {
sg, _ := newSigner(t)
raw, _, err := sg.Mint(context.Background(), ids.MustNewOrg(), ids.MustNewUser(), "member", nil, time.Millisecond)
if err != nil {
t.Fatalf("Mint: %v", err)
}
time.Sleep(10 * time.Millisecond)
if _, err := sg.Parse(context.Background(), raw); err == nil {
t.Error("expected expired token to be rejected")
}
}
func TestRevokeAddsToDenylist(t *testing.T) {
sg, s := newSigner(t)
raw, claims, err := sg.Mint(context.Background(), ids.MustNewOrg(), ids.MustNewUser(), "member", nil, time.Hour)
if err != nil {
t.Fatalf("Mint: %v", err)
}
// Write the token metadata to the store so Revoke has something to update.
if err := s.Tokens().Create(context.Background(), &store.APIToken{
JTI: mustParseToken(t, claims.ID), OrgID: claims.Org, UserID: claims.User,
Label: "test", ExpiresAt: claims.ExpiresAt.Time,
}); err != nil {
t.Fatalf("seed token: %v", err)
}
jti := mustParseToken(t, claims.ID)
if err := sg.Revoke(context.Background(), jti, claims.ExpiresAt.Time, "test"); err != nil {
t.Fatalf("Revoke: %v", err)
}
if _, err := sg.Parse(context.Background(), raw); err == nil {
t.Error("expected revoked token to be rejected")
}
}
func mustParseToken(t *testing.T, s string) ids.TokenID {
t.Helper()
id, err := ids.ParseToken(s)
if err != nil {
t.Fatalf("ParseToken(%q): %v", s, err)
}
return id
}