mirror of
https://github.com/hanzoai/iam.git
synced 2026-11-19 18:37:16 +00:00
POST /v1/iam/users and PUT /v1/iam/users/{owner}/{name} answered 200 and
dropped user.isAdmin: the field was read from the calling code only, so a
SuperAdmin could not make hanzo/denis an admin and nothing said so.
One rule, users.Admin, now decides every change to an org-admin role: the
user create and update, SCIM, an admin membership, and an invitation that
carries the role. A SuperAdmin moves it anywhere; an org's admin moves it on
the others of a customer org; only a SuperAdmin makes an admin of a brand
(policy.IsPlatformOrg) or touches the admin org; nobody raises their own; the
last admin stays (409) unless a SuperAdmin takes them; applications, machines
and members are refused (403). The request is read for presence, so leaving
isAdmin out keeps it and a full-row write cannot demote by omission.
A revoke, a removed membership, an upsert lowering and a deleted account call
store.Void: User.Epoch moves to now, the account's token rows and sessions
are deleted, and verifyBearer refuses a token with iat <= epoch.
Invitations carry a role (member or admin), written only by who may grant it
and applied on signup and accept. GET /v1/iam/users takes isAdmin=true. Every
grant, revoke, role invitation, removal and void is an audit row under the
org, with actor, target, from, to, reason and request id.
Claude-Session: https://claude.ai/code/session_016DKtyuzxU43Gsc6Pm9vKTF
361 lines
13 KiB
Go
361 lines
13 KiB
Go
// Copyright 2026 Hanzo AI, Inc.
|
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
// Package invitations serves the IAM v2 CRUD surface for the `invitations`
|
|
// entity: a pending org-membership invite owner-scoped by (owner, name). Every
|
|
// operation is a typed zip handler over hanzoai/orm; the orm string key is
|
|
// "owner/name". Reads scope to one owner (organization); writes address one
|
|
// invitation by its (owner, name) key.
|
|
package invitations
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/hanzoai/orm"
|
|
"github.com/zap-proto/zip"
|
|
|
|
"github.com/hanzoai/iam/internal/authz"
|
|
"github.com/hanzoai/iam/internal/principal"
|
|
"github.com/hanzoai/iam/internal/users"
|
|
"github.com/hanzoai/iam/pkg/schema"
|
|
"github.com/hanzoai/iam/pkg/store"
|
|
)
|
|
|
|
// Handler binds the invitations operations to one orm store.
|
|
type Handler struct {
|
|
db orm.DB
|
|
}
|
|
|
|
//go:generate go run github.com/zap-proto/zip/cmd/zipdoc
|
|
|
|
// Route registers the invitations CRUD routes on app against db.
|
|
func Route(app *zip.Group, db orm.DB) {
|
|
h := &Handler{db: db}
|
|
app.Get("/v1/iam/invitations", h.List, zip.WithTags("invitations"))
|
|
app.Post("/v1/iam/invitations", h.Create, zip.WithTags("invitations"))
|
|
app.Get("/v1/iam/invitations/:owner/:name", h.Get, zip.WithTags("invitations"))
|
|
app.Put("/v1/iam/invitations/:owner/:name", h.Update, zip.WithTags("invitations"))
|
|
app.Delete("/v1/iam/invitations/:owner/:name", h.Delete, zip.WithTags("invitations"))
|
|
app.Post("/v1/iam/invitations/:owner/:name/send", h.Send, zip.WithTags("invitations"))
|
|
}
|
|
|
|
// Ref addresses one invitation by its owner-scoped natural key.
|
|
type Ref struct {
|
|
Owner string `json:"owner"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// Input is the writable projection of an invitation (the v1 add/update-invitation
|
|
// body). It keeps the HTTP contract clean of the orm.Model bookkeeping fields.
|
|
type Input struct {
|
|
Owner string `json:"owner"`
|
|
Name string `json:"name"`
|
|
CreatedTime string `json:"createdTime" url:"-"`
|
|
UpdatedTime string `json:"updatedTime" url:"-"`
|
|
DisplayName string `json:"displayName" url:"-"`
|
|
Code string `json:"code" url:"-"`
|
|
IsRegexp bool `json:"isRegexp" url:"-"`
|
|
Quota int `json:"quota" url:"-"`
|
|
UsedCount int `json:"usedCount" url:"-"`
|
|
Application string `json:"application"`
|
|
Username string `json:"username" url:"-"`
|
|
Email string `json:"email"`
|
|
Phone string `json:"phone" url:"-"`
|
|
SignupGroup string `json:"signupGroup" url:"-"`
|
|
DefaultCode string `json:"defaultCode" url:"-"`
|
|
State string `json:"state" url:"-"`
|
|
// Role is the role a redeemer arrives holding: "member" (the default) or
|
|
// "admin". An invitation carries admin only when its writer may make an admin
|
|
// of the org (users.Admin), and every edit of one asks again.
|
|
Role string `json:"role" url:"-"`
|
|
}
|
|
|
|
// ListInput scopes a listing to one owner (organization).
|
|
type ListInput struct {
|
|
Owner string `json:"owner"`
|
|
}
|
|
|
|
// ListOutput is the owner-scoped page of invitations.
|
|
type ListOutput struct {
|
|
Invitations []*schema.Invitation `json:"invitations"`
|
|
Total int `json:"total"`
|
|
}
|
|
|
|
// DeleteOutput reports the delete result.
|
|
type DeleteOutput struct {
|
|
Deleted bool `json:"deleted"`
|
|
}
|
|
|
|
// key builds the orm string key from the (owner, name) natural key.
|
|
func key(owner, name string) string { return owner + "/" + name }
|
|
|
|
// apply copies the mutable domain fields of an Input onto an invitation. The
|
|
// identity fields (owner, name) and the created stamp are set only on Create,
|
|
// never overwritten by an update.
|
|
func apply(dst *schema.Invitation, in *Input) {
|
|
dst.UpdatedTime = in.UpdatedTime
|
|
dst.DisplayName = in.DisplayName
|
|
dst.Code = in.Code
|
|
dst.IsRegexp = in.IsRegexp
|
|
dst.Quota = in.Quota
|
|
dst.UsedCount = in.UsedCount
|
|
dst.Application = in.Application
|
|
dst.Username = in.Username
|
|
dst.Email = in.Email
|
|
dst.Phone = store.NormalizePhone(in.Phone)
|
|
dst.SignupGroup = in.SignupGroup
|
|
dst.DefaultCode = in.DefaultCode
|
|
dst.State = in.State
|
|
dst.Role = in.Role
|
|
}
|
|
|
|
// List returns your organization's invitations, newest first — who has
|
|
// been asked to join, on what terms, and how many seats each invitation still
|
|
// has left.
|
|
//
|
|
// You see the invitations of the organization your credentials run, and no one
|
|
// else's: your own, or one you own or administer.
|
|
func (h *Handler) List(ctx context.Context, in *ListInput) (*ListOutput, error) {
|
|
// The owner is resolved by principal.Scope from the authenticated principal,
|
|
// never taken from the input: a tenant reads only its own org, a SuperAdmin
|
|
// reads the owner it asks for. in.Owner is whatever the CALLER wrote in the URL,
|
|
// since zip binds a typed op's scalar fields from the query string on every
|
|
// method, so filtering on it would let a request name the tenant it reads.
|
|
owner, err := principal.Scope(ctx, in.Owner)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
q := orm.TypedQuery[schema.Invitation](h.db)
|
|
if owner != "" {
|
|
q = q.Filter("owner", owner)
|
|
}
|
|
invitations, err := q.Order("-createdTime").GetAll(ctx)
|
|
if err != nil {
|
|
return nil, zip.ErrInternal(err.Error())
|
|
}
|
|
return &ListOutput{Invitations: invitations, Total: len(invitations)}, nil
|
|
}
|
|
|
|
// Get returns one invitation: who it is for, what it grants on acceptance, and
|
|
// when it expires.
|
|
func (h *Handler) Get(ctx context.Context, in *Ref) (*schema.Invitation, error) {
|
|
if in.Owner == "" || in.Name == "" {
|
|
return nil, zip.ErrBadRequest("owner and name are required")
|
|
}
|
|
invitation, err := orm.Get[schema.Invitation](h.db, key(in.Owner, in.Name))
|
|
if err != nil {
|
|
return nil, mapErr(err)
|
|
}
|
|
return invitation, nil
|
|
}
|
|
|
|
// authorizeRefs gates the rows an invitation NAMES: the application whoever
|
|
// redeems it arrives through, and the group they arrive holding. Neither is the
|
|
// invitation's own (Owner, Name), so the seam that authorizes the row authorized
|
|
// where the invitation is FILED and never what it hands out — an invitation naming
|
|
// another organization's application, or the platform's, is an invitation into
|
|
// that organization. A caller may name only what it may write, and an unqualified
|
|
// name is read in the invitation's own organization.
|
|
func authorizeRefs(ctx context.Context, method string, in *Input) error {
|
|
if err := authz.AuthorizeRef(ctx, method, "applications", in.Owner, in.Application); err != nil {
|
|
return err
|
|
}
|
|
return authz.AuthorizeRef(ctx, method, "groups", in.Owner, in.SignupGroup)
|
|
}
|
|
|
|
// validate refuses terms no invitation may carry: a pattern, which is retired; a
|
|
// code too short or too plain to stand as the only thing admitting a stranger; and
|
|
// an address that is anything but one bare address, since it is where the
|
|
// invitation is sent. A term an update leaves as it was is not re-judged, so an
|
|
// older invitation can still be edited.
|
|
func validate(in *Input, was *schema.Invitation) error {
|
|
if in.IsRegexp && (was == nil || !was.IsRegexp) {
|
|
return zip.ErrBadRequest("pattern invitations are retired; issue a code")
|
|
}
|
|
if in.Code != "" && (was == nil || in.Code != was.Code) {
|
|
if err := schema.InviteCode(in.Code); err != nil {
|
|
return zip.ErrBadRequest(err.Error())
|
|
}
|
|
}
|
|
if in.Email != "" && (was == nil || in.Email != was.Email) && !schema.BareAddress(in.Email) {
|
|
return zip.ErrBadRequest("an invitation is pinned to one email address, written bare")
|
|
}
|
|
switch in.Role {
|
|
case "", store.RoleMember, store.RoleAdmin:
|
|
default:
|
|
return zip.ErrBadRequest("an invitation's role is member or admin")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// role holds an invitation that carries org admin to the admin rule, and returns
|
|
// the audit row the write owes: one whenever the role it carries is admin, or
|
|
// changed. An admin invitation is a grant to whoever redeems it, so writing one —
|
|
// or editing one, which can widen who that is — needs the authority to make an
|
|
// admin of its org; nil when the write carries no role worth recording.
|
|
func role(ctx context.Context, db orm.DB, in *Input, was string) (*schema.AuditLog, error) {
|
|
if in.Role == store.RoleMember {
|
|
in.Role = ""
|
|
}
|
|
if in.Role == store.RoleAdmin {
|
|
if err := users.Admin(ctx, db, in.Owner, "", "", true); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
if in.Role != store.RoleAdmin && in.Role == was {
|
|
return nil, nil
|
|
}
|
|
return users.Act(ctx, in.Owner, "invitation "+in.Name).Row(schema.ActionInviteRole, map[string]any{
|
|
"invitation": in.Owner + "/" + in.Name, "from": orMember(was), "to": orMember(in.Role),
|
|
}), nil
|
|
}
|
|
|
|
// orMember names an invitation's role, "member" when it states none.
|
|
func orMember(r string) string {
|
|
if r == "" {
|
|
return store.RoleMember
|
|
}
|
|
return r
|
|
}
|
|
|
|
// Create issues an invitation to join your organization — the code or link a new
|
|
// member redeems, with the role they arrive holding and the date it stops
|
|
// working. A name already used in the organization is refused.
|
|
func (h *Handler) Create(ctx context.Context, in *Input) (*schema.Invitation, error) {
|
|
if in.Owner == "" || in.Name == "" {
|
|
return nil, zip.ErrBadRequest("owner and name are required")
|
|
}
|
|
if err := authorizeRefs(ctx, "POST", in); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := validate(in, nil); err != nil {
|
|
return nil, err
|
|
}
|
|
trail, err := role(ctx, h.db, in, "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch _, err := orm.Get[schema.Invitation](h.db, key(in.Owner, in.Name)); {
|
|
case err == nil:
|
|
return nil, zip.ErrConflict("invitation already exists")
|
|
case !errors.Is(err, orm.ErrNotFound):
|
|
return nil, zip.ErrInternal(err.Error())
|
|
}
|
|
|
|
invitation := orm.New[schema.Invitation](h.db)
|
|
invitation.Owner = in.Owner
|
|
invitation.Name = in.Name
|
|
invitation.CreatedTime = in.CreatedTime
|
|
if invitation.CreatedTime == "" {
|
|
invitation.CreatedTime = time.Now().UTC().Format(time.RFC3339)
|
|
}
|
|
apply(invitation, in)
|
|
if invitation.Code == "" {
|
|
code, err := MintCode()
|
|
if err != nil {
|
|
return nil, zip.ErrInternal(err.Error())
|
|
}
|
|
invitation.Code, invitation.Generated = code, true
|
|
}
|
|
invitation.SetId(key(in.Owner, in.Name))
|
|
|
|
if err := h.written(ctx, invitation, trail, func(i *schema.Invitation) error { return i.CreateCtx(ctx) }); err != nil {
|
|
return nil, zip.ErrInternal(err.Error())
|
|
}
|
|
return invitation, nil
|
|
}
|
|
|
|
// written runs one write of inv, and when the write owes a role row (trail) runs
|
|
// it in the same transaction as that row, so an invitation never carries a role
|
|
// its trail does not record.
|
|
func (h *Handler) written(ctx context.Context, inv *schema.Invitation, trail *schema.AuditLog, write func(*schema.Invitation) error) error {
|
|
if trail == nil {
|
|
return write(inv)
|
|
}
|
|
err := h.db.RunInTransaction(ctx, func(tx orm.DB) error {
|
|
inv.Init(tx)
|
|
if err := write(inv); err != nil {
|
|
return err
|
|
}
|
|
return store.Append(ctx, tx, trail)
|
|
})
|
|
inv.Init(h.db)
|
|
return err
|
|
}
|
|
|
|
// Update changes an invitation's terms — the role it grants, how many may redeem
|
|
// it, or when it expires. What it is called does not change.
|
|
func (h *Handler) Update(ctx context.Context, in *Input) (*schema.Invitation, error) {
|
|
if in.Owner == "" || in.Name == "" {
|
|
return nil, zip.ErrBadRequest("owner and name are required")
|
|
}
|
|
if err := authorizeRefs(ctx, "PUT", in); err != nil {
|
|
return nil, err
|
|
}
|
|
invitation, err := orm.Get[schema.Invitation](h.db, key(in.Owner, in.Name))
|
|
if err != nil {
|
|
return nil, mapErr(err)
|
|
}
|
|
if err := validate(in, invitation); err != nil {
|
|
return nil, err
|
|
}
|
|
trail, err := role(ctx, h.db, in, invitation.Role)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
generated := invitation.Generated && in.Code == invitation.Code
|
|
apply(invitation, in)
|
|
invitation.Generated = generated
|
|
if err := h.written(ctx, invitation, trail, func(i *schema.Invitation) error { return i.UpdateCtx(ctx) }); err != nil {
|
|
return nil, zip.ErrInternal(err.Error())
|
|
}
|
|
return invitation, nil
|
|
}
|
|
|
|
// Delete withdraws an invitation. It stops being redeemable at once; anyone who
|
|
// already joined through it keeps their account.
|
|
func (h *Handler) Delete(ctx context.Context, in *Ref) (*DeleteOutput, error) {
|
|
if in.Owner == "" || in.Name == "" {
|
|
return nil, zip.ErrBadRequest("owner and name are required")
|
|
}
|
|
invitation, err := orm.Get[schema.Invitation](h.db, key(in.Owner, in.Name))
|
|
if err != nil {
|
|
return nil, mapErr(err)
|
|
}
|
|
if err := invitation.DeleteCtx(ctx); err != nil {
|
|
return nil, zip.ErrInternal(err.Error())
|
|
}
|
|
return &DeleteOutput{Deleted: true}, nil
|
|
}
|
|
|
|
// mapErr translates an orm lookup error into the matching HTTP status.
|
|
func mapErr(err error) error {
|
|
if errors.Is(err, orm.ErrNotFound) {
|
|
return zip.ErrNotFound("invitation not found")
|
|
}
|
|
return zip.ErrInternal(err.Error())
|
|
}
|
|
|
|
// codeAlphabet is 32 letters and digits with none that read alike (no 0/O, 1/I),
|
|
// so a minted code survives being read aloud; 32 divides 256, so a byte maps onto
|
|
// it without bias.
|
|
const codeAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
|
|
|
// codeLength is 20 characters of codeAlphabet: 100 bits.
|
|
const codeLength = 20
|
|
|
|
// MintCode draws an invitation code from crypto/rand.
|
|
func MintCode() (string, error) {
|
|
b := make([]byte, codeLength)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", err
|
|
}
|
|
for i := range b {
|
|
b[i] = codeAlphabet[int(b[i])%len(codeAlphabet)]
|
|
}
|
|
return string(b), nil
|
|
}
|