bootstrap

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package bootstrap implements the kiban-bootstrap step runner: an ordered set of idempotent, individually-logged steps (preflight, migrations orchestration, realm reconciliation, service accounts, superadmin, seed, verify) that each report a truthful applied|converged|failed outcome. There is deliberately no "rolled back" outcome: a step that fails partway reports Failed with the real error, and whatever state it left behind stands — no step implementation may claim to have undone it.

Index

Constants

View Source
const SystemPlatformID = store.SystemPlatformID

SystemPlatformID is the base authz model's one well-known `system` object id — model.json's `system#superadmin` relation ("this": true) is the platform-wide anchor every base type's `admin` union ultimately reaches via `tupleToUserset(system, superadmin)` (company, module, company_module, ...). There is exactly one platform, so exactly one `system` object; this constant IS the platform, not a per-tenant id. Owned by authz/store (the tuple's writer).

Variables

View Source
var KnownModules = []registry.ModuleManifest{}

KnownModules is the built-in module manifest set SeedStep validates KIBAN_INSTALLED_MODULES against, mirroring cmd/registry/main.go's own `builtinModules` (currently empty — no module registration workflow exists yet, so a non-empty KIBAN_INSTALLED_MODULES today loudly fails, which is correct). Tests override this via Deps (see seed_test.go) to exercise the non-overwrite proof with a synthetic manifest without touching this production list.

View Source
var MigrationServiceOrder = []string{"registry", "authz", "identity", "org"}

MigrationServiceOrder is the real dependency order tern migrations must run in: registry FIRST, because migrations/registry/0001_roles.sql creates the four per-service DB roles (kiban_registry/kiban_identity/kiban_org/kiban_authz) that identity's own migrations/identity/0001_schema.sql immediately GRANTs USAGE to — running identity before registry fails outright ("role kiban_identity does not exist"); authz BEFORE identity, because migrations/authz/0010 backfills the superadmin tuples that migrations/identity/0005 requires before it drops identity.platform_role. This matches tools/dev/migrate.go (the compose migrate job's order).

View Source
var StructuralTuples []store.Tuple

StructuralTuples is the production set of structural authz tuples SeedStep grants on every run (idempotent by natural key). Currently empty: per-company structural parents (`company#admin`, `company_module#admin`, ...) are org's own runtime concern, not a platform one-shot bootstrap concern, and the superadmin's own `system:platform#superadmin` tuple is SuperadminStep's one-time write (and authz's grant/revoke routes' afterwards) — never a projection re-seeded here. The grant mechanism below (SeedStructuralTuples) is real, transactional, and tested (see seed_test.go's synthetic-tuple proof) — this var is simply empty until a feature needs a genuine structural fact seeded here.

Functions

func CompanyMemberBackfill

func CompanyMemberBackfill(ctx context.Context, orgPool *pgxpool.Pool, actor string) (string, bool, error)

CompanyMemberBackfill is the bootstrap converge step: idempotent backfill of `company:<companyId>#member @ member:<memberId>#mapped_user` for every ACTIVE member that predates org.Store.CreateMember/UpdateMember maintaining the tuple. Same shape and pool as MemberMappedUserBackfill: runs entirely on orgPool (kiban_org has USAGE+INSERT on the authz schema — migrations/authz/0005), one small transaction per member, a same-transaction pre-check so the ledger gets exactly one grant row per tuple actually written and a converged re-run writes nothing.

func DefaultGrantBackfill

func DefaultGrantBackfill(ctx context.Context, regPool, authzPool *pgxpool.Pool, actor string) (string, bool, error)

