Files
tenant-registry/internal/keycloak/users.go
T
Sharang ParnerkarandClaude Fable 5 4a49c630d4
ci / shared (pull_request) Failing after 12s
ci / test (pull_request) Successful in 21m20s
ci / image (pull_request) Skipped
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>
2026-08-24 16:09:53 +02:00

75 lines
2.2 KiB
Go

package keycloak
import (
"context"
"fmt"
"net/http"
"strings"
)
// userRepresentation is the slice of the Admin API's UserRepresentation we
// need. Attributes arrive as map[name][]values; the KC admin console writes
// multivalued attributes either as separate list entries or as one entry
// joined with "##", so both shapes must be accepted.
type userRepresentation struct {
ID string `json:"id"`
Username string `json:"username"`
Enabled bool `json:"enabled"`
Attributes map[string][]string `json:"attributes"`
}
// Memberships implements Adapter against GET /admin/realms/{realm}/users/{id}.
func (a *HTTPAdapter) Memberships(ctx context.Context, userID string) ([]Claims, error) {
var u userRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+userID, nil, &u)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusNotFound {
_ = resp.Body.Close()
return nil, ErrUserNotFound
}
if resp.StatusCode/100 != 2 {
_ = resp.Body.Close()
return nil, fmt.Errorf("keycloak get user: %d", resp.StatusCode)
}
return claimsFromAttributes(u.Attributes), nil
}
// claimsFromAttributes builds the membership list from a user's attribute
// projection. A user with no tenant_id and no tenant_slug attribute simply
// has no memberships — that is a valid state, not an error.
func claimsFromAttributes(attrs map[string][]string) []Claims {
c := Claims{
TenantID: attrValue(attrs, "tenant_id"),
TenantSlug: attrValue(attrs, "tenant_slug"),
OrgRoles: attrValues(attrs, "org_roles"),
Products: attrValues(attrs, "products"),
Plan: attrValue(attrs, "plan"),
TenantStatus: attrValue(attrs, "tenant_status"),
}
if c.TenantID == "" && c.TenantSlug == "" {
return []Claims{}
}
return []Claims{c}
}
func attrValue(attrs map[string][]string, key string) string {
if vs := attrValues(attrs, key); len(vs) > 0 {
return vs[0]
}
return ""
}
func attrValues(attrs map[string][]string, key string) []string {
out := []string{}
for _, entry := range attrs[key] {
for _, v := range strings.Split(entry, "##") {
if v = strings.TrimSpace(v); v != "" {
out = append(out, v)
}
}
}
return out
}