feat(auth): membership authority endpoint + fail-closed API auth (RBAC Phase 1)
ci / shared (pull_request) Failing after 12s
ci / test (pull_request) Successful in 21m20s
ci / image (pull_request) Skipped

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:
Sharang Parnerkar
2026-08-24 16:09:53 +02:00
co-authored by Claude Fable 5
parent 31cb06cf3d
commit 4a49c630d4
14 changed files with 797 additions and 7 deletions
+106
View File
@@ -0,0 +1,106 @@
package keycloak
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
// stubUsersKC is a users-endpoint-only KC look-alike; stubKC (client_test.go)
// covers the org/invite paths and doesn't register GET /users/{id}.
func stubUsersKC(t *testing.T, users map[string]userRepresentation) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "test-token", "expires_in": 60})
})
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
u, ok := users[r.PathValue("id")]
if !ok {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"User not found"}`))
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(u)
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func usersAdapter(srv *httptest.Server) *HTTPAdapter {
return NewHTTPAdapter(HTTPConfig{
BaseURL: srv.URL, Realm: "test-realm", ClientID: "svc", ClientSecret: "secret",
})
}
func TestHTTPAdapter_Memberships(t *testing.T) {
srv := stubUsersKC(t, map[string]userRepresentation{
"u-1": {ID: "u-1", Username: "test@breakpilot.com", Enabled: true, Attributes: map[string][]string{
"tenant_id": {"acme-001"},
"tenant_slug": {"acme"},
"tenant_status": {"active"},
"plan": {"Scale"},
"org_roles": {"IT_ADMIN", "FINANCE"},
// the KC admin console writes multivalued attrs "##"-joined
"products": {"compliance##certifai"},
}},
"u-2": {ID: "u-2", Username: "bare@breakpilot.com", Enabled: true},
})
a := usersAdapter(srv)
t.Run("attribute projection becomes one membership", func(t *testing.T) {
got, err := a.Memberships(context.Background(), "u-1")
if err != nil {
t.Fatalf("memberships: %v", err)
}
if len(got) != 1 {
t.Fatalf("want 1 membership, got %d", len(got))
}
c := got[0]
if c.TenantID != "acme-001" || c.TenantSlug != "acme" || c.Plan != "Scale" || c.TenantStatus != "active" {
t.Errorf("scalar claims wrong: %+v", c)
}
if len(c.OrgRoles) != 2 || c.OrgRoles[0] != "IT_ADMIN" || c.OrgRoles[1] != "FINANCE" {
t.Errorf("org_roles wrong: %v", c.OrgRoles)
}
if len(c.Products) != 2 || c.Products[0] != "compliance" || c.Products[1] != "certifai" {
t.Errorf("## split failed: %v", c.Products)
}
})
t.Run("user without tenant attributes has zero memberships", func(t *testing.T) {
got, err := a.Memberships(context.Background(), "u-2")
if err != nil {
t.Fatalf("memberships: %v", err)
}
if len(got) != 0 {
t.Fatalf("want 0 memberships, got %+v", got)
}
})
t.Run("unknown user is ErrUserNotFound", func(t *testing.T) {
_, err := a.Memberships(context.Background(), "nope")
if !errors.Is(err, ErrUserNotFound) {
t.Fatalf("want ErrUserNotFound, got %v", err)
}
})
}
func TestMock_Memberships(t *testing.T) {
m := NewMock()
if _, err := m.Memberships(context.Background(), "ghost"); !errors.Is(err, ErrUserNotFound) {
t.Fatalf("want ErrUserNotFound, got %v", err)
}
want := Claims{TenantSlug: "acme", OrgRoles: []string{"IT_ADMIN"}}
m.Claims["u-1"] = want
got, err := m.Memberships(context.Background(), "u-1")
if err != nil || len(got) != 1 || got[0].TenantSlug != "acme" {
t.Fatalf("got %+v err %v", got, err)
}
}