DefaultGrantBackfill is the bootstrap converge step that writes the default module-access grant for every EXISTING (active company × installed+enabled module) pair, so stacks that predate default grants work without manual intervention. It reads active companies and installed+enabled modules through regPool (kiban_registry's own role — granted read access to org.org_unit/org_unit_type by migrations/org/0008 and already owning platform.module_installation outright), then writes each pair's default grant through authzPool via authz/store.EnsureDefaultGrant (default-ONCE, audited, never a raw INSERT). Safe to call on every bootstrap run: already-defaulted pairs (whether still granted or deliberately excluded since) are untouched.

func MemberMappedUserBackfill

func MemberMappedUserBackfill(ctx context.Context, orgPool *pgxpool.Pool, actor string) (string, bool, error)

MemberMappedUserBackfill is the bootstrap converge step: idempotent backfill of `member:<memberId>#mapped_user @ user:<kcSub>` for every member ALREADY linked to a user before the tuple-maintenance code path existed (Store.LinkUser/UnlinkUser only maintain the tuple going forward, on new link/unlink calls). Runs entirely on orgPool (kiban_org's own role) — it already has SELECT on identity.user_read_v (identity's published read view) and USAGE+INSERT on the authz schema (migrations/authz/0005), so no new cross-service grant is needed and no separate AuthzPool transaction either. Safe to call on every bootstrap run: store.Grant's `INSERT ... ON CONFLICT DO NOTHING` makes an already-granted pair a no-op.

func OrgObjectCompanyBackfill

func OrgObjectCompanyBackfill(ctx context.Context, orgPool *pgxpool.Pool, actor string) (string, bool, error)

OrgObjectCompanyBackfill is the bootstrap converge step: idempotent backfill of `position:<id>#company @ company:<companyId>` and `group:<id>#company @ company:<companyId>` for every position and group that predates org.Store.CreatePosition/CreateGroup writing the anchor. Same shape and pool as CompanyMemberBackfill: runs entirely on orgPool, one small transaction per object, a same-transaction pre-check so the ledger gets exactly one grant row per tuple actually written and a converged re-run writes nothing.

func SeedStructuralTuples

func SeedStructuralTuples(ctx context.Context, pool *pgxpool.Pool, actor string, tuples []store.Tuple) (string, bool, error)

SeedStructuralTuples grants tuples via authz/store.Grant (one transaction), then re-checks each tuple's natural key is actually present (post-write re-check) — fail-closed: a grant that doesn't read back is a hard failure, never silently ignored. Idempotent by natural key: store.Grant's INSERT ... ON CONFLICT DO NOTHING means re-running with the same tuples is always OutcomeConverged (applied=false) after the first run.

func WithAdvisoryLock

func WithAdvisoryLock(ctx context.Context, pool *pgxpool.Pool, fn func(context.Context) error) error

WithAdvisoryLock acquires a SESSION-level Postgres advisory lock (pg_advisory_lock) on a single dedicated connection, blocking until any concurrent bootstrap run releases it, runs fn, then releases the lock and the connection. Session-level advisory locks are tied to the connection that took them (Postgres semantics) — using one pinned pgxpool.Conn for both acquire and release, never released from a different connection, is load-bearing here, not incidental.

Types

type Deps

type Deps struct {
	Logger *slog.Logger

	// Pool connects as the migration-owner role (`kiban`, the non-superuser app-DB
	// owner — infra/postgres-init/01-roles.sh) — the only role with DDL rights. Preflight pings it; MigrationsStep reads schema_version_*
	// tables through it (before/after comparisons never need elevated DDL, just SELECT);
	// SuperadminStep writes the one-time superadmin's identity row and platform-role tuple
	// through it in one transaction (the only role that may write both schemas); VerifyStep
	// re-counts the tuple through it.
	Pool *pgxpool.Pool

	HTTPClient *http.Client

	// KeycloakManagementURL is Keycloak's health endpoint base (management port, split from
	// the app port in this Keycloak version) — infra/bootstrap-stub/entrypoint.sh's own step 2
	// ported to Go. Empty skips the check (test-only escape hatch; production wiring always
	// sets it).
	KeycloakManagementURL string
	// KeycloakRealmDiscoveryURL is the realm's OIDC discovery document URL — a non-empty
	// issuer there proves the realm is actually imported (entrypoint.sh's step 3). Empty skips
	// the check.
	KeycloakRealmDiscoveryURL string

	// RepoRoot is the working directory `go tool tern` and the role-password step run from (a
	// module-rooted directory so `go tool` resolves the go.mod tool directive).
	RepoRoot string
	// MigrationsRoot is the absolute path to the migrations/ directory (contains the
	// registry/identity/org/authz subdirectories, each with its own tern.conf).
	MigrationsRoot string
	// DBEnv is passed verbatim as extra environment to every tern/the role-password step
	// subprocess: KIBAN_DB_HOST, KIBAN_DB_PORT, POSTGRES_DB, KIBAN_DB_PASSWORD (the owner
	// role's own connection info — tern.conf's own {{env "..."}} templates read
	// exactly these names).
	DBEnv map[string]string
	// RolePasswords maps service name ("registry"|"identity"|"org"|"authz") to its runtime
	// DB role's password — used both to drive the role-password step (KIBAN_<SVC>_DB_PASSWORD)
	// and to open real (non-superuser) connections for the grant-matrix spot-check.
	RolePasswords map[string]string

	// KeycloakAdminBaseURL is Keycloak's APP port base (e.g. "http://127.0.0.1:8081") — the
	// admin REST API lives under {base}/admin/realms/{realm}, token endpoint under
	// {base}/realms/master/... (master realm password grant; the master-realm bootstrap admin
	// is used only by bootstrap). Empty skips RealmStep entirely (test-only escape hatch).
	KeycloakAdminBaseURL string
	// KeycloakRealm is the app realm RealmStep reconciles (matches KEYCLOAK_REALM).
	KeycloakRealm string
	// KCBootstrapAdminUsername/Password are the master-realm bootstrap admin credentials
	// (KC_BOOTSTRAP_ADMIN_USERNAME/PASSWORD) — used ONLY by RealmStep/SuperadminStep, never
	// passed to any other service.
	KCBootstrapAdminUsername string
	KCBootstrapAdminPassword string
	// KibanDomain sources kiban-frontend's redirect URIs/web origins.
	// Empty falls back to the dev-loopback origins already in infra/keycloak-build/
	// realm-kiban.json (localhost:3000/5173/80), so a domainless dev run still converges.
	KibanDomain string
	// ServiceClients (KIBAN_SERVICE_CLIENTS, comma-separated client ids) are the confidential
	// service-account clients RealmStep creates for backends that need their own token.
	ServiceClients []string
	// ExtraOrigins (KIBAN_EXTRA_ORIGINS, comma-separated) adds redirect URIs and web origins to
	// kiban-frontend beyond KIBAN_DOMAIN's: web origins ("https://app.example.com") and native
	// redirect URIs ("com.example.app:/callback").
	ExtraOrigins []string
	// IdentityClientSecret is the kiban-identity-service client's current secret
	// (KEYCLOAK_IDENTITY_CLIENT_SECRET) — RealmStep writes it to SecretsDir as a 0600 file;
	// with RotateSecrets it instead rotates the secret via the admin API first and writes the
	// NEW value (the operator must then update KEYCLOAK_IDENTITY_CLIENT_SECRET to match — see
	// this step's own detail/warning output).
	IdentityClientSecret string
	// SecretsDir is the shared volume directory per-service client secrets are written to as
	// 0600 files. Empty skips the write (test-only escape hatch).
	SecretsDir string
	// RotateSecrets is the --rotate-secrets flag: forces RealmStep to regenerate every managed
	// client secret via the admin API instead of just re-reading/re-writing the existing one.
	RotateSecrets bool

	// SuperadminUsername/Email are the one-time superadmin's Keycloak username/email.
	SuperadminUsername string
	SuperadminEmail    string
	// SuperadminPassword is the initial (forced-temporary) password, read by main.go from
	// KIBAN_SUPERADMIN_PASSWORD_FILE (never a plain env var: secrets are never stored in
	// env-visible places).
	SuperadminPassword string

	// RegistryPool connects to the registry service's OWN database as its OWN runtime role
	// (kiban_registry) — SeedStep calls registry.Store.Seed on this pool, the same rule.
	RegistryPool *pgxpool.Pool
	// AuthzPool connects to the authz service's OWN database as its OWN runtime role
	// (kiban_authz) — SeedStep seeds structural tuples via authz/store.Grant on this pool.
	AuthzPool *pgxpool.Pool
	// OrgPool connects to the org service's OWN database as its OWN runtime role (kiban_org) —
	// SeedStep's MemberMappedUserBackfill sub-step reads org.member JOIN
	// identity.user_read_v and writes authz.tuple/grant_ledger through it: kiban_org already has
	// SELECT on identity.user_read_v and USAGE+INSERT on the authz schema
	// (migrations/authz/0005) — no new cross-service grant needed, unlike RegistryPool (which is
	// deliberately NOT granted read access to identity's user rows).
	OrgPool *pgxpool.Pool
	// InstalledModulesCSV is KIBAN_INSTALLED_MODULES, parsed by SeedStep the same way
	// cmd/registry/main.go parses it.
	InstalledModulesCSV string
}

Deps bundles everything the ordered steps need.

type MigrationsStep

type MigrationsStep struct{}

MigrationsStep applies every service's tern migrations, in MigrationServiceOrder, as the owner role — then sets the four runtime role passwords (idempotent, ALTER ROLE) and spot- checks the per-service grant matrix: a runtime role can SELECT another service's PUBLISHED VIEW but not its base tables. Never runs DDL itself in Go — it only shells out to `go tool tern`, the same tool/config files `make migrate-*` already uses (migrations are the single source of schema truth, not bootstrap's own logic).

func (MigrationsStep) Name

func (MigrationsStep) Name() string

func (MigrationsStep) Run

func (MigrationsStep) Run(ctx context.Context, deps *Deps) (Outcome, string, error)

type Outcome

type Outcome string

Outcome is one step's truthful result: applied, converged, or failed.

const (
	// OutcomeApplied means the step changed real state to reach its target.
	OutcomeApplied Outcome = "applied"
	// OutcomeConverged means the step found its target state already satisfied — a no-op
	// re-run, the common case once a deployment has bootstrapped once.
	OutcomeConverged Outcome = "converged"
	// OutcomeFailed means the step did not reach its target state. Err is always non-nil.
	OutcomeFailed Outcome = "failed"
)

type PreflightStep

type PreflightStep struct{}

PreflightStep proves the two hard dependencies every later step needs before touching anything: Postgres reachable (as the owner role) and — when configured — Keycloak ready with its realm actually imported (ports infra/bootstrap-stub/entrypoint.sh's shell checks into Go, versions logged instead of just a pass/fail exit code). Preflight is read-only, so a successful run is always "converged" — there is nothing for it to "apply".

func (PreflightStep) Name

func (PreflightStep) Name() string

func (PreflightStep) Run

func (PreflightStep) Run(ctx context.Context, deps *Deps) (Outcome, string, error)

type RealmStep

type RealmStep struct{}

RealmStep reconciles the Keycloak realm via the admin REST API: realm settings, the kiban-api/kiban-frontend clients, the MFA browser-flow wiring, the identity service-account client's exact realm-management roles, and per-service client secrets written to a shared volume as 0600 files.

func (RealmStep) Name

func (RealmStep) Name() string

func (RealmStep) Run

func (RealmStep) Run(ctx context.Context, deps *Deps) (Outcome, string, error)

type Result

type Result struct {
	Step    string
	Outcome Outcome
	Detail  string
	Err     error
}

Result is one step's reported outcome, in run order.

type Runner

type Runner struct {
	Steps []Step
}

Runner runs an ordered list of Steps against one Deps, stopping at the first Failed result — later steps generally depend on earlier ones having actually succeeded (seeding needs migrations applied, superadmin creation needs the realm reconciled). Steps after a failure are simply never attempted; nothing about them is reported.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, deps *Deps) ([]Result, error)

Run executes every step in order, logging each outcome as it completes, and returns every result produced (including the failing one, if any) plus a non-nil error wrapping the first failure.

type SeedStep

type SeedStep struct{}

SeedStep seeds registry modules (seed-missing-only, never overwriting an existing row) via registry's own Seed package, then structural authz tuples via authz/store's transactional grant API with a post-write re-check. Both go through the owning service's imported Go code (authz/store is authz's OWN published transactional API for exactly this purpose, not a bypass of it).

func (SeedStep) Name

func (SeedStep) Name() string

func (SeedStep) Run

func (SeedStep) Run(ctx context.Context, deps *Deps) (Outcome, string, error)

type Step

type Step interface {
	Name() string
	Run(ctx context.Context, deps *Deps) (Outcome, string, error)
}

Step is one ordered, idempotent bootstrap unit. Run must never partially apply changes and then report success — if it returns (OutcomeFailed, _, err), any state it already touched before failing is exactly what's left; nothing is (or claims to be) rolled back.

type SuperadminStep

type SuperadminStep struct{}

SuperadminStep creates the one-time platform superadmin — ONLY if none exists yet. Marker = "does any `system:platform#superadmin` tuple exist" (authz/store.CountSuperadmins on the owner connection, deps.Pool): the tuple is the platform role's one record. A second run is always OutcomeConverged ("skipped"), never re-creates, re-enables, or resets the existing superadmin. On first run it creates the Keycloak user, then — in ONE transaction on the owner connection, the only role that may write both schemas — the identity user row (identity.SeedSuperadmin) and the tuple with its grant-ledger and audit rows (store.Grant).

func (SuperadminStep) Name

func (SuperadminStep) Name() string

func (SuperadminStep) Run

func (SuperadminStep) Run(ctx context.Context, deps *Deps) (Outcome, string, error)

type VerifyStep

type VerifyStep struct{}

VerifyStep re-reads everything the earlier steps seeded and reports drift found-and-not- overwritten — runtime-owned state is sacred. It is deliberately read-only: it never writes, so it is always Converged on success — a discrepancy it finds is reported as a Failed outcome with the diff, never silently repaired (repairing would be this step secretly becoming a second writer of runtime-owned state).

func (VerifyStep) Name

func (VerifyStep) Name() string

func (VerifyStep) Run

func (VerifyStep) Run(ctx context.Context, deps *Deps) (Outcome, string, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL