1 parent
9be7a6f990
commit
fcbcf91d66
23 files changed
+811
-81
No files matched your search
@@ -26,6 +26,7 @@ const (
|
||||
CapabilityAuditRead Capability = "audit.read"
|
||||
CapabilityAuditExport Capability = "audit.export"
|
||||
CapabilityNotificationManage Capability = "notification.manage"
|
||||
CapabilityAccountGroupManage Capability = "account_group.manage"
|
||||
)
|
||||
|
||||
type Policy struct {
|
||||
@@ -37,6 +38,7 @@ type Policy struct {
|
||||
}
|
||||
|
||||
var policies = map[Capability]Policy{
|
||||
CapabilityAccountGroupManage: {Capability: CapabilityAccountGroupManage, HighRisk: true, RequiresRecentAuth: true},
|
||||
CapabilityNotificationManage: {Capability: CapabilityNotificationManage, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true},
|
||||
CapabilityConfigRead: {Capability: CapabilityConfigRead},
|
||||
CapabilityConfigWriteGlobal: {Capability: CapabilityConfigWriteGlobal, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true},
|
||||
@@ -64,6 +66,7 @@ var policies = map[Capability]Policy{
|
||||
|
||||
var grants = map[Role]map[Capability]struct{}{
|
||||
RoleSuperAdmin: grant(
|
||||
CapabilityAccountGroupManage,
|
||||
CapabilityNotificationManage,
|
||||
CapabilityPluginReadGlobal, CapabilityUserCreate, CapabilityProfileWriteOwn,
|
||||
CapabilityConfigRead, CapabilityConfigWriteGlobal, CapabilityConfigRollback,
|
||||
|
||||
@@ -9,6 +9,12 @@ type Endpoint struct {
|
||||
}
|
||||
|
||||
var managementEndpoints = []Endpoint{
|
||||
{Method: "POST", Path: "/api/system/notification/authorization", Capability: CapabilityNotificationManage},
|
||||
{Method: "POST", Path: "/api/system/notification/credential", Capability: CapabilityNotificationManage},
|
||||
{Method: "POST", Path: "/api/v1/user/groups/save", Capability: CapabilityAccountGroupManage},
|
||||
{Method: "POST", Path: "/api/v1/user/groups/membership", Capability: CapabilityAccountGroupManage},
|
||||
{Method: "POST", Path: "/api/user/groups/save", Capability: CapabilityAccountGroupManage},
|
||||
{Method: "POST", Path: "/api/user/groups/membership", Capability: CapabilityAccountGroupManage},
|
||||
{Method: "POST", Path: "/api/v1/system/notification/authorization", Capability: CapabilityNotificationManage},
|
||||
{Method: "POST", Path: "/api/v1/system/notification/credential", Capability: CapabilityNotificationManage},
|
||||
{Method: "POST", Path: "/api/settings/modify_password", Capability: CapabilityPasswordChangeOwn},
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package accountgroup
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDenied = errors.New("account group scope denied")
|
||||
ErrInvalid = errors.New("invalid account group")
|
||||
ErrConflict = errors.New("account group membership changed")
|
||||
)
|
||||
|
||||
// ScopePredicate 的外层必须是用户表。使用实时子查询,不缓存管理员的分组范围。
|
||||
// 未建立成员关系的旧账号以及新账号都属于默认分组,无需迁移或复制账号数据。
|
||||
func ScopePredicate(actorID int) (string, []any) {
|
||||
return `(id IN (
|
||||
SELECT gm.user_id FROM account_group_member gm
|
||||
JOIN account_group_member am ON gm.group_id = am.group_id
|
||||
WHERE am.user_id = ?
|
||||
) OR ((id NOT IN (SELECT user_id FROM account_group_member)
|
||||
OR id IN (SELECT user_id FROM account_group_member WHERE group_id = 0))
|
||||
AND (NOT EXISTS (SELECT 1 FROM account_group_member WHERE user_id = ?)
|
||||
OR EXISTS (SELECT 1 FROM account_group_member WHERE user_id = ? AND group_id = 0))))`,
|
||||
[]any{actorID, actorID, actorID}
|
||||
}
|
||||
|
||||
func ApplyScope(query *xorm.Session, actorID int, role access.Role) {
|
||||
if actorID <= 0 {
|
||||
query.And("1 = 0")
|
||||
return
|
||||
}
|
||||
switch role {
|
||||
case access.RoleSuperAdmin:
|
||||
return
|
||||
case access.RoleAdmin:
|
||||
predicate, args := ScopePredicate(actorID)
|
||||
query.And(predicate, args...)
|
||||
default:
|
||||
query.And("id = ?", actorID)
|
||||
}
|
||||
}
|
||||
|
||||
func ApplyGroup(query *xorm.Session, groupID int) {
|
||||
if groupID == 0 {
|
||||
query.And("(id NOT IN (SELECT user_id FROM account_group_member) OR id IN (SELECT user_id FROM account_group_member WHERE group_id = 0))")
|
||||
} else {
|
||||
query.And("id IN (SELECT user_id FROM account_group_member WHERE group_id = ?)", groupID)
|
||||
}
|
||||
}
|
||||
|
||||
func CanAccess(engine *xorm.Engine, actorID int, role access.Role, targetID int) bool {
|
||||
if engine == nil || actorID <= 0 || targetID <= 0 {
|
||||
return false
|
||||
}
|
||||
query := engine.Table(&models.User{}).Where("id = ?", targetID)
|
||||
defer query.Close()
|
||||
ApplyScope(query, actorID, role)
|
||||
found, err := query.Exist(&models.User{})
|
||||
return err == nil && found
|
||||
}
|
||||
|
||||
func Memberships(engine *xorm.Engine, userIDs []int) (map[int][]int, error) {
|
||||
result := make(map[int][]int, len(userIDs))
|
||||
if engine == nil {
|
||||
return nil, ErrDenied
|
||||
}
|
||||
if len(userIDs) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
var rows []models.AccountGroupMember
|
||||
if err := engine.In("user_id", userIDs).Asc("group_id").Find(&rows); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
result[row.UserID] = append(result[row.UserID], row.GroupID)
|
||||
}
|
||||
for _, id := range userIDs {
|
||||
if len(result[id]) == 0 {
|
||||
result[id] = []int{0}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func VisibleGroups(engine *xorm.Engine, actorID int, role access.Role) ([]models.AccountGroup, error) {
|
||||
if engine == nil || actorID <= 0 || (role != access.RoleAdmin && role != access.RoleSuperAdmin) {
|
||||
return nil, ErrDenied
|
||||
}
|
||||
query := engine.Table(&models.AccountGroup{})
|
||||
defer query.Close()
|
||||
showDefault := role == access.RoleSuperAdmin
|
||||
if role == access.RoleAdmin {
|
||||
members, err := Memberships(engine, []int{actorID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := members[actorID]
|
||||
query.In("id", ids)
|
||||
for _, id := range ids {
|
||||
if id == 0 {
|
||||
showDefault = true
|
||||
}
|
||||
}
|
||||
}
|
||||
groups := make([]models.AccountGroup, 0)
|
||||
if err := query.Asc("id").Find(&groups); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if showDefault {
|
||||
groups = append([]models.AccountGroup{{ID: 0, Name: "默认分组"}}, groups...)
|
||||
}
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
func NormalizeName(value string) (string, error) {
|
||||
name := strings.TrimSpace(value)
|
||||
if name == "" || name == "默认分组" || !utf8.ValidString(name) || utf8.RuneCountInString(name) > 32 {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
for _, r := range name {
|
||||
if unicode.IsControl(r) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// ValidateMembership 必须在持有目标用户写锁的事务内调用,避免降级和分组变更并发突破单组约束。
|
||||
func ValidateMembership(tx *xorm.Session, role access.Role, input []int) ([]int, error) {
|
||||
if len(input) > 100 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
ids := make([]int, 0, len(input))
|
||||
seen := map[int]bool{}
|
||||
for _, id := range input {
|
||||
if id < 0 || seen[id] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
ids = []int{0}
|
||||
}
|
||||
if role != access.RoleAdmin && len(ids) != 1 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
for _, id := range ids {
|
||||
if id == 0 {
|
||||
continue
|
||||
}
|
||||
found, err := tx.ID(id).Exist(&models.AccountGroup{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
sort.Ints(ids)
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func ReplaceMembership(tx *xorm.Session, userID int, ids []int) error {
|
||||
if _, err := tx.Where("user_id = ?", userID).Delete(&models.AccountGroupMember{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 1 && ids[0] == 0 {
|
||||
return nil
|
||||
}
|
||||
rows := make([]models.AccountGroupMember, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
rows = append(rows, models.AccountGroupMember{UserID: userID, GroupID: id})
|
||||
}
|
||||
_, err := tx.Insert(&rows)
|
||||
return err
|
||||
}
|
||||
|
||||
func SetMembership(engine *xorm.Engine, user models.User, input []int) error {
|
||||
if engine == nil || user.ID <= 0 {
|
||||
return ErrDenied
|
||||
}
|
||||
tx := engine.NewSession()
|
||||
defer tx.Close()
|
||||
if err := tx.Begin(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
updated := user
|
||||
updated.SessionVersion++
|
||||
updated.SecurityVersion++
|
||||
n, err := tx.ID(user.ID).Where("session_version = ? AND security_version = ?", user.SessionVersion, user.SecurityVersion).
|
||||
Cols("session_version", "security_version").Update(&updated)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrConflict
|
||||
}
|
||||
ids, err := ValidateMembership(tx, user.EffectiveRole(), input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ReplaceMembership(tx, user.ID, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -12,10 +12,10 @@ import (
|
||||
|
||||
// ProtocolSession 保存不可变身份与凭据快照,拒绝后的连接不能通过重新启用恢复权限。
|
||||
type ProtocolSession struct {
|
||||
user models.User
|
||||
grant *credentials.ProtocolGrant
|
||||
user models.User
|
||||
grant *credentials.ProtocolGrant
|
||||
notification *notification.Grant
|
||||
invalid atomic.Bool
|
||||
invalid atomic.Bool
|
||||
}
|
||||
|
||||
func AuthenticateProtocolSession(protocol, remoteAddress, account, plain string) (*models.User, *ProtocolSession, error) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/db/migration"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/accountgroup"
|
||||
"git.pcux.cn/xuans/Smail/utils/logpolicy"
|
||||
)
|
||||
|
||||
@@ -197,7 +198,13 @@ func (s *Store) Query(ctx context.Context, query Query) ([]Entry, error) {
|
||||
if s.dialect == migration.DialectMySQL {
|
||||
userTable, idType = "`user`", "CHAR"
|
||||
}
|
||||
statement += "actor_id IN (SELECT CAST(id AS " + idType + ") FROM " + userTable + " WHERE " + models.OrdinaryUserPredicate + ")"
|
||||
actorID, parseErr := strconv.Atoi(query.ScopeActorID)
|
||||
if parseErr != nil || actorID <= 0 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
groupScope, groupArgs := accountgroup.ScopePredicate(actorID)
|
||||
statement += "actor_id IN (SELECT CAST(id AS " + idType + ") FROM " + userTable + " WHERE " + models.OrdinaryUserPredicate + " AND " + groupScope + ")"
|
||||
args = append(args, groupArgs...)
|
||||
// 代管视图还要核对操作发生时的角色,不能因账号降级暴露旧管理操作。
|
||||
// 缺少历史角色的操作仅本人和超级管理员可见,收发信元数据不包含管理操作。
|
||||
if isOperationKind(query.Kind) {
|
||||
|
||||
@@ -15,19 +15,19 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
UsernamePrefix = "notify:"
|
||||
UsernamePrefix = "notify:"
|
||||
DefaultMinuteLimit = 10
|
||||
DefaultDayLimit = 100
|
||||
MaxRecipients = 10
|
||||
MaxMessageBytes = 1 << 20
|
||||
DefaultDayLimit = 100
|
||||
MaxRecipients = 10
|
||||
MaxMessageBytes = 1 << 20
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDenied = errors.New("notification authorization denied")
|
||||
ErrConflict = errors.New("notification authorization changed")
|
||||
ErrQuota = errors.New("notification quota exceeded")
|
||||
ErrDenied = errors.New("notification authorization denied")
|
||||
ErrConflict = errors.New("notification authorization changed")
|
||||
ErrQuota = errors.New("notification quota exceeded")
|
||||
ErrUnavailable = errors.New("notification authorization unavailable")
|
||||
ErrLimits = errors.New("invalid notification limits")
|
||||
ErrLimits = errors.New("invalid notification limits")
|
||||
)
|
||||
|
||||
func IsUsername(username string) bool {
|
||||
@@ -118,11 +118,11 @@ func Rotate(engine *xorm.Engine, user models.User, expected int) (string, error)
|
||||
}
|
||||
|
||||
type Grant struct {
|
||||
engine *xorm.Engine
|
||||
userID int
|
||||
version int
|
||||
hash string
|
||||
sessionVersion int
|
||||
engine *xorm.Engine
|
||||
userID int
|
||||
version int
|
||||
hash string
|
||||
sessionVersion int
|
||||
securityVersion int
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/accountgroup"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
@@ -377,6 +378,9 @@ func (s *ConfigService) UpdateOwnTelegramSettings(actorUserID int, settings Tele
|
||||
|
||||
// UpdateTelegramSettingsForUser 查询目标账户的当前角色后才进行跨用户授权。
|
||||
func (s *ConfigService) UpdateTelegramSettingsForUser(actor models.User, targetUserID int, settings TelegramUserSettings, expectedVersion uint64) (UserSettingsStatus, error) {
|
||||
if s == nil || !accountgroup.CanAccess(s.engine, actor.ID, actor.EffectiveRole(), targetUserID) {
|
||||
return UserSettingsStatus{}, &access.Denial{Code: access.CodeAccessDenied}
|
||||
}
|
||||
if actor.ID <= 0 || targetUserID <= 0 {
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user