Files
iam/internal/seed/seed.go
zooqueenandHanzo Dev 484922ec8b applications: only a SuperAdmin writes an application that serves other orgs
An application serves every org when it is shared or offers an org choice
(orgChoiceMode other than "" and "None"). Create and Update refuse a
non-SuperAdmin any such write -- making one, editing one, or confining one --
through one gate, authorizeSpan, on schema.Application.Spans.

Tenant isolation reads ServesAnyOrg, which also requires the platform to own
the row (Owner "admin"). A row any other org owns serves that org alone,
whatever it declares, so the code mint, the password grant, impersonation,
device approval and federation cross tenants only through a platform
application.

The seed files an owner-less application under the owner its key names.
Regenerates the internal/tokens zipdoc.

Co-authored-by: Hanzo Dev <[email protected]>
2026-10-14 23:38:53 -07:00

427 lines
17 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
// Package seed bootstraps the iam store from an init_data.json file — the same
// file the the legacy surface iam uses. This is the ported InitFromFile behavior: on boot,
// upsert organizations, applications, providers, and certs so a fresh iam
// (embedded in cloud or standalone) comes up with the real app/provider/cert
// config instead of an empty store.
//
// New-only by default (like the legacy surface's initDataNewOnly): an entity that already
// exists is left untouched; only missing ones are created. ${VAR} references in
// the JSON (client ids/secrets, cert keys) are substituted from the environment
// before parsing — the same mechanism that injects KMS-synced secrets.
package seed
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"strings"
policy "github.com/hanzoai/authz"
"github.com/hanzoai/orm"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
)
// initData is the subset of the init_data.json shape iam seeds. Users and the
// Casbin/LDAP/syncer artifacts are deliberately excluded — identity config only.
type initData struct {
Organizations []*schema.Organization `json:"organizations"`
Applications []*schema.Application `json:"applications"`
Providers []*schema.Provider `json:"providers"`
Certs []*schema.Cert `json:"certs"`
// appDeclared is the RAW json object for each application, keyed "owner/name".
// It is what makes an application's declared POLICY converge on an existing row
// (see reconcileApp) — the typed struct above cannot, because an absent key and
// a declared `false` are both the zero value once decoded. Populated by
// FromInitData; nil when Apply is called with a literal (tests), in which case
// seeding stays strictly new-only.
appDeclared map[string]json.RawMessage
}
// Summary reports what a seed run created, skipped, reconciled, or refused.
type Summary struct {
Created map[string]int // kind -> created count
Skipped map[string]int // kind -> already-existed, unchanged
Reconciled map[string]int // kind -> already-existed, declared policy re-applied
Refused []string // "owner/name: reason" for each declaration not written
}
var envRef = regexp.MustCompile(`\$\{([A-Z0-9_]+)\}`)
// substituteEnv replaces ${VAR} with os.Getenv(VAR). An unset var becomes empty
// (the legacy surface-compatible) — a provider/cert with an empty credential simply reads
// as unconfigured downstream, never a dead-end.
func substituteEnv(b []byte) []byte {
return envRef.ReplaceAllFunc(b, func(m []byte) []byte {
name := envRef.FindSubmatch(m)[1]
return []byte(os.Getenv(string(name)))
})
}
// FromInitData reads path, substitutes ${VAR}, and upserts the identity config
// into db. new-only: existing rows (by owner/name) are skipped.
func FromInitData(ctx context.Context, db orm.DB, path string) (*Summary, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("seed: read %s: %w", path, err)
}
sub := substituteEnv(raw)
var data initData
if err := json.Unmarshal(sub, &data); err != nil {
return nil, fmt.Errorf("seed: parse %s: %w", path, err)
}
// Second pass, applications only: keep each declared object VERBATIM so
// reconcileApp can tell "declared false" from "not declared at all".
var rawDoc struct {
Applications []json.RawMessage `json:"applications"`
}
if err := json.Unmarshal(sub, &rawDoc); err != nil {
return nil, fmt.Errorf("seed: parse %s (raw applications): %w", path, err)
}
data.appDeclared = make(map[string]json.RawMessage, len(rawDoc.Applications))
for _, obj := range rawDoc.Applications {
var ref struct {
Owner string `json:"owner"`
Name string `json:"name"`
}
if err := json.Unmarshal(obj, &ref); err != nil {
continue
}
if ref.Owner == "" {
ref.Owner = "admin"
}
data.appDeclared[ref.Owner+"/"+ref.Name] = obj
}
if err := refuseRegistration(path, rawDoc.Applications); err != nil {
return nil, err
}
return Apply(ctx, db, &data)
}
// registrationKeys are the application fields this file MAY NOT carry, because
// something else owns them and writes them at a different time.
//
// Registration — where an application may send a browser back, and which grants
// it may use — belongs to the provision document, which both creates and
// updates it. This file is read for an application ONLY when that application
// does not exist yet, so a redirect declared here takes effect once, at
// creation, and is ignored by every boot after. Editing it then changes
// nothing, silently, and the failure surfaces a layer away as the application
// answering "invalid redirect_uri" for a callback its own configuration names.
//
// That is not a rule anyone can be expected to remember from the call site: the
// field is right there, beside fields that DO converge. So the file may not say
// it at all, and saying it stops the boot rather than being quietly dropped.
var registrationKeys = []string{"redirectUris", "grantTypes"}
// refuseRegistration reports an init_data document that declares registration.
//
// Loudly and at boot, naming the application and the field: the whole point is
// that a wrong declaration must not be survivable. A seed that silently ignores
// half of what it is given is indistinguishable from one that applied it.
func refuseRegistration(path string, apps []json.RawMessage) error {
var said []string
for _, obj := range apps {
var app map[string]json.RawMessage
if err := json.Unmarshal(obj, &app); err != nil {
continue
}
var ref struct {
Name string `json:"name"`
}
_ = json.Unmarshal(obj, &ref)
for _, k := range registrationKeys {
if _, ok := app[k]; ok {
said = append(said, ref.Name+"."+k)
}
}
}
if len(said) == 0 {
return nil
}
shown := said
if len(shown) > 8 {
shown = shown[:8]
}
return fmt.Errorf(
"seed: %s declares registration this file does not own: %s (%d in all) — "+
"redirectUris and grantTypes are set by the provision document, which creates "+
"and updates applications; declared here they apply once at creation and are "+
"ignored afterwards, so the two drift and sign-in fails with invalid redirect_uri",
path, strings.Join(shown, ", "), len(said))
}
// Apply upserts an already-parsed initData. Split out so tests can seed from a
// literal without a file.
func Apply(ctx context.Context, db orm.DB, data *initData) (*Summary, error) {
s := &Summary{Created: map[string]int{}, Skipped: map[string]int{}, Reconciled: map[string]int{}}
declared := map[string]bool{}
for _, o := range data.Organizations {
if err := upsert[schema.Organization](ctx, db, o.Owner, o.Name, o, s, "organizations"); err != nil {
return s, err
}
declared[cmp.Or(o.Owner, policy.AdminOrg)+"/"+o.Name] = true
}
if err := markPlatformOrgs(ctx, db, declared); err != nil {
return s, err
}
for _, p := range data.Providers {
if err := upsert[schema.Provider](ctx, db, p.Owner, p.Name, p, s, "providers"); err != nil {
return s, err
}
}
for _, c := range data.Certs {
// Certs are seeded as METADATA — owner, name, algorithm, expiry. A signing
// cert arrives from init_data without key material because secrets cannot
// ride a ConfigMap, and it stays that way: the key is mounted by the
// deployment and filled in on load (internal/keyring).
if err := upsert[schema.Cert](ctx, db, c.Owner, c.Name, c, s, "certs"); err != nil {
return s, err
}
}
platform := map[string]bool{}
for _, a := range data.Applications {
owner := a.Owner
if owner == "" {
owner = "admin"
}
// The row carries the owner its key names: tenant isolation reads Owner
// (schema.Application.ServesAnyOrg), and markPlatform keys on it.
a.Owner = owner
// A NEW declaration beside another owner's application of the same name would
// outrank it wherever a name alone is resolved (see store.NameHeldElsewhere),
// so it is refused. Only it: a tenant chose that name, and a tenant's choice
// must not stop the seed applying its policy to every other application.
if held, err := nameHeld(ctx, db, owner, a.Name); err != nil {
return s, err
} else if held {
s.Refused = append(s.Refused, owner+"/"+a.Name+": the name is held by another owner")
continue
}
before := s.Skipped["applications"]
if err := upsert[schema.Application](ctx, db, a.Owner, a.Name, a, s, "applications"); err != nil {
return s, err
}
// Existing row: re-apply the DECLARED policy so init_data.json is converging
// state rather than a one-shot bootstrap.
if s.Skipped["applications"] > before {
if err := reconcileApp(db, owner+"/"+a.Name, data.appDeclared, s); err != nil {
return s, err
}
}
if owner == policy.AdminOrg {
platform[owner+"/"+a.Name] = true
}
}
if err := markPlatform(ctx, db, platform); err != nil {
return s, err
}
return s, nil
}
// markPlatform makes the platform's own applications exactly the ones this file
// declares under the reserved admin org, on every run: each of those is marked,
// and every other row — one the file stopped declaring, or one it declares under
// an ordinary org, whose admin can write it — is unmarked. Only this file says
// which applications are the platform's.
func markPlatform(ctx context.Context, db orm.DB, platform map[string]bool) error {
apps, err := orm.TypedQuery[schema.Application](db).GetAll(ctx)
if err != nil && !errors.Is(err, orm.ErrNotFound) {
return fmt.Errorf("seed: list applications: %w", err)
}
for _, app := range apps {
want := platform[app.Owner+"/"+app.Name]
if app.Platform == want {
continue
}
// Rows are stored whole, so the flag is set on a fresh read under the row's
// lock: nothing written to the row meanwhile is overwritten with what the
// listing saw.
if err := db.RunInTransaction(ctx, func(tx orm.DB) error {
fresh, err := orm.GetForUpdate[schema.Application](tx, app.Key().Encode())
if err != nil || fresh.Platform == want {
return err
}
fresh.Platform = want
return fresh.UpdateCtx(ctx)
}); err != nil {
return fmt.Errorf("seed: mark application %s/%s: %w", app.Owner, app.Name, err)
}
}
return nil
}
// markPlatformOrgs makes the platform's own organizations exactly the ones this
// file declares plus the held names (policy.IsHeldOrg) that exist, on every run,
// the way markPlatform does for applications: each is marked and every other row
// is unmarked.
func markPlatformOrgs(ctx context.Context, db orm.DB, declared map[string]bool) error {
orgs, err := orm.TypedQuery[schema.Organization](db).GetAll(ctx)
if err != nil && !errors.Is(err, orm.ErrNotFound) {
return fmt.Errorf("seed: list organizations: %w", err)
}
for _, org := range orgs {
want := declared[org.Owner+"/"+org.Name] || (org.Owner == policy.AdminOrg && policy.IsHeldOrg(org.Name))
if org.Platform == want {
continue
}
if err := db.RunInTransaction(ctx, func(tx orm.DB) error {
fresh, err := orm.GetForUpdate[schema.Organization](tx, org.Key().Encode())
if err != nil || fresh.Platform == want {
return err
}
fresh.Platform = want
return fresh.UpdateCtx(ctx)
}); err != nil {
return fmt.Errorf("seed: mark organization %s/%s: %w", org.Owner, org.Name, err)
}
}
return nil
}
// nameHeld reports whether owner/name is new and its name is held by another
// owner. A row already standing is not re-judged: it is how the store was found.
func nameHeld(ctx context.Context, db orm.DB, owner, name string) (bool, error) {
if existing, err := store.GetApplicationByName(ctx, db, owner, name); err != nil {
return false, fmt.Errorf("seed: application %s/%s: %w", owner, name, err)
} else if existing != nil {
return false, nil
}
held, err := store.NameHeldElsewhere(ctx, db, owner, name)
if err != nil {
return false, fmt.Errorf("seed: application %s/%s: %w", owner, name, err)
}
return held, nil
}
// reconcileApp re-applies an application's DECLARED fields onto the existing row.
//
// Seeding is new-only, which is right for identity DATA (a live user row must never
// be stomped by a bootstrap file) but wrong for application POLICY: init_data.json is
// how the platform declares whether an app allows sign-up, which org it belongs to,
// and how it lets users choose one. Because upsert skipped existing rows, flipping
// `enableSignUp` in init_data.json changed nothing on a seeded deployment, so the
// declared state and the live flag could disagree with no way to reconcile them
// short of an admin call. Declared policy now converges on boot.
//
// It merges the RAW declared object onto the loaded row, which is the whole point:
// json.Unmarshal sets only the keys PRESENT in the JSON, so a field init_data.json
// does not mention keeps its stored value. That is what protects `clientSecret`,
// which is generated at first seed and never written back to the file — decoding the
// typed struct and saving it would blank the secret and lock every client out (the
// same de-secret hazard update-application had to fix). Nothing is written when the
// application was not declared with a raw object (Apply called from a literal).
func reconcileApp(db orm.DB, id string, declared map[string]json.RawMessage, s *Summary) error {
raw, ok := declared[id]
if !ok {
return nil
}
// Narrow the declared object to the POLICY keys before applying it. Merging the
// WHOLE object would make init_data.json authoritative over the entire
// registration, and it is not: live applications legitimately carry redirect
// URIs and grants this file does not list, so a full merge would silently
// DELETE them and break the very logins it was meant to fix.
//
// Registration — redirects, grants, hosts — is owned by the provision document.
// This file owns identity POLICY. Keeping the two apart is why a bootstrap file
// can converge a flag without being able to take a surface offline.
policy := map[string]json.RawMessage{}
var all map[string]json.RawMessage
if err := json.Unmarshal(raw, &all); err != nil {
return fmt.Errorf("seed: reconcile application %s: %w", id, err)
}
for _, k := range appPolicyKeys {
if v, ok := all[k]; ok {
policy[k] = v
}
}
if len(policy) == 0 {
return nil
}
patch, err := json.Marshal(policy)
if err != nil {
return fmt.Errorf("seed: reconcile application %s: %w", id, err)
}
if _, err := orm.GetOrUpdate[schema.Application](db, id, func(dst *schema.Application) {
// Only the keys present in `patch` are written; everything else on the row —
// including clientSecret, redirects and grants — is left exactly as stored.
_ = json.Unmarshal(patch, dst)
}); err != nil {
return fmt.Errorf("seed: reconcile application %s: %w", id, err)
}
s.Reconciled["applications"]++
return nil
}
// appPolicyKeys are the application fields init_data.json GOVERNS — who may sign in
// and how they pick an org. Deliberately short: every key added here becomes one the
// file can silently revert on the next boot, so a field belongs on this list only if
// the declared value should always win over whatever is live.
//
// Not here, on purpose: redirectUris, grantTypes, clientId/clientSecret, cert — the
// registration surface, which drifts legitimately and is owned elsewhere.
var appPolicyKeys = []string{
"enableSignUp",
"enablePassword",
"enableCodeSignin",
// Passkeys. Omitting this is the exact class this function exists to fix, one
// field over: a new-only upsert never carries a declared policy flag to a
// seeded row, so init_data.json can declare enableWebAuthn TRUE while the live
// auth-methods endpoint answers `webauthn:false`, with nothing logged and no
// way to reconcile short of diffing the ConfigMap against the endpoint.
//
// It belongs here by this list's own test — the declared value should always
// win. Whether an app offers passkeys is identity POLICY, not registration
// drift: it names no external party, no redirect and no secret, so unlike
// redirectUris there is no legitimate live value for it to clobber.
"enableWebAuthn",
"enableSigninSession",
"orgChoiceMode",
"isShared",
"organization",
// Which identity providers an app offers is the same kind of fact as
// enableWebAuthn: it decides who may sign in, names only provider RECORDS
// (no redirect, no secret), and has no legitimate live drift. Without it,
// an app registered by the provision document (which cannot say providers)
// could never gain a social button from declared state, even where
// init_data.json declares one.
"providers",
}
// upsert creates entity if (owner,name) is absent; otherwise counts it skipped
// (new-only). GetOrCreate wires a fresh Model + sets the id; the defaults func
// copies the entity's data fields via a JSON round-trip, which sets only the
// json-tagged fields and leaves the wired Model's internals (db handle, key)
// intact — the generic-safe way to persist a fully-formed struct.
func upsert[T any](_ context.Context, db orm.DB, owner, name string, entity *T, s *Summary, kind string) error {
if owner == "" {
owner = "admin"
}
id := owner + "/" + name
blob, err := json.Marshal(entity)
if err != nil {
return fmt.Errorf("seed: marshal %s %s: %w", kind, id, err)
}
_, created, err := orm.GetOrCreate[T](db, id, func(dst *T) {
_ = json.Unmarshal(blob, dst)
})
if err != nil {
return fmt.Errorf("seed: create %s %s: %w", kind, id, err)
}
if created {
s.Created[kind]++
} else {
s.Skipped[kind]++
}
return nil
}