This commit is contained in:
Yvan
2026-08-17 07:44:52 +08:00
parent d09e6b42bd
commit 9715b2ef1a
28 changed files with 1586 additions and 326 deletions
-204
View File
@@ -8,10 +8,7 @@ import (
"kra/internal/biz"
"github.com/casbin/casbin/v3"
casbinmodel "github.com/casbin/casbin/v3/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type apiRepo struct{ data *Data }
@@ -181,204 +178,3 @@ func (r *apiRepo) ListAPIs(ctx context.Context, page, size int, q *biz.API) ([]*
}
return out, total, nil
}
func (r *apiRepo) APIRoleIDs(ctx context.Context, path, method string) ([]uint, error) {
rows := make([]casbinRulePO, 0)
err := policyScope(r.data.gormDB.WithContext(ctx)).
Where("v1 = ? AND v2 = ?", path, method).
Find(&rows).Error
if err != nil {
return nil, err
}
ids := make([]uint, 0, len(rows))
for _, row := range rows {
id, err := strconv.ParseUint(row.V0, 10, 64)
if err != nil {
continue
}
ids = append(ids, uint(id))
}
return ids, nil
}
func (r *apiRepo) SetAPIRoles(ctx context.Context, path, method string, ids []uint) error {
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// A path/method need not be present in sys_apis when replacing
// all matching policy rows. Do not validate or deduplicate authority IDs.
if err := deletePoliciesForPath(tx, path, method); err != nil {
return err
}
if len(ids) == 0 {
return nil
}
rules := make([]casbinRulePO, 0, len(ids))
for _, aid := range ids {
rules = append(rules, newPolicyRule(aid, path, method))
}
return tx.Create(&rules).Error
})
}
func (r *apiRepo) Authorize(ctx context.Context, aid uint, path, method string) (bool, error) {
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
if err != nil {
return false, err
}
model, err := casbinmodel.NewModelFromString(`[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && keyMatch2(r.obj, p.obj) && r.act == p.act`)
if err != nil {
return false, err
}
enforcer, err := casbin.NewEnforcer(model)
if err != nil {
return false, err
}
subject := strconv.FormatUint(uint64(aid), 10)
for _, policy := range rows {
if _, err := enforcer.AddPolicy(subject, policy.V1, policy.V2); err != nil {
return false, err
}
}
return enforcer.Enforce(subject, path, method)
}
func (r *apiRepo) PolicyPaths(ctx context.Context, aid uint) ([]*biz.API, error) {
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
if err != nil {
return nil, err
}
var out []*biz.API
if len(rows) > 0 {
out = make([]*biz.API, 0, len(rows))
}
for _, row := range rows {
out = append(out, &biz.API{Path: row.V1, Method: row.V2})
}
return out, nil
}
func (r *apiRepo) SetPolicyPaths(ctx context.Context, aid uint, paths []*biz.API) error {
if err := (&authorityAccessRepo{data: r.data}).checkAuthorityIDAuth(ctx, aid); err != nil {
return err
}
config := r.data.runtime.Admin()
if actor, ok := biz.ActorFromContext(ctx); ok && config != nil && config.System != nil && config.System.UseStrictAuth {
var authority authorityPO
if err := r.data.gormDB.WithContext(ctx).Where("authority_id = ?", actor.AuthorityID).First(&authority).Error; err != nil {
return err
}
var registered []apiPO
if err := r.data.gormDB.WithContext(ctx).Find(&registered).Error; err != nil {
return err
}
allowedSet := make(map[string]bool, len(registered))
if authority.ParentID == nil || *authority.ParentID == 0 {
for _, item := range registered {
allowedSet[item.Path+"\x00"+item.Method] = true
}
} else {
policies, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), actor.AuthorityID)
if err != nil {
return err
}
policySet := make(map[string]bool, len(policies))
for _, item := range policies {
policySet[item.V1+"\x00"+item.V2] = true
}
for _, item := range registered {
key := item.Path + "\x00" + item.Method
if policySet[key] {
allowedSet[key] = true
}
}
}
for _, item := range paths {
if !allowedSet[item.Path+"\x00"+item.Method] {
return errors.New("存在api不在权限列表中")
}
}
}
db := r.data.gormDB.WithContext(ctx)
// The reference enforcer removes the old authority policies before it
// attempts to add the replacement set. Keep that ordering visible even
// though Kra reads policies directly from the database rather than through
// an in-memory enforcer.
if err := deletePoliciesForAuthority(db, aid); err != nil {
return err
}
// Keep the legacy relation table clean for upgraded installations. It is
// not consulted for authorization anymore.
if err := db.Where("authority_id = ?", aid).Delete(&authorityAPIPO{}).Error; err != nil {
return err
}
rules := make([]casbinRulePO, 0, len(paths))
seen := make(map[string]struct{})
for _, path := range paths {
key := strconv.FormatUint(uint64(aid), 10) + path.Path + path.Method
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
rules = append(rules, newPolicyRule(aid, path.Path, path.Method))
}
if len(rules) > 0 {
return db.Clauses(clause.OnConflict{DoNothing: true}).Create(&rules).Error
}
return nil
}
func (r *apiRepo) IgnoredAPIs(ctx context.Context) ([]*biz.API, error) {
var pos []ignoredAPIPO
if err := r.data.gormDB.WithContext(ctx).Find(&pos).Error; err != nil {
return nil, err
}
out := make([]*biz.API, 0, len(pos))
for _, po := range pos {
out = append(out, &biz.API{Path: po.Path, Method: po.Method})
}
return out, nil
}
func (r *apiRepo) SetAPIIgnored(ctx context.Context, path, method string, ignored bool) error {
po := ignoredAPIPO{Path: path, Method: method}
if ignored {
// The compatible endpoint creates an ignore row on every request (the table has no
// path/method uniqueness constraint); retain that observable behavior.
return r.data.gormDB.WithContext(ctx).Create(&po).Error
}
return r.data.gormDB.WithContext(ctx).Unscoped().Where("path = ? AND method = ?", po.Path, po.Method).Delete(&ignoredAPIPO{}).Error
}
func (r *apiRepo) ApplyAPISync(ctx context.Context, added, deleted []*biz.API) error {
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if len(added) > 0 {
pos := make([]apiPO, 0, len(added))
for _, item := range added {
pos = append(pos, apiPO{Path: item.Path, Method: item.Method, Description: item.Description, APIGroup: item.APIGroup})
}
// Insert the submitted newApis slice as-is. Do not silently
// collapse repeated/existing path+method pairs here; sys_apis itself
// intentionally has no uniqueness constraint.
if err := tx.Create(&pos).Error; err != nil {
return err
}
}
for _, item := range deleted {
var ids []uint
if err := tx.Model(&apiPO{}).Where("path = ? AND method = ?", item.Path, item.Method).Pluck("id", &ids).Error; err != nil {
return err
}
if len(ids) > 0 {
if err := deletePoliciesForPath(tx, item.Path, item.Method); err != nil {
return err
}
if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
return err
}
if err := tx.Where("id IN ?", ids).Delete(&apiPO{}).Error; err != nil {
return err
}
}
}
return nil
})
}
+161
View File
@@ -0,0 +1,161 @@
package data
import (
"context"
"errors"
"strconv"
"kra/internal/biz"
"github.com/casbin/casbin/v3"
casbinmodel "github.com/casbin/casbin/v3/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func (r *apiRepo) APIRoleIDs(ctx context.Context, path, method string) ([]uint, error) {
rows := make([]casbinRulePO, 0)
err := policyScope(r.data.gormDB.WithContext(ctx)).
Where("v1 = ? AND v2 = ?", path, method).
Find(&rows).Error
if err != nil {
return nil, err
}
ids := make([]uint, 0, len(rows))
for _, row := range rows {
id, err := strconv.ParseUint(row.V0, 10, 64)
if err != nil {
continue
}
ids = append(ids, uint(id))
}
return ids, nil
}
func (r *apiRepo) SetAPIRoles(ctx context.Context, path, method string, ids []uint) error {
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// A path/method need not be present in sys_apis when replacing
// all matching policy rows. Do not validate or deduplicate authority IDs.
if err := deletePoliciesForPath(tx, path, method); err != nil {
return err
}
if len(ids) == 0 {
return nil
}
rules := make([]casbinRulePO, 0, len(ids))
for _, aid := range ids {
rules = append(rules, newPolicyRule(aid, path, method))
}
return tx.Create(&rules).Error
})
}
func (r *apiRepo) Authorize(ctx context.Context, aid uint, path, method string) (bool, error) {
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
if err != nil {
return false, err
}
model, err := casbinmodel.NewModelFromString(`[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && keyMatch2(r.obj, p.obj) && r.act == p.act`)
if err != nil {
return false, err
}
enforcer, err := casbin.NewEnforcer(model)
if err != nil {
return false, err
}
subject := strconv.FormatUint(uint64(aid), 10)
for _, policy := range rows {
if _, err := enforcer.AddPolicy(subject, policy.V1, policy.V2); err != nil {
return false, err
}
}
return enforcer.Enforce(subject, path, method)
}
func (r *apiRepo) PolicyPaths(ctx context.Context, aid uint) ([]*biz.API, error) {
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
if err != nil {
return nil, err
}
var out []*biz.API
if len(rows) > 0 {
out = make([]*biz.API, 0, len(rows))
}
for _, row := range rows {
out = append(out, &biz.API{Path: row.V1, Method: row.V2})
}
return out, nil
}
func (r *apiRepo) SetPolicyPaths(ctx context.Context, aid uint, paths []*biz.API) error {
if err := (&authorityAccessRepo{data: r.data}).checkAuthorityIDAuth(ctx, aid); err != nil {
return err
}
config := r.data.runtime.Admin()
if actor, ok := biz.ActorFromContext(ctx); ok && config != nil && config.System != nil && config.System.UseStrictAuth {
var authority authorityPO
if err := r.data.gormDB.WithContext(ctx).Where("authority_id = ?", actor.AuthorityID).First(&authority).Error; err != nil {
return err
}
var registered []apiPO
if err := r.data.gormDB.WithContext(ctx).Find(&registered).Error; err != nil {
return err
}
allowedSet := make(map[string]bool, len(registered))
if authority.ParentID == nil || *authority.ParentID == 0 {
for _, item := range registered {
allowedSet[item.Path+"\x00"+item.Method] = true
}
} else {
policies, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), actor.AuthorityID)
if err != nil {
return err
}
policySet := make(map[string]bool, len(policies))
for _, item := range policies {
policySet[item.V1+"\x00"+item.V2] = true
}
for _, item := range registered {
key := item.Path + "\x00" + item.Method
if policySet[key] {
allowedSet[key] = true
}
}
}
for _, item := range paths {
if !allowedSet[item.Path+"\x00"+item.Method] {
return errors.New("存在api不在权限列表中")
}
}
}
db := r.data.gormDB.WithContext(ctx)
// The reference enforcer removes the old authority policies before it
// attempts to add the replacement set. Keep that ordering visible even
// though Kra reads policies directly from the database rather than through
// an in-memory enforcer.
if err := deletePoliciesForAuthority(db, aid); err != nil {
return err
}
// Keep the legacy relation table clean for upgraded installations. It is
// not consulted for authorization anymore.
if err := db.Where("authority_id = ?", aid).Delete(&authorityAPIPO{}).Error; err != nil {
return err
}
rules := make([]casbinRulePO, 0, len(paths))
seen := make(map[string]struct{})
for _, path := range paths {
key := strconv.FormatUint(uint64(aid), 10) + path.Path + path.Method
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
rules = append(rules, newPolicyRule(aid, path.Path, path.Method))
}
if len(rules) > 0 {
return db.Clauses(clause.OnConflict{DoNothing: true}).Create(&rules).Error
}
return nil
}
+64
View File
@@ -0,0 +1,64 @@
package data
import (
"context"
"kra/internal/biz"
"gorm.io/gorm"
)
func (r *apiRepo) IgnoredAPIs(ctx context.Context) ([]*biz.API, error) {
var pos []ignoredAPIPO
if err := r.data.gormDB.WithContext(ctx).Find(&pos).Error; err != nil {
return nil, err
}
out := make([]*biz.API, 0, len(pos))
for _, po := range pos {
out = append(out, &biz.API{Path: po.Path, Method: po.Method})
}
return out, nil
}
func (r *apiRepo) SetAPIIgnored(ctx context.Context, path, method string, ignored bool) error {
po := ignoredAPIPO{Path: path, Method: method}
if ignored {
// The compatible endpoint creates an ignore row on every request (the table has no
// path/method uniqueness constraint); retain that observable behavior.
return r.data.gormDB.WithContext(ctx).Create(&po).Error
}
return r.data.gormDB.WithContext(ctx).Unscoped().Where("path = ? AND method = ?", po.Path, po.Method).Delete(&ignoredAPIPO{}).Error
}
func (r *apiRepo) ApplyAPISync(ctx context.Context, added, deleted []*biz.API) error {
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if len(added) > 0 {
pos := make([]apiPO, 0, len(added))
for _, item := range added {
pos = append(pos, apiPO{Path: item.Path, Method: item.Method, Description: item.Description, APIGroup: item.APIGroup})
}
// Insert the submitted newApis slice as-is. Do not silently
// collapse repeated/existing path+method pairs here; sys_apis itself
// intentionally has no uniqueness constraint.
if err := tx.Create(&pos).Error; err != nil {
return err
}
}
for _, item := range deleted {
var ids []uint
if err := tx.Model(&apiPO{}).Where("path = ? AND method = ?", item.Path, item.Method).Pluck("id", &ids).Error; err != nil {
return err
}
if len(ids) > 0 {
if err := deletePoliciesForPath(tx, item.Path, item.Method); err != nil {
return err
}
if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
return err
}
if err := tx.Where("id IN ?", ids).Delete(&apiPO{}).Error; err != nil {
return err
}
}
}
return nil
})
}
+1 -1
View File
@@ -28,7 +28,7 @@ func TestLogViewerReadsNestedCategoryFiles(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(files) != 1 || files[0].Path != filepath.Join("http", "access.log") {
if len(files) != 1 || files[0].Path != "http/access.log" {
t.Fatalf("unexpected nested log files: %+v", files)
}
content, err := repo.LogContent(context.Background(), date, "http/access.log", nil)