Files
iam/pkg/schema/membership.go
zeekayandHanzo Dev 54d5e32ac2 store: Prepare keys every unkeyed user and membership on every open; NameKey is read-only in the schema
v1.34.136 keyed old rows only from store.Open, once per store, and a host that opens the store its own way never ran it, so a legacy "Alice" was invisible to the fold lookup and "alice" could register beside it. Prepare runs on every open (store.Open, server.OpenSQLite, and any host's own open path calls it), finds unkeyed rows by the field's absence through its index (orm v0.6.42), and keys each in a transaction that reads it again first, so a racing write is kept. A rollback that unkeys rows is undone at the next open. The one-shot migrations kind is gone. NameKey is a schema.Folded, always written and published readOnly.

Co-authored-by: Hanzo Dev <[email protected]>
2026-10-02 22:25:48 -07:00

117 lines
4.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package schema
import (
"strings"
"github.com/hanzoai/orm"
)
// Membership records that a user may ACT IN an org — the (User × Org × Role)
// relation that lets ONE identity belong to its personal org AND to team orgs.
// It is the tenancy set a token emits as the `orgs` claim, against which the
// edge authorizes an org-switch (X-Org-Id ∈ orgs) with no round-trip.
//
// It is orthogonal to the Role/Permission catalog: Membership answers "which
// orgs may this identity act in, and with what COARSE role", while
// Role/Permission answer fine-grained authorization WITHIN an org. A user's HOME
// org (User.Owner) is always an implicit membership; explicit rows add the team
// orgs the user was invited into.
//
// Like every tenant-registry row it is owned by the platform ("admin"); the
// natural key (Owner, Name) uses Name = "<userId>|<org>", so a (user, org) pair
// is unique by construction and Ensure is idempotent without a read-modify-write
// race. The User and Org columns are the hot lookup paths and stay indexed.
type Membership struct {
orm.Model[Membership]
Owner string `json:"owner"`
Name string `json:"name"`
CreatedTime string `json:"createdTime"`
// The SUBJECT. Exactly one of these is set: a person, or a team of them.
// Granting to a team keeps access correct as people come and go.
User string `json:"user" orm:"index"` // the user id, "<homeOrg>/<username>"
Team string `json:"team" orm:"index"` // the team name, owner-scoped by Org
// NameKey is Fold of User's username half, derived on every save and on every
// open for a row saved without it (store.Prepare): the indexed key that finds an
// org's member by name (store.MemberByIdentifier). Always written.
NameKey Folded `json:"nameKey" orm:"index"`
// The SCOPE. Org is the tenant and is always set. Workspace narrows the grant
// to one workspace inside it; Project narrows it further, and requires
// Workspace. Empty means the whole of the level above, so a row with neither
// is an org-wide grant.
//
// The scope lives here rather than on the team because a team is a set of
// people and nothing else: the same team holds different roles in different
// places, and braiding the two would need one team per scope.
Org string `json:"org" orm:"index"`
Workspace string `json:"workspace" orm:"index"`
Project string `json:"project" orm:"index"`
Role string `json:"role"` // owner | admin | member
// Invitation is the name of the invitation, in Org, the member joined by; ""
// for a grant nobody was invited to.
Invitation string `json:"invitation"`
}
// OrgRef is the lightweight (org, role) projection of a Membership that a token
// carries in its `orgs` claim — the tenancy set a resource server reads to
// authorize an org-switch (X-Org-Id ∈ orgs) with no round-trip. It is the bind
// value ONLY (no storage identity, no orm.Model): Membership is how the relation
// is stored, OrgRef is how it travels in a JWT and how a consumer (cloud's
// SanitizeIdentity) decodes it. The JSON tags (`org`, `role,omitempty`) are the
// fixed claim contract — a token minted here and read by a consumer round-trips
// byte-for-byte. It is exported to consumers as model.OrgRef (pkg/model), the ONE
// place external services import it from; there is no second copy.
type OrgRef struct {
Org string `json:"org"`
Role string `json:"role,omitempty"`
}
// AsOrgRef projects a Membership onto its claim-side (org, role) reference — the
// ONE way to turn a stored membership into the value a token emits.
func (m *Membership) AsOrgRef() OrgRef {
return OrgRef{Org: m.Org, Role: m.Role}
}
// OrgRefsFromMemberships projects a membership set onto the `orgs` claim slice a
// token carries. A nil/empty set yields a nil slice so the claim is omitted, not
// emitted empty.
func OrgRefsFromMemberships(ms []*Membership) []OrgRef {
if len(ms) == 0 {
return nil
}
out := make([]OrgRef, 0, len(ms))
for _, m := range ms {
if m != nil {
out = append(out, m.AsOrgRef())
}
}
return out
}
// BeforeCreate and BeforeUpdate derive NameKey from User's username half on every
// save the model makes.
func (m *Membership) BeforeCreate() error {
m.NameKey = MemberKey(m.User)
return nil
}
// BeforeUpdate is BeforeCreate for a save of an existing membership.
func (m *Membership) BeforeUpdate(*Membership) error {
m.NameKey = MemberKey(m.User)
return nil
}
// MemberKey is the NameKey of a membership held by the user id "<home>/<name>".
func MemberKey(user string) Folded {
_, name, _ := strings.Cut(user, "/")
return Folded(Fold(name))
}