Files
iam/internal/seed/seed_test.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

654 lines
25 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package seed
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/hanzoai/orm"
ormdb "github.com/hanzoai/orm/db"
"github.com/hanzoai/iam/pkg/schema"
)
func openDB(t *testing.T) orm.DB {
t.Helper()
_ = schema.Kinds() // force schema init() (kind registration)
db, err := orm.OpenSQLite(&ormdb.SQLiteDBConfig{
Path: filepath.Join(t.TempDir(), "seed.db"),
Config: ormdb.SQLiteConfig{BusyTimeout: 5000, JournalMode: "WAL"},
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
return db
}
const fixture = `{
"organizations": [{"owner":"admin","name":"hanzo"}],
"certs": [{"owner":"admin","name":"cert-hanzo","cryptoAlgorithm":"RS256","privateKey":"${TEST_CERT_KEY}"}],
"providers": [{"owner":"admin","name":"provider-github","category":"OAuth","type":"GitHub","clientId":"${TEST_GH_ID}"}],
"applications": [{"owner":"admin","name":"hanzo-console","clientId":"hanzo-console","organization":"hanzo","enablePassword":true}]
}`
func TestFromInitData_SeedsAndSubstitutesEnv(t *testing.T) {
db := openDB(t)
ctx := context.Background()
t.Setenv("TEST_CERT_KEY", "PEMDATA")
t.Setenv("TEST_GH_ID", "Iv23-real-github-id")
path := filepath.Join(t.TempDir(), "init_data.json")
if err := os.WriteFile(path, []byte(fixture), 0o600); err != nil {
t.Fatal(err)
}
sum, err := FromInitData(ctx, db, path)
if err != nil {
t.Fatalf("seed: %v", err)
}
for _, kind := range []string{"organizations", "certs", "providers", "applications"} {
if sum.Created[kind] != 1 {
t.Fatalf("%s created = %d, want 1", kind, sum.Created[kind])
}
}
// The application is resolvable and carries its fields.
app, err := orm.Get[schema.Application](db, "admin/hanzo-console")
if err != nil || app == nil {
t.Fatalf("app not seeded: %v", err)
}
if app.ClientId != "hanzo-console" || app.Organization != "hanzo" || !app.EnablePassword {
t.Fatalf("app fields wrong: clientId=%q org=%q pw=%v", app.ClientId, app.Organization, app.EnablePassword)
}
// ${VAR} was substituted from the environment (KMS-style injection).
prov, err := orm.Get[schema.Provider](db, "admin/provider-github")
if err != nil || prov == nil {
t.Fatalf("provider not seeded: %v", err)
}
if prov.ClientId != "Iv23-real-github-id" {
t.Fatalf("env not substituted: clientId=%q", prov.ClientId)
}
// The cert is seeded as metadata, and the key material the fixture carries is
// NOT stored: init_data.json rides a ConfigMap, and a signing key must not.
cert, _ := orm.Get[schema.Cert](db, "admin/cert-hanzo")
if cert == nil {
t.Fatal("cert not seeded")
}
if cert.PrivateKey != "" {
t.Fatalf("init_data key material reached the store: %q", cert.PrivateKey)
}
}
func TestFromInitData_NewOnlyIdempotent(t *testing.T) {
db := openDB(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "init_data.json")
_ = os.WriteFile(path, []byte(fixture), 0o600)
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
// Second run: everything already exists → all skipped, nothing created.
sum, err := FromInitData(ctx, db, path)
if err != nil {
t.Fatal(err)
}
for _, kind := range []string{"organizations", "certs", "providers", "applications"} {
if sum.Created[kind] != 0 || sum.Skipped[kind] != 1 {
t.Fatalf("%s: created=%d skipped=%d, want 0/1 (new-only)", kind, sum.Created[kind], sum.Skipped[kind])
}
}
}
func TestSubstituteEnv_UnsetBecomesEmpty(t *testing.T) {
os.Unsetenv("DEFINITELY_UNSET_VAR_XYZ")
got := substituteEnv([]byte(`x=${DEFINITELY_UNSET_VAR_XYZ}y`))
if string(got) != "x=y" {
t.Fatalf("unset var: got %q, want %q", got, "x=y")
}
}
// Seeding a cert stores its IDENTITY and none of its key material — owner, name,
// algorithm, expiry, all of which the JWKS publishes anyway. The key comes from
// what the deployment mounts (internal/keyring), so there is nothing here to
// write, and a fixture that states one states it in vain.
func TestSeed_StoresCertMetadataAndNoKeyMaterial(t *testing.T) {
db := openDB(t)
ctx := context.Background()
data := &initData{Certs: []*schema.Cert{
{Owner: "admin", Name: "cert-hanzo", Type: "x509", CryptoAlgorithm: "RS256"},
{Owner: "admin", Name: "cert-es", Type: "x509", CryptoAlgorithm: "ES256"},
// A fixture that states key material anyway: it is identity that is stored,
// so the declared key reaches no row.
{Owner: "admin", Name: "cert-explicit", Type: "x509", CryptoAlgorithm: "RS256", PrivateKey: "EXISTING-PEM"},
{Owner: "hanzo", Name: "cert-tenant", CryptoAlgorithm: "RS256"},
}}
if _, err := Apply(ctx, db, data); err != nil {
t.Fatalf("apply: %v", err)
}
for _, id := range []string{"admin/cert-hanzo", "admin/cert-es", "admin/cert-explicit", "hanzo/cert-tenant"} {
c, err := orm.Get[schema.Cert](db, id)
if err != nil || c == nil {
t.Fatalf("%s not seeded: %v", id, err)
}
if c.PrivateKey != "" {
t.Errorf("%s: key material reached the store: %q", id, c.PrivateKey)
}
if c.CryptoAlgorithm == "" {
t.Errorf("%s: metadata not seeded", id)
}
}
}
// ── declared application policy converges ────────────────────────────────────────
// Seeding is new-only, which is right for identity DATA but was wrong for
// application POLICY: with upsert skipping existing rows, flipping enableSignUp in
// init_data.json changed nothing on a seeded deployment. Production read
// enableSignUp=false — "the application does not allow to sign up new account" —
// while the declared state said otherwise, and only an out-of-band admin call could
// move it.
func TestSeed_DeclaredAppPolicyReconciles(t *testing.T) {
db := openDB(t)
ctx := context.Background()
dir := t.TempDir()
path := filepath.Join(dir, "init_data.json")
// First boot: signup off.
_ = os.WriteFile(path, []byte(fixture), 0o600)
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
app, err := orm.Get[schema.Application](db, "admin/hanzo-console")
if err != nil || app == nil {
t.Fatalf("seed application: %v", err)
}
if app.EnableSignUp {
t.Fatal("fixture should start with signup disabled")
}
// The operator declares signup on. A converging seed must apply it.
on := `{
"organizations": [{"owner":"admin","name":"hanzo"}],
"applications": [{"owner":"admin","name":"hanzo-console","clientId":"hanzo-console","organization":"hanzo","enablePassword":true,"enableSignUp":true}]
}`
_ = os.WriteFile(path, []byte(on), 0o600)
sum, err := FromInitData(ctx, db, path)
if err != nil {
t.Fatal(err)
}
if sum.Reconciled["applications"] != 1 {
t.Fatalf("reconciled=%d, want 1", sum.Reconciled["applications"])
}
app, _ = orm.Get[schema.Application](db, "admin/hanzo-console")
if !app.EnableSignUp {
t.Fatal("declared enableSignUp=true did not converge onto the existing row")
}
}
// The reason reconcile merges the RAW declared object rather than saving the decoded
// struct: clientSecret is generated at first seed and never written back to
// init_data.json. Saving a decoded struct would blank it and lock every OAuth client
// out — the same de-secret hazard update-application had to fix. A field the file
// does not mention must keep its stored value.
func TestSeed_ReconcileKeepsUndeclaredFields(t *testing.T) {
db := openDB(t)
ctx := context.Background()
dir := t.TempDir()
path := filepath.Join(dir, "init_data.json")
_ = os.WriteFile(path, []byte(fixture), 0o600)
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
// Stand in for the secret the deployment generates after the first seed.
if _, err := orm.GetOrUpdate[schema.Application](db, "admin/hanzo-console", func(a *schema.Application) {
a.ClientSecret = "generated-at-first-boot"
}); err != nil {
t.Fatal(err)
}
// init_data.json carries NO clientSecret — reconciling must not erase it.
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
app, _ := orm.Get[schema.Application](db, "admin/hanzo-console")
if app.ClientSecret != "generated-at-first-boot" {
t.Fatalf("reconcile blanked an undeclared field: clientSecret=%q", app.ClientSecret)
}
// And a declared field is still authoritative.
if !app.EnablePassword {
t.Fatal("declared enablePassword=true should hold")
}
}
// Live applications legitimately carry redirect URIs and grants init_data.json
// does not list, so reconciling the WHOLE declared object would delete them and
// break the very logins the flag change was meant to fix. The reconcile is
// narrowed to policy keys; this is the guard on that.
func TestSeed_ReconcileNeverStripsRegistration(t *testing.T) {
db := openDB(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "init_data.json")
_ = os.WriteFile(path, []byte(fixture), 0o600)
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
// Stand in for registration that drifted ahead of the file, as production had.
if _, err := orm.GetOrUpdate[schema.Application](db, "admin/hanzo-console", func(a *schema.Application) {
a.RedirectUris = []string{"https://console.hanzo.ai/callback", "https://admin.hanzo.ai/auth/callback"}
a.GrantTypes = []string{"authorization_code", "refresh_token", "client_credentials"}
a.ClientSecret = "generated-at-first-boot"
}); err != nil {
t.Fatal(err)
}
// The file declares neither, and now flips a policy flag.
on := `{
"organizations": [{"owner":"admin","name":"hanzo"}],
"applications": [{"owner":"admin","name":"hanzo-console","clientId":"hanzo-console","organization":"hanzo","enablePassword":true,"enableSignUp":true}]
}`
_ = os.WriteFile(path, []byte(on), 0o600)
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
app, _ := orm.Get[schema.Application](db, "admin/hanzo-console")
if !app.EnableSignUp {
t.Fatal("declared policy must converge")
}
if len(app.RedirectUris) != 2 {
t.Fatalf("registration must survive: redirectUris=%v", app.RedirectUris)
}
if len(app.GrantTypes) != 3 {
t.Fatalf("registration must survive: grantTypes=%v", app.GrantTypes)
}
if app.ClientSecret != "generated-at-first-boot" {
t.Fatalf("clientSecret must survive: %q", app.ClientSecret)
}
}
// Passkeys must converge like every other declared policy flag.
//
// A policy key absent from appPolicyKeys never converges: a new-only upsert does
// not carry its declared value to a seeded row, so init_data.json can declare
// enableWebAuthn TRUE while /v1/iam/auth/methods answers `webauthn:false`, and the
// two never reconcile. enableWebAuthn belongs on the reconcile for the same reason
// enableSignUp does — it is declared policy, not registration drift — and this
// pins that it converges.
func TestSeed_ReconcileConvergesWebAuthn(t *testing.T) {
db := openDB(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "init_data.json")
// A seeded row with passkeys OFF — the production state.
off := `{
"organizations": [{"owner":"admin","name":"hanzo"}],
"applications": [{"owner":"admin","name":"hanzo-console","clientId":"hanzo-console","organization":"hanzo","enablePassword":true,"enableWebAuthn":false}]
}`
if err := os.WriteFile(path, []byte(off), 0o600); err != nil {
t.Fatal(err)
}
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
app, err := orm.Get[schema.Application](db, "admin/hanzo-console")
if err != nil || app == nil {
t.Fatalf("seed application: %v", err)
}
if app.EnableWebAuthn {
t.Fatal("fixture should start with passkeys disabled")
}
// The operator declares passkeys on. A converging seed must apply it.
on := `{
"organizations": [{"owner":"admin","name":"hanzo"}],
"applications": [{"owner":"admin","name":"hanzo-console","clientId":"hanzo-console","organization":"hanzo","enablePassword":true,"enableWebAuthn":true}]
}`
if err := os.WriteFile(path, []byte(on), 0o600); err != nil {
t.Fatal(err)
}
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
app, _ = orm.Get[schema.Application](db, "admin/hanzo-console")
if !app.EnableWebAuthn {
t.Fatal("declared enableWebAuthn=true did not converge onto the existing row")
}
// ...and it converges BACK off, so the file stays authoritative in both
// directions. A one-way flag would be a trapdoor, not a declaration.
if err := os.WriteFile(path, []byte(off), 0o600); err != nil {
t.Fatal(err)
}
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
app, _ = orm.Get[schema.Application](db, "admin/hanzo-console")
if app.EnableWebAuthn {
t.Fatal("declared enableWebAuthn=false did not converge back off")
}
}
// ── store faults propagate ───────────────────────────────────────────────────────
// Every kind's upsert reaches orm.GetOrCreate, whose read fails on a closed store
// with a real fault (not ErrNotFound), so Apply surfaces it instead of swallowing
// it. Each case carries ONLY its kind so the fault lands on that kind's loop —
// Apply returns on the first error, so an earlier kind would mask a later one.
func TestApply_StoreFaultPropagates(t *testing.T) {
ctx := context.Background()
cases := []struct {
kind string
data *initData
}{
{"organizations", &initData{Organizations: []*schema.Organization{{Owner: "admin", Name: "hanzo"}}}},
{"providers", &initData{Providers: []*schema.Provider{{Owner: "admin", Name: "provider-github", Category: "OAuth", Type: "GitHub"}}}},
{"certs", &initData{Certs: []*schema.Cert{{Owner: "admin", Name: "cert-hanzo", CryptoAlgorithm: "RS256"}}}},
{"applications", &initData{Applications: []*schema.Application{{Owner: "admin", Name: "hanzo-console", ClientId: "hanzo-console"}}}},
}
for _, c := range cases {
t.Run(c.kind, func(t *testing.T) {
db := openDB(t)
_ = db.Close() // the store is gone before the write
if _, err := Apply(ctx, db, c.data); err == nil {
t.Fatalf("%s: a closed store seeded without error", c.kind)
}
})
}
}
// A missing path and a malformed document both fail before any upsert — read and
// parse are the two ways FromInitData can refuse a file.
func TestFromInitData_FileErrors(t *testing.T) {
ctx := context.Background()
t.Run("read", func(t *testing.T) {
db := openDB(t)
if _, err := FromInitData(ctx, db, filepath.Join(t.TempDir(), "absent.json")); err == nil {
t.Fatal("a missing init_data.json seeded without error")
}
})
t.Run("parse", func(t *testing.T) {
db := openDB(t)
path := filepath.Join(t.TempDir(), "init_data.json")
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := FromInitData(ctx, db, path); err == nil {
t.Fatal("malformed init_data.json parsed without error")
}
})
}
// ── owner defaulting ─────────────────────────────────────────────────────────────
// A missing owner is the admin org: Apply and upsert both default "" to "admin",
// so every entity declared without an owner resolves under admin/<name>.
func TestApply_DefaultsEmptyOwnerToAdmin(t *testing.T) {
db := openDB(t)
ctx := context.Background()
data := &initData{
Organizations: []*schema.Organization{{Name: "hanzo"}},
Providers: []*schema.Provider{{Name: "provider-github", Category: "OAuth", Type: "GitHub"}},
Certs: []*schema.Cert{{Name: "cert-hanzo", CryptoAlgorithm: "RS256"}},
Applications: []*schema.Application{{Name: "hanzo-console", ClientId: "hanzo-console"}},
}
sum, err := Apply(ctx, db, data)
if err != nil {
t.Fatalf("apply: %v", err)
}
for _, kind := range []string{"organizations", "providers", "certs", "applications"} {
if sum.Created[kind] != 1 {
t.Fatalf("%s created = %d, want 1", kind, sum.Created[kind])
}
}
if org, err := orm.Get[schema.Organization](db, "admin/hanzo"); err != nil || org == nil {
t.Fatalf("owner-less org not under admin: %v", err)
}
if app, err := orm.Get[schema.Application](db, "admin/hanzo-console"); err != nil || app == nil || app.Owner != "admin" {
t.Fatalf("owner-less app not under admin: %v", err)
}
}
// An owner-less declaration is the platform's: its row carries the admin owner
// its key names, so an application it declares to serve every org does
// (schema.Application.ServesAnyOrg reads Owner), and it is marked the platform's.
func TestApply_OwnerlessDeclarationIsThePlatforms(t *testing.T) {
db := openDB(t)
data := &initData{Applications: []*schema.Application{
{Name: "hanzo-app", ClientId: "hanzo-app", Organization: "hanzo", OrgChoiceMode: "create"},
}}
if _, err := Apply(context.Background(), db, data); err != nil {
t.Fatalf("apply: %v", err)
}
app, err := orm.Get[schema.Application](db, "admin/hanzo-app")
if err != nil {
t.Fatal(err)
}
if app.Owner != "admin" || !app.ServesAnyOrg() || !app.Platform {
t.Fatalf("owner=%q servesAnyOrg=%v platform=%v, want admin/true/true", app.Owner, app.ServesAnyOrg(), app.Platform)
}
}
// FromInitData defaults a missing owner the same way for the RAW declared object it
// keys for reconcile, so an owner-less application seeds under admin and stays
// reconcilable on a later boot.
func TestFromInitData_DefaultsMissingOwner(t *testing.T) {
db := openDB(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "init_data.json")
doc := `{"applications":[{"name":"console","clientId":"console","enablePassword":true}]}`
if err := os.WriteFile(path, []byte(doc), 0o600); err != nil {
t.Fatal(err)
}
sum, err := FromInitData(ctx, db, path)
if err != nil {
t.Fatal(err)
}
if sum.Created["applications"] != 1 {
t.Fatalf("created=%d, want 1", sum.Created["applications"])
}
if app, err := orm.Get[schema.Application](db, "admin/console"); err != nil || app == nil || app.Owner != "admin" {
t.Fatalf("owner-less app not under admin: %v", err)
}
}
// ── reconcile no-ops ─────────────────────────────────────────────────────────────
// Apply from a literal carries no raw declared objects, so a second run finds the
// row present, counts it skipped, and reconcile has nothing to converge — it is
// FromInitData that populates the declared map, not Apply.
func TestApply_LiteralReconcileNoopWhenNotDeclared(t *testing.T) {
db := openDB(t)
ctx := context.Background()
data := &initData{Applications: []*schema.Application{
{Owner: "admin", Name: "hanzo-console", ClientId: "hanzo-console", EnableSignUp: true},
}}
if _, err := Apply(ctx, db, data); err != nil {
t.Fatal(err)
}
sum, err := Apply(ctx, db, data)
if err != nil {
t.Fatal(err)
}
if sum.Skipped["applications"] != 1 {
t.Fatalf("skipped=%d, want 1", sum.Skipped["applications"])
}
if sum.Reconciled["applications"] != 0 {
t.Fatalf("reconciled=%d, want 0 (nothing declared to converge)", sum.Reconciled["applications"])
}
}
// An existing application re-declared with no policy keys — only name and clientId,
// which are registration, not policy — has nothing to converge, so reconcile
// returns before touching the row and the run reconciles nothing.
func TestFromInitData_ReconcileEmptyPolicyNoop(t *testing.T) {
db := openDB(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "init_data.json")
doc := `{"applications":[{"owner":"admin","name":"plain","clientId":"plain"}]}`
if err := os.WriteFile(path, []byte(doc), 0o600); err != nil {
t.Fatal(err)
}
if _, err := FromInitData(ctx, db, path); err != nil {
t.Fatal(err)
}
sum, err := FromInitData(ctx, db, path)
if err != nil {
t.Fatal(err)
}
if sum.Skipped["applications"] != 1 {
t.Fatalf("skipped=%d, want 1", sum.Skipped["applications"])
}
if sum.Reconciled["applications"] != 0 {
t.Fatalf("reconciled=%d, want 0 (no policy declared)", sum.Reconciled["applications"])
}
}
// A document that declares registration is refused, by name, at load.
//
// This is the failure the refusal exists to make impossible: hanzo-dataroom was
// created before it carried any callback, IAM derived one from its homepage, and
// every later edit to redirectUris in init_data.json was dropped without a word.
// The application then answered "invalid redirect_uri" for the exact callback
// its own configuration named, and the file that looked authoritative was the
// one place the answer was not.
func TestFromInitData_RefusesRegistration(t *testing.T) {
for _, key := range []string{"redirectUris", "grantTypes"} {
t.Run(key, func(t *testing.T) {
db := openDB(t)
doc := `{"applications":[{"owner":"admin","name":"hanzo-dataroom","organization":"hanzo","` +
key + `":["https://dataroom.hanzo.ai/api/auth/callback/hanzo-iam"]}]}`
path := filepath.Join(t.TempDir(), "init_data.json")
if err := os.WriteFile(path, []byte(doc), 0o600); err != nil {
t.Fatal(err)
}
_, err := FromInitData(context.Background(), db, path)
if err == nil {
t.Fatalf("%s was accepted; a field this file cannot apply must not be sayable", key)
}
// The message has to name the application and the field, or it sends
// the reader back to the same guess that cost the outage.
for _, want := range []string{"hanzo-dataroom", key, "provision"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("error must name %q, got: %v", want, err)
}
}
// And nothing was written: a refused document is a refused document.
if app, _ := orm.Get[schema.Application](db, "admin/hanzo-dataroom"); app != nil {
t.Fatal("a refused document still seeded the application")
}
})
}
}
// The same document without registration loads.
func TestFromInitData_AcceptsPolicyOnly(t *testing.T) {
db := openDB(t)
doc := `{"applications":[{"owner":"admin","name":"hanzo-dataroom","organization":"hanzo","enableSignUp":false}]}`
path := filepath.Join(t.TempDir(), "init_data.json")
if err := os.WriteFile(path, []byte(doc), 0o600); err != nil {
t.Fatal(err)
}
if _, err := FromInitData(context.Background(), db, path); err != nil {
t.Fatalf("policy-only document refused: %v", err)
}
if app, _ := orm.Get[schema.Application](db, "admin/hanzo-dataroom"); app == nil {
t.Fatal("policy-only document seeded nothing")
}
}
// The seed declares platform applications, and a platform row outranks a tenant's
// of the same name wherever a name alone is resolved. Created beside a tenant's
// application of that name, it would pull every account the tenant registered into
// the platform's org, so that one declaration is refused and reported. The rest of
// the seed still applies: a tenant picks its names, and a name it picked must not
// keep the platform's policy off every other application.
func TestApply_RefusesANameAnotherOwnerHoldsAndAppliesTheRest(t *testing.T) {
db := openDB(t)
ctx := context.Background()
tenant := orm.New[schema.Application](db)
tenant.Owner, tenant.Name, tenant.Organization = "acme", "hanzo-new", "acme"
tenant.SetId("acme/hanzo-new")
if err := tenant.CreateCtx(ctx); err != nil {
t.Fatalf("seed tenant app: %v", err)
}
sum, err := Apply(ctx, db, &initData{Applications: []*schema.Application{
{Owner: "admin", Name: "hanzo-new", ClientId: "hanzo-new", Organization: "hanzo"},
{Owner: "admin", Name: "hanzo-next", ClientId: "hanzo-next", Organization: "hanzo"},
}})
if err != nil {
t.Fatalf("a tenant's name stopped the seed: %v", err)
}
if a, _ := orm.Get[schema.Application](db, "admin/hanzo-new"); a != nil {
t.Fatal("the seed created a platform app beside a tenant's app of the same name")
}
if len(sum.Refused) != 1 || !strings.HasPrefix(sum.Refused[0], "admin/hanzo-new: ") {
t.Fatalf("refused = %q, want the one declaration named", sum.Refused)
}
if a, _ := orm.Get[schema.Application](db, "admin/hanzo-next"); a == nil {
t.Fatal("the declaration after the refused one was not applied")
}
}
// The platform's own applications are exactly the ones the file declares under
// the admin org: marked on the run that creates them and on every run after,
// whatever the row said meanwhile. One declared under an ordinary org — whose
// admin can write it — is not, and neither is one the file does not declare,
// even when it was marked before.
func TestApply_DeclaredAdminApplicationsAreThePlatforms(t *testing.T) {
db := openDB(t)
ctx := context.Background()
for _, row := range []struct{ owner, name string }{{"admin", "acme-app"}, {"admin", "retired"}} {
a := orm.New[schema.Application](db)
a.Owner, a.Name, a.ClientId, a.Platform = row.owner, row.name, row.name, row.name == "retired"
a.SetId(row.owner + "/" + row.name)
if err := a.CreateCtx(ctx); err != nil {
t.Fatal(err)
}
}
data := &initData{Applications: []*schema.Application{
{Owner: "admin", Name: "hanzo-app", ClientId: "hanzo-app", Organization: "hanzo"},
{Owner: "karma", Name: "karma-style", ClientId: "karma-style", Organization: "karma"},
}}
platform := func(id string) bool {
app, err := orm.Get[schema.Application](db, id)
if err != nil {
t.Fatal(err)
}
return app.Platform
}
if _, err := Apply(ctx, db, data); err != nil {
t.Fatal(err)
}
for id, want := range map[string]bool{"admin/hanzo-app": true, "karma/karma-style": false, "admin/acme-app": false, "admin/retired": false} {
if platform(id) != want {
t.Fatalf("after the first run %s platform=%v, want %v", id, !want, want)
}
}
app, _ := orm.Get[schema.Application](db, "admin/hanzo-app")
app.Platform = false
if err := app.UpdateCtx(ctx); err != nil {
t.Fatal(err)
}
if _, err := Apply(ctx, db, data); err != nil {
t.Fatal(err)
}
if !platform("admin/hanzo-app") {
t.Fatal("the next run did not mark the declared application again")
}
}