From 043ff99a51ecad8229389ddd04f45f4b25a23ac6 Mon Sep 17 00:00:00 2001 From: CaIon Date: Sat, 12 Sep 2026 19:33:53 +0800 Subject: [PATCH] fix: handle legacy database constraints and scoped policies Resolve obsolete PostgreSQL single-column unique constraints by their actual catalog names inside a locked transaction. Preserve unrelated indexes and roll back constraint removal when foreign keys depend on them. Load legacy authorization policies as structured fields. Preserve scoped rows during baseline reseeding and load unsupported own/other scopes as deny, preventing fallback to broader admin grants. Existing global grants remain usable; unsupported scoped grants require administrator review. Validation: fresh databases and rc.37 through rc.27, 60/60 combinations on SQLite 3.50.4, MySQL 5.7.44/8.0.46, and PostgreSQL 9.6.24/16.15. Each ran InitDB, separate InitLogDB, and authz.Init twice with persisted data. Focused schema, foreign-key rollback, and master/slave policy reload regressions passed, along with the authz package tests. Security references: OWASP ASVS 5.0.0 controls 8.2.1, 8.2.2, and 8.3.1; OWASP Authorization Cheat Sheet (least privilege and deny by default). --- model/migration_dialector.go | 45 ++++++++++++++++++++++++++-- model/migration_dialector_test.go | 43 +++++++++++++++++++++++++++ service/authz/adapter.go | 41 +++++++++++++++----------- service/authz/authz_test.go | 49 +++++++++++++++++++++++++++++++ service/authz/seed.go | 6 +++- 5 files changed, 164 insertions(+), 20 deletions(-) diff --git a/model/migration_dialector.go b/model/migration_dialector.go index 19197f68a4..f560409373 100644 --- a/model/migration_dialector.go +++ b/model/migration_dialector.go @@ -1,6 +1,7 @@ package model import ( + "fmt" "strings" "github.com/shopspring/decimal" @@ -10,8 +11,8 @@ import ( "gorm.io/gorm/schema" ) -// Embed the concrete dialectors to retain their transaction/savepoint and other -// optional GORM interfaces. Only schema comparison needs normalization. +// Embed the concrete dialectors to customize schema reconciliation while +// retaining transaction/savepoint and other optional GORM interfaces. type mysqlMigrationDialector struct{ mysql.Dialector } func (d mysqlMigrationDialector) Migrator(db *gorm.DB) gorm.Migrator { @@ -66,6 +67,46 @@ func (m postgresSchemaMigrator) MigrateColumn(value any, field *schema.Field, co return m.Migrator.MigrateColumn(value, field, column) } +// Older schemas and database imports can use a different constraint name from +// the current naming strategy. Resolve single-column uniqueness from the +// catalog instead of asking GORM to drop an inferred uni__. +func (m postgresSchemaMigrator) MigrateColumnUnique(value any, field *schema.Field, column gorm.ColumnType) error { + unique, ok := column.Unique() + if !ok || field.PrimaryKey || !unique || field.Unique { + return m.Migrator.MigrateColumnUnique(value, field, column) + } + return m.RunWithValue(value, func(stmt *gorm.Statement) error { + schemaName, tableName := m.CurrentSchema(stmt, stmt.Table) + return m.DB.Transaction(func(tx *gorm.DB) error { + if err := tx.Exec("LOCK TABLE ? IN ACCESS EXCLUSIVE MODE", m.CurrentTable(stmt)).Error; err != nil { + return err + } + var constraints []string + if err := tx.Raw(` +SELECT constraint_meta.conname +FROM pg_catalog.pg_constraint AS constraint_meta +JOIN pg_catalog.pg_class AS table_meta ON table_meta.oid = constraint_meta.conrelid +JOIN pg_catalog.pg_namespace AS schema_meta ON schema_meta.oid = table_meta.relnamespace +JOIN pg_catalog.pg_attribute AS attribute_meta + ON attribute_meta.attrelid = table_meta.oid + AND attribute_meta.attnum = constraint_meta.conkey[1] +WHERE schema_meta.nspname = ? AND table_meta.relname = ? + AND constraint_meta.contype = 'u' + AND cardinality(constraint_meta.conkey) = 1 + AND attribute_meta.attname = ? +ORDER BY constraint_meta.conname`, schemaName, tableName, field.DBName).Scan(&constraints).Error; err != nil { + return err + } + for _, name := range constraints { + if err := tx.Migrator().DropConstraint(value, name); err != nil { + return fmt.Errorf("drop obsolete unique constraint %q on %s.%s: %w", name, stmt.Table, field.DBName, err) + } + } + return nil + }) + }) +} + type charColumnType struct{ migrationColumnType } func (charColumnType) DatabaseTypeName() string { return "char" } diff --git a/model/migration_dialector_test.go b/model/migration_dialector_test.go index 539dca78fe..5e15b10293 100644 --- a/model/migration_dialector_test.go +++ b/model/migration_dialector_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/gorm" + "gorm.io/gorm/clause" ) type MigrationIdentityFields struct { @@ -141,6 +142,48 @@ func TestMigrationSchemaStability(t *testing.T) { require.NoError(t, db.Table(table).Create(&migrationConstraintV1{Name: "existing"}).Error) }) + if dialect == "postgres" { + t.Run("renamed_unique_constraints", func(t *testing.T) { + const table = "migration_renamed_unique" + t.Cleanup(func() { _ = db.Migrator().DropTable(table) }) + tableDB := db.Table(table).Session(&gorm.Session{}) + require.NoError(t, tableDB.AutoMigrate(&migrationConstraintV1{})) + original := migrationConstraintV1{Name: "existing"} + require.NoError(t, tableDB.Create(&original).Error) + for _, name := range []string{"models_model_name_key", `imported "model" name`} { + require.NoError(t, db.Exec("ALTER TABLE ? ADD CONSTRAINT ? UNIQUE (name)", clause.Table{Name: table}, clause.Column{Name: name}).Error) + } + require.NoError(t, db.Exec("ALTER TABLE ? ADD CONSTRAINT keep_composite UNIQUE (id, name)", clause.Table{Name: table}).Error) + require.NoError(t, db.Exec("CREATE INDEX keep_name_lookup ON ? (name)", clause.Table{Name: table}).Error) + // A unique field must keep the old names and still reject duplicates. + require.NoError(t, tableDB.AutoMigrate(&migrationConstraintV2{})) + require.Error(t, tableDB.Create(&migrationConstraintV2{Name: "existing"}).Error) + require.NoError(t, db.Exec("CREATE TABLE migration_unique_reference (name varchar(64) REFERENCES migration_renamed_unique(name))").Error) + t.Cleanup(func() { _ = db.Migrator().DropTable("migration_unique_reference") }) + require.NoError(t, db.Exec("INSERT INTO migration_unique_reference (name) VALUES (?)", "existing").Error) + require.Error(t, tableDB.AutoMigrate(&migrationConstraintV1{}), "dependent foreign keys must not be cascaded away") + for _, name := range []string{"models_model_name_key", `imported "model" name`} { + assert.True(t, tableDB.Migrator().HasConstraint(&migrationConstraintV1{}, name), "all old constraints must survive rollback") + } + var references int64 + require.NoError(t, db.Table("migration_unique_reference").Count(&references).Error) + assert.EqualValues(t, 1, references) + require.NoError(t, db.Migrator().DropTable("migration_unique_reference")) + // Removing column uniqueness must resolve both actual constraint names. + require.NoError(t, tableDB.AutoMigrate(&migrationConstraintV1{})) + recorder.reset() + require.NoError(t, tableDB.AutoMigrate(&migrationConstraintV1{})) + assert.Empty(t, recorder.schemaMutations()) + require.NoError(t, tableDB.Create(&migrationConstraintV1{Name: "existing"}).Error) + assert.True(t, tableDB.Migrator().HasConstraint(&migrationConstraintV1{}, "keep_composite")) + assert.True(t, tableDB.Migrator().HasIndex(&migrationConstraintV1{}, "keep_name_lookup")) + var rows []migrationConstraintV1 + require.NoError(t, tableDB.Order("id").Find(&rows).Error) + require.Len(t, rows, 2) + assert.Equal(t, original, rows[0]) + }) + } + if dialect == "mysql" { t.Run("decimal_default_and_real_changes", func(t *testing.T) { const table = "migration_decimal_test" diff --git a/service/authz/adapter.go b/service/authz/adapter.go index 4a2484c4d0..4237a2031a 100644 --- a/service/authz/adapter.go +++ b/service/authz/adapter.go @@ -1,8 +1,9 @@ package authz import ( - "strings" + "fmt" + "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/model" casbinmodel "github.com/casbin/casbin/v2/model" "github.com/casbin/casbin/v2/persist" @@ -24,7 +25,28 @@ func (a *gormAdapter) LoadPolicy(m casbinmodel.Model) error { return err } for _, rule := range rules { - if err := persist.LoadPolicyLine(ruleToLine(rule), m); err != nil { + if rule.Ptype != "p" { + // This model has no role-inheritance or other policy sections. + continue + } + if rule.V0 == "" || rule.V1 == "" || rule.V2 == "" { + return fmt.Errorf("authorization policy %d is missing a subject, resource or action", rule.Id) + } + effect := rule.V3 + if effect == "" { + effect = EffectAllow + } + if effect != EffectAllow && effect != EffectDeny { + return fmt.Errorf("authorization policy %d has an invalid effect", rule.Id) + } + if rule.V5 != "" || (rule.V4 != "" && rule.V4 != "all") { + // The current model cannot enforce legacy own/other scopes. Keep + // the stored rule for review and deny this permission in memory. + // Skipping a per-user rule would expose the admin role baseline. + effect = EffectDeny + common.SysLog(fmt.Sprintf("authorization policy %d has an unsupported legacy scope; loaded as deny; review the stored policy before granting access", rule.Id)) + } + if err := persist.LoadPolicyArray([]string{rule.Ptype, rule.V0, rule.V1, rule.V2, effect}, m); err != nil { return err } } @@ -104,18 +126,3 @@ func newRule(ptype string, policy []string) model.CasbinRule { } return rule } - -func ruleToLine(rule model.CasbinRule) string { - parts := []string{rule.Ptype} - values := []string{rule.V0, rule.V1, rule.V2, rule.V3, rule.V4, rule.V5} - if rule.Ptype == "p" && rule.V0 != "" && rule.V1 != "" && rule.V2 != "" && rule.V3 == "" { - values[3] = EffectAllow - } - for _, value := range values { - if value == "" { - continue - } - parts = append(parts, value) - } - return strings.Join(parts, ", ") -} diff --git a/service/authz/authz_test.go b/service/authz/authz_test.go index 4cf1f9b717..2d1542a5ec 100644 --- a/service/authz/authz_test.go +++ b/service/authz/authz_test.go @@ -77,6 +77,55 @@ func TestInitOnSlaveOnlyLoadsPolicies(t *testing.T) { assert.False(t, Can(2, common.RoleAdminUser, ChannelRead)) } +func TestLegacyScopedPoliciesDoNotExpandPermissions(t *testing.T) { + for _, master := range []bool{true, false} { + name := "master" + if !master { + name = "slave" + } + t.Run(name, func(t *testing.T) { + db := newAuthzTestDB(t) + common.IsMasterNode = master + rules := []model.CasbinRule{ + {Ptype: "p", V0: "role:vendor", V1: "channel", V2: "read", V3: "allow", V4: "own"}, + {Ptype: "p", V0: UserSubject(42), V1: "channel", V2: "read", V3: "allow", V4: "own"}, + {Ptype: "p", V0: UserSubject(43), V1: "channel", V2: "sensitive_write", V3: "allow", V4: "all"}, + {Ptype: "p", V0: UserSubject(44), V1: "channel", V2: "secret_view", V3: "deny", V4: "all"}, + {Ptype: "p", V0: UserSubject(45), V1: "channel", V2: "read"}, + {Ptype: "p", V0: UserSubject(46), V1: "channel", V2: "read", V3: "allow", V4: "unknown-scope"}, + {Ptype: "p", V0: UserSubject(47), V1: "channel", V2: "read", V3: "allow", V5: "own"}, + {Ptype: "p", V0: UserSubject(48), V1: "channel", V2: "read", V3: "allow", V4: "own"}, + {Ptype: "p", V0: UserSubject(48), V1: "channel", V2: "read", V3: "allow", V4: "all"}, + {Ptype: "p", V0: RoleSubject(BuiltInRoleAdmin), V1: "channel", V2: "operate", V3: "allow", V4: "own"}, + {Ptype: "p", V0: UserSubject(50), V1: "channel", V2: "sensitive_write", V3: "allow"}, + {Ptype: "g", V0: UserSubject(99), V1: RoleSubject(BuiltInRoleAdmin)}, + } + require.NoError(t, db.Create(&rules).Error) + ids := make([]uint, len(rules)) + for i := range rules { + ids[i] = rules[i].Id + } + for range 2 { + require.NoError(t, Init(db)) + require.NoError(t, ReloadPolicy()) + assert.False(t, Can(42, common.RoleAdminUser, ChannelRead), "own must not fall back to the admin allow baseline") + assert.True(t, Can(43, common.RoleAdminUser, ChannelSensitiveWrite)) + assert.False(t, Can(44, common.RoleAdminUser, ChannelSecretView)) + assert.True(t, Can(45, common.RoleAdminUser, ChannelRead)) + for _, userID := range []int{46, 47, 48} { + assert.False(t, Can(userID, common.RoleAdminUser, ChannelRead)) + } + assert.False(t, Can(51, common.RoleAdminUser, ChannelOperate), "reseed must not erase a scoped role restriction") + assert.True(t, Can(50, common.RoleAdminUser, ChannelSensitiveWrite)) + assert.False(t, Can(99, common.RoleCommonUser, ChannelRead)) + var stored []model.CasbinRule + require.NoError(t, db.Where("id IN ?", ids).Order("id").Find(&stored).Error) + assert.Equal(t, rules, stored, "legacy rows must remain available for administrator review") + } + }) + } +} + func TestSetUserPermissionsStoresOnlyOverrides(t *testing.T) { db := newAuthzTestDB(t) require.NoError(t, Init(db)) diff --git a/service/authz/seed.go b/service/authz/seed.go index 78536fcf94..e1c9a5af0a 100644 --- a/service/authz/seed.go +++ b/service/authz/seed.go @@ -39,7 +39,11 @@ func resetBuiltInRolePolicies(db *gorm.DB) error { for _, spec := range builtInRoles { subjects = append(subjects, RoleSubject(spec.Key)) } - return db.Where("ptype = ? AND v0 IN ?", "p", subjects).Delete(&model.CasbinRule{}).Error + // Scoped legacy rules must survive baseline reseeding so the adapter can + // retain their restrictions instead of replacing them with global grants. + return db.Where("ptype = ? AND v0 IN ?", "p", subjects). + Where("(v4 = ? OR v4 IS NULL) AND (v5 = ? OR v5 IS NULL)", "", ""). + Delete(&model.CasbinRule{}).Error } func seedDefaultPolicies() error {