feat(auth): membership authority endpoint + fail-closed API auth (RBAC Phase 1)
GET /v1/users/{id}/memberships answers 'which tenants does this JWT
subject belong to, with which org_roles and entitlements' (ratified
auth design, model B2). Keycloak supplies user->tenant links and roles
via the Adapter (attribute projection until the realm migrates to
Organizations); registered tenants override status/plan/products from
registry tables.
New internal/authn verifies Keycloak bearer tokens (OIDC discovery +
JWKS, audience AUTH_EXPECTED_AUDIENCE, default tenant-registry). With
AUTH_ENABLED=true all routes except /healthz + /readyz require a token
and the server refuses to start if the verifier cannot initialize;
false (dev default) keeps the API open. Completes the M5.2-deferred
org_roles lookup and replaces the 'M4.3 adds JWT validation' TODO in
the spec.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
31cb06cf3d
commit
4a49c630d4
@@ -0,0 +1,88 @@
|
||||
// Package authn validates Keycloak-issued bearer tokens for the
|
||||
// tenant-registry API (RBAC rollout Phase 1; fail-closed per the ratified
|
||||
// compliance auth design, model B2).
|
||||
//
|
||||
// The package only verifies — issuer, signature via JWKS, expiry, and
|
||||
// audience. It deliberately does not authorize: tenant-registry IS the
|
||||
// membership authority, so its callers are services (INTERNAL_SERVICE_ONLY
|
||||
// posture) holding client_credentials tokens whose audience includes
|
||||
// AUTH_EXPECTED_AUDIENCE.
|
||||
package authn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
)
|
||||
|
||||
// ErrNoToken means the Authorization header was absent or not a Bearer
|
||||
// scheme. Handlers map it to 401 TOKEN_MISSING.
|
||||
var ErrNoToken = errors.New("authorization header missing or not Bearer")
|
||||
|
||||
// Principal is the verified caller identity, placed in the request context
|
||||
// so handlers (and, later, audit writes) can attribute actions.
|
||||
type Principal struct {
|
||||
Subject string // JWT sub — the Keycloak user or service-account id
|
||||
ClientID string // JWT azp — which OAuth client obtained the token
|
||||
Issuer string
|
||||
}
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// WithPrincipal returns ctx carrying p.
|
||||
func WithPrincipal(ctx context.Context, p *Principal) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, p)
|
||||
}
|
||||
|
||||
// PrincipalFrom extracts the verified principal, if any.
|
||||
func PrincipalFrom(ctx context.Context) (*Principal, bool) {
|
||||
p, ok := ctx.Value(ctxKey{}).(*Principal)
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// Verifier checks bearer tokens against one issuer + audience. A nil
|
||||
// *Verifier means auth is disabled (AUTH_ENABLED=false) and the server
|
||||
// passes requests through unauthenticated.
|
||||
type Verifier struct {
|
||||
issuer string
|
||||
verifier *oidc.IDTokenVerifier
|
||||
}
|
||||
|
||||
// New performs OIDC discovery against issuer and prepares JWKS-backed
|
||||
// verification. Callers must treat an error as fatal when AUTH_ENABLED=true
|
||||
// (AUTH_CONFIG_INCOMPLETE — refuse to start, never fall open).
|
||||
func New(ctx context.Context, issuer, audience string) (*Verifier, error) {
|
||||
if issuer == "" || audience == "" {
|
||||
return nil, errors.New("issuer and audience are required")
|
||||
}
|
||||
provider, err := oidc.NewProvider(ctx, issuer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("oidc discovery for %s: %w", issuer, err)
|
||||
}
|
||||
return &Verifier{
|
||||
issuer: issuer,
|
||||
verifier: provider.Verifier(&oidc.Config{ClientID: audience}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Verify checks the raw Authorization header value and returns the caller
|
||||
// principal. Signature, issuer, expiry, and audience are all enforced by
|
||||
// the underlying oidc verifier.
|
||||
func (v *Verifier) Verify(ctx context.Context, authorization string) (*Principal, error) {
|
||||
raw, ok := strings.CutPrefix(authorization, "Bearer ")
|
||||
if !ok || strings.TrimSpace(raw) == "" {
|
||||
return nil, ErrNoToken
|
||||
}
|
||||
tok, err := v.verifier.Verify(ctx, strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var claims struct {
|
||||
Azp string `json:"azp"`
|
||||
}
|
||||
_ = tok.Claims(&claims) // azp is informational; absence is not an error
|
||||
return &Principal{Subject: tok.Subject, ClientID: claims.Azp, Issuer: tok.Issuer}, nil
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package authn_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
jose "github.com/go-jose/go-jose/v4"
|
||||
|
||||
"gitea.meghsakha.com/platform/tenant-registry/internal/authn"
|
||||
"gitea.meghsakha.com/platform/tenant-registry/internal/config"
|
||||
"gitea.meghsakha.com/platform/tenant-registry/internal/keycloak"
|
||||
"gitea.meghsakha.com/platform/tenant-registry/internal/server"
|
||||
"gitea.meghsakha.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// stubIssuer is a minimal OIDC issuer: discovery + JWKS + an RS256 signer.
|
||||
type stubIssuer struct {
|
||||
URL string
|
||||
key *rsa.PrivateKey
|
||||
sign func(t *testing.T, claims map[string]any) string
|
||||
}
|
||||
|
||||
func newStubIssuer(t *testing.T) *stubIssuer {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &stubIssuer{key: key}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"issuer": s.URL,
|
||||
"jwks_uri": s.URL + "/jwks",
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/jwks", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{
|
||||
{Key: key.Public(), KeyID: "test-kid", Algorithm: "RS256", Use: "sig"},
|
||||
}})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
s.URL = srv.URL
|
||||
|
||||
signer, err := jose.NewSigner(
|
||||
jose.SigningKey{Algorithm: jose.RS256, Key: key},
|
||||
(&jose.SignerOptions{}).WithHeader("kid", "test-kid"),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.sign = func(t *testing.T, claims map[string]any) string {
|
||||
t.Helper()
|
||||
payload, _ := json.Marshal(claims)
|
||||
jws, err := signer.Sign(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := jws.CompactSerialize()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *stubIssuer) claims(overrides map[string]any) map[string]any {
|
||||
c := map[string]any{
|
||||
"iss": s.URL,
|
||||
"aud": "tenant-registry",
|
||||
"sub": "svc-account-1",
|
||||
"azp": "compliance-svc",
|
||||
"exp": time.Now().Add(5 * time.Minute).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
}
|
||||
for k, v := range overrides {
|
||||
c[k] = v
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func TestVerifier(t *testing.T) {
|
||||
iss := newStubIssuer(t)
|
||||
v, err := authn.New(context.Background(), iss.URL, "tenant-registry")
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("valid token yields principal", func(t *testing.T) {
|
||||
p, err := v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(nil)))
|
||||
if err != nil {
|
||||
t.Fatalf("verify: %v", err)
|
||||
}
|
||||
if p.Subject != "svc-account-1" || p.ClientID != "compliance-svc" || p.Issuer != iss.URL {
|
||||
t.Errorf("principal wrong: %+v", p)
|
||||
}
|
||||
})
|
||||
|
||||
fail := func(name, header string) {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := v.Verify(ctx, header); err == nil {
|
||||
t.Fatal("expected verification failure")
|
||||
}
|
||||
})
|
||||
}
|
||||
fail("missing header", "")
|
||||
fail("not bearer", "Basic abc")
|
||||
fail("garbage token", "Bearer not.a.jwt")
|
||||
fail("expired", "Bearer "+iss.sign(t, iss.claims(map[string]any{"exp": time.Now().Add(-time.Minute).Unix()})))
|
||||
fail("wrong audience", "Bearer "+iss.sign(t, iss.claims(map[string]any{"aud": "someone-else"})))
|
||||
fail("wrong issuer", "Bearer "+iss.sign(t, iss.claims(map[string]any{"iss": "https://evil.example"})))
|
||||
|
||||
t.Run("missing header is ErrNoToken", func(t *testing.T) {
|
||||
if _, err := v.Verify(ctx, ""); err != authn.ErrNoToken {
|
||||
t.Fatalf("want ErrNoToken, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNew_failsClosed(t *testing.T) {
|
||||
if _, err := authn.New(context.Background(), "", "aud"); err == nil {
|
||||
t.Fatal("empty issuer must error")
|
||||
}
|
||||
if _, err := authn.New(context.Background(), "http://127.0.0.1:1/realms/none", "aud"); err == nil {
|
||||
t.Fatal("unreachable issuer must error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterGating proves the wiring: health stays PUBLIC_EXPLICIT, every
|
||||
// API route fails closed without a token, and a valid service token passes.
|
||||
func TestRouterGating(t *testing.T) {
|
||||
iss := newStubIssuer(t)
|
||||
v, err := authn.New(context.Background(), iss.URL, "tenant-registry")
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
handler := server.NewRouter(&server.Server{
|
||||
Cfg: &config.Config{Env: "dev"},
|
||||
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
Store: store.NewMemory(),
|
||||
Keycloak: keycloak.NewMock(),
|
||||
Auth: v,
|
||||
})
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
get := func(t *testing.T, path, authz string) (int, string) {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest(http.MethodGet, srv.URL+path, nil)
|
||||
if authz != "" {
|
||||
req.Header.Set("Authorization", authz)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(raw)
|
||||
}
|
||||
|
||||
if code, _ := get(t, "/healthz", ""); code != http.StatusOK {
|
||||
t.Errorf("healthz must stay public, got %d", code)
|
||||
}
|
||||
if code, body := get(t, "/v1/catalog", ""); code != http.StatusUnauthorized || !strings.Contains(body, "TOKEN_MISSING") {
|
||||
t.Errorf("no token: want 401 TOKEN_MISSING, got %d %s", code, body)
|
||||
}
|
||||
if code, body := get(t, "/v1/catalog", "Bearer junk"); code != http.StatusUnauthorized || !strings.Contains(body, "TOKEN_INVALID") {
|
||||
t.Errorf("bad token: want 401 TOKEN_INVALID, got %d %s", code, body)
|
||||
}
|
||||
if code, _ := get(t, "/v1/catalog", "Bearer "+iss.sign(t, iss.claims(nil))); code != http.StatusOK {
|
||||
t.Errorf("valid token: want 200, got %d", code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user