mirror of
https://github.com/hanzoai/iam.git
synced 2026-11-19 18:37:16 +00:00
A join code is claimed in the per-mailbox ledger (3 per inviting org, 20 across orgs a day) under the joining org's lock before it is sent, under a fixed subject. POST /v1/iam/invitations mints a 20-character crypto/rand code when none is given and marks it generated; only generated codes skip the per-org gate, so a typed code however strong it looks stays behind it. Names keep combining marks and an inviter without a display name is left out; an address with an empty domain label is not bare. The platform flag is written by the seed alone, on a locked fresh read. Co-authored-by: Hanzo Dev <[email protected]>
294 lines
10 KiB
Go
294 lines
10 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/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:"-"`
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// 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")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 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
|
|
}
|
|
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 := invitation.CreateCtx(ctx); err != nil {
|
|
return nil, zip.ErrInternal(err.Error())
|
|
}
|
|
return invitation, nil
|
|
}
|
|
|
|
// 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
|
|
}
|
|
generated := invitation.Generated && in.Code == invitation.Code
|
|
apply(invitation, in)
|
|
invitation.Generated = generated
|
|
if err := invitation.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
|
|
}
|