Files
tenant-registry/internal/authn/authn.go
T
sharangandSharang Parnerkar 99214c088b
ci / shared (push) Successful in 13s
ci / test (push) Successful in 22m21s
ci / image (push) Successful in 25s
feat(members): tenant organization members, invites, admin email (#28)
Demonstration plan, phase D1 (registry side). The portal's Settings/Users page renders design fixtures today and its "Invite member" button posts to a route that does not exist, because the registry had no membership surface.

**`GET /v1/tenants/{id}/members`** lists the tenant's Keycloak organization members — user id, email, first/last name, `org_roles`, `enabled`, `created_at`. A tenant whose organization was never created (sales-led) answers an empty list rather than an error.

**`POST /v1/tenants/{id}/invites`** `{email, first_name?, last_name?, role?}` creates the Keycloak user if missing, adds the organization member (KC 26: the member body is the bare user id), writes the tenant-context user attributes, sends the same execute-actions mail the first admin gets, and audits `user.invited` with the caller as actor. Idempotent: an existing member answers `200 {status:"member"}` and sends no mail; a new one `202 {status:"invited"}`.

**Scope.** A user token may only touch its own tenant — another tenant's id is a 404, never a hint that it exists. Inviting needs the `IT_ADMIN` or `OWNER` org role, so `Principal` now carries the `org_roles` claim and `IsTenantAdmin()`. Service clients stay gated by `AUTHZ_RULES` route groups: members on `tenants.read`, invites on `tenants.write`.

**`admin_email` on the tenant** (migration `0006`, backfilled from the `keycloak.invite_sent` audit trail, and from `keycloak.provision_failed` metadata where the first invite failed) so Settings can show a real contact instead of an em dash. The first `IT_ADMIN`/`OWNER` invite fills it in when it was empty.

**Routing note worth keeping:** `GET /v1/tenants/{id}/members` cannot be registered — Go's ServeMux calls it a conflict with `GET /v1/tenants/by-slug/{slug}`, since both match `/v1/tenants/by-slug/members` and neither pattern is more specific. It is registered as `GET /v1/tenants/{id}/{sub}` instead, which *is* less specific than the by-slug lookup, so the two coexist; anything but `members` answers 404.

`openapi.yaml` documents both endpoints, the `OrgMember`/`Invite` schemas, `admin_email` and a `Forbidden` response.

Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.3%** (gate 70%).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #28
2026-09-14 08:27:12 +00:00

165 lines
5.5 KiB
Go

// 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"
"encoding/json"
"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
// tenant-context scope claims (present on user tokens; empty on
// client_credentials service tokens).
TenantID string
TenantSlug string
TenantStatus string
Email string
// OrgRoles is the `org_roles` claim (the tenant-context mapper projects
// the Keycloak user attribute of the same name). Empty on service tokens.
OrgRoles []string
}
// IsUser reports whether the token carries a tenant context (a person
// logged in through the portal / a CLI device flow) rather than a service.
func (p *Principal) IsUser() bool { return p != nil && p.TenantID != "" }
// Tenant-admin org roles: the registry seeds IT_ADMIN for the first admin
// (keycloak.CreateOrgAndInvite); OWNER is the portal's owner role. Both may
// manage the tenant's users.
const (
RoleITAdmin = "IT_ADMIN"
RoleOwner = "OWNER"
)
// IsTenantAdmin reports whether a user token carries an org role that may
// administer the tenant (invite users, create API keys). Always false for
// service tokens — those are authorized per client via AUTHZ_RULES instead.
func (p *Principal) IsTenantAdmin() bool {
if !p.IsUser() {
return false
}
for _, r := range p.OrgRoles {
if r == RoleITAdmin || r == RoleOwner {
return true
}
}
return false
}
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"`
TenantID string `json:"tenant_id"`
TenantSlug string `json:"tenant_slug"`
TenantStatus string `json:"tenant_status"`
Email string `json:"email"`
OrgRoles roles `json:"org_roles"`
}
_ = tok.Claims(&claims) // azp is informational; absence is not an error
return &Principal{Subject: tok.Subject, ClientID: claims.Azp, Issuer: tok.Issuer,
TenantID: claims.TenantID, TenantSlug: claims.TenantSlug, TenantStatus: claims.TenantStatus, Email: claims.Email,
OrgRoles: []string(claims.OrgRoles)}, nil
}
// roles decodes the org_roles claim in either shape the Keycloak mapper
// produces: a JSON array when the attribute mapper is multivalued, or a
// single string (possibly "##"- or comma-joined) when it is not.
type roles []string
func (r *roles) UnmarshalJSON(b []byte) error {
var list []string
if err := json.Unmarshal(b, &list); err == nil {
*r = normalizeRoles(list)
return nil
}
var one string
if err := json.Unmarshal(b, &one); err != nil {
*r = nil
return nil // unknown shape: no roles rather than a rejected token
}
*r = normalizeRoles([]string{one})
return nil
}
func normalizeRoles(in []string) []string {
out := []string{}
for _, entry := range in {
for _, v := range strings.FieldsFunc(entry, func(c rune) bool { return c == '#' || c == ',' }) {
if v = strings.TrimSpace(v); v != "" {
out = append(out, v)
}
}
}
return out
}