检查点:保留通知授权开发状态,开始用户分组隔离
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-25 21:19:28 +08:00
1 parent deba430f2f
commit 9be7a6f990
22 files changed
+1024 -7

No files matched your search

+9
View File
@@ -63,6 +63,10 @@ func Authorize(request Request) error {
func authorizeResource(request Request) error {
switch request.Capability {
case CapabilityNotificationManage:
if !CanManageNotification(request.ActorRole, request.TargetRole, request.OwnResource) {
return deny(CodeTargetRoleDenied)
}
case CapabilityPasswordChangeOwn, CapabilityPluginWriteOwn, CapabilityProfileWriteOwn:
if !request.OwnResource {
return deny(CodeAccessDenied)
@@ -112,6 +116,11 @@ func canManageAccountTarget(actor Role, target Role) bool {
}
}
// 通知授权不改变账号角色;管理员只管理本人和普通用户,不能操作其他管理员。
func CanManageNotification(actor, target Role, own bool) bool {
return target.Valid() && (actor == RoleSuperAdmin || actor == RoleAdmin && (target == RoleUser || own && target == RoleAdmin))
}
func canManagePluginTarget(actor Role, target Role) bool {
if actor == RoleSuperAdmin {
return target.Valid()
+4
View File
@@ -25,6 +25,7 @@ const (
CapabilityPasswordReset Capability = "password.reset"
CapabilityAuditRead Capability = "audit.read"
CapabilityAuditExport Capability = "audit.export"
CapabilityNotificationManage Capability = "notification.manage"
)
type Policy struct {
@@ -36,6 +37,7 @@ type Policy struct {
}
var policies = map[Capability]Policy{
CapabilityNotificationManage: {Capability: CapabilityNotificationManage, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true},
CapabilityConfigRead: {Capability: CapabilityConfigRead},
CapabilityConfigWriteGlobal: {Capability: CapabilityConfigWriteGlobal, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true},
CapabilityConfigRollback: {Capability: CapabilityConfigRollback, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true},
@@ -62,6 +64,7 @@ var policies = map[Capability]Policy{
var grants = map[Role]map[Capability]struct{}{
RoleSuperAdmin: grant(
CapabilityNotificationManage,
CapabilityPluginReadGlobal, CapabilityUserCreate, CapabilityProfileWriteOwn,
CapabilityConfigRead, CapabilityConfigWriteGlobal, CapabilityConfigRollback,
CapabilityDatabaseMigrate, CapabilityPluginRead, CapabilityPluginControl,
@@ -71,6 +74,7 @@ var grants = map[Role]map[Capability]struct{}{
CapabilityAuditRead, CapabilityAuditExport,
),
RoleAdmin: grant(
CapabilityNotificationManage,
CapabilityPluginReadGlobal, CapabilityPluginRead, CapabilityPluginWriteGlobal, CapabilityProfileWriteOwn,
CapabilityPluginWriteAnyUser, CapabilityPluginWriteOwn, CapabilityUserRead,
CapabilityUserManage, CapabilityUserSecurityManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset,
+2
View File
@@ -9,6 +9,8 @@ type Endpoint struct {
}
var managementEndpoints = []Endpoint{
{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},
{Method: "POST", Path: "/api/user/create", Capability: CapabilityUserCreate},
{Method: "POST", Path: "/api/user/profile", Capability: CapabilityProfileWriteOwn},
@@ -0,0 +1,67 @@
package auth
import (
"strings"
"time"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/notification"
)
// 通知身份拥有独立用户名空间,不会回退到普通协议或网页认证。
func authenticateNotification(protocol, remoteAddress, account, plain string) (*models.User, *ProtocolSession, error) {
account = strings.ToLower(strings.TrimSpace(account))
identifier := strings.TrimPrefix(account, notification.UsernamePrefix)
remote := protocolRemoteHost(remoteAddress)
pairKey := hashedProtocolLoginKey("pair", "notification", remote, identifier)
accountKey := hashedProtocolLoginKey("account", identifier)
remoteKey := hashedProtocolLoginKey("remote", remote)
fail := func() (*models.User, *ProtocolSession, error) {
protocolPairAttempts.recordFailure(pairKey)
protocolAccountAttempts.recordFailure(accountKey)
protocolRemoteAttempts.recordFailure(remoteKey)
return nil, nil, notification.ErrDenied
}
if protocolPairAttempts.blocked(pairKey) || protocolAccountAttempts.blocked(accountKey) || protocolRemoteAttempts.blocked(remoteKey) {
return nil, nil, notification.ErrDenied
}
if protocol != "smtp" || db.Instance == nil {
return fail()
}
identifier, err := NormalizeProtocolIdentifier(identifier)
if err != nil {
return fail()
}
identity, err := ResolveIdentifier(identifier)
if err != nil || identity.UserID <= 0 {
return fail()
}
var user models.User
found, err := db.Instance.ID(identity.UserID).Get(&user)
if err != nil || !found {
return fail()
}
grant, err := notification.Authenticate(db.Instance, user, plain)
if err != nil {
return fail()
}
session := &ProtocolSession{user: user, notification: grant}
if err := session.Check(); err != nil {
return fail()
}
protocolPairAttempts.clear(pairKey)
protocolAccountAttempts.clear(accountKey)
return &user, session, nil
}
func (s *ProtocolSession) IsNotification() bool {
return s != nil && s.notification != nil
}
func (s *ProtocolSession) ReserveNotification(recipients int) error {
if !s.IsNotification() || s.Check() != nil {
return notification.ErrDenied
}
return s.notification.Reserve(db.Instance, recipients, time.Now())
}
+7 -1
View File
@@ -7,16 +7,21 @@ import (
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/credentials"
"git.pcux.cn/xuans/Smail/services/notification"
)
// ProtocolSession 保存不可变身份与凭据快照,拒绝后的连接不能通过重新启用恢复权限。
type ProtocolSession struct {
user models.User
grant *credentials.ProtocolGrant
notification *notification.Grant
invalid atomic.Bool
}
func AuthenticateProtocolSession(protocol, remoteAddress, account, plain string) (*models.User, *ProtocolSession, error) {
if notification.IsUsername(account) {
return authenticateNotification(protocol, remoteAddress, account, plain)
}
var grant *credentials.ProtocolGrant
user, err := authenticateProtocol(protocol, remoteAddress, account, plain, &grant)
if err != nil {
@@ -36,7 +41,8 @@ func (s *ProtocolSession) Check() error {
return denied
}
engine := db.Instance
if engine != nil && s.grant.Valid(engine) {
validGrant := engine != nil && (s.grant.Valid(engine) || s.notification.Valid(engine))
if validGrant {
var user models.User
has, err := engine.ID(s.user.ID).Where("disabled = 0").Get(&user)
if err == nil && has && user.Account == s.user.Account && user.Password == s.user.Password &&
+192
View File
@@ -0,0 +1,192 @@
package notification
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"strings"
"time"
"git.pcux.cn/xuans/Smail/models"
"xorm.io/xorm"
)
const (
UsernamePrefix = "notify:"
DefaultMinuteLimit = 10
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")
ErrUnavailable = errors.New("notification authorization unavailable")
ErrLimits = errors.New("invalid notification limits")
)
func IsUsername(username string) bool {
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(username)), UsernamePrefix)
}
func Load(engine *xorm.Engine, userID int) (models.NotificationGrant, error) {
var item models.NotificationGrant
if engine == nil || userID <= 0 {
return item, ErrUnavailable
}
found, err := engine.ID(userID).Get(&item)
if err == nil && !found {
item = models.NotificationGrant{UserID: userID, MinuteLimit: DefaultMinuteLimit, DayLimit: DefaultDayLimit}
}
return item, err
}
func Configured(item models.NotificationGrant, user models.User) bool {
return item.Enabled == 1 && item.CodeHash != "" && user.Disabled == 0 && user.MustChangePassword == 0 &&
item.SessionVersion == user.SessionVersion && item.SecurityVersion == user.SecurityVersion
}
// SetAuthorization 使用版本条件避免覆盖其他管理员的修改;关闭时永久清除旧凭据。
func SetAuthorization(engine *xorm.Engine, user models.User, expected int, enabled bool, minuteLimit, dayLimit int) error {
if minuteLimit < 1 || minuteLimit > 100 || dayLimit < minuteLimit || dayLimit > 10000 {
return ErrLimits
}
if enabled && (user.Disabled != 0 || user.MustChangePassword != 0) {
return ErrDenied
}
item, err := Load(engine, user.ID)
if err != nil {
return err
}
if item.CodeVersion != expected {
return ErrConflict
}
item.Enabled = 0
if enabled {
item.Enabled = 1
} else {
item.CodeHash = ""
}
item.MinuteLimit, item.DayLimit = minuteLimit, dayLimit
item.CodeVersion++
if expected == 0 {
_, err = engine.Insert(&item)
return err
}
affected, err := engine.ID(user.ID).Where("code_version = ?", expected).
Cols("enabled", "code_hash", "code_version", "minute_limit", "day_limit").Update(&item)
if err == nil && affected != 1 {
return ErrConflict
}
return err
}
// Rotate 仅返回一次明文。随机凭据具有 256 位熵,数据库只保存 SHA-256 摘要。
func Rotate(engine *xorm.Engine, user models.User, expected int) (string, error) {
item, err := Load(engine, user.ID)
if err != nil {
return "", err
}
if item.Enabled != 1 || user.Disabled != 0 || user.MustChangePassword != 0 {
return "", ErrDenied
}
if item.CodeVersion != expected {
return "", ErrConflict
}
var entropy [32]byte
if _, err := rand.Read(entropy[:]); err != nil {
return "", err
}
code := "sn_" + base64.RawURLEncoding.EncodeToString(entropy[:])
item.CodeHash = digest(code)
item.CodeVersion++
item.SessionVersion, item.SecurityVersion = user.SessionVersion, user.SecurityVersion
affected, err := engine.ID(user.ID).Where("code_version = ? AND enabled = 1", expected).
Cols("code_hash", "code_version", "session_version", "security_version").Update(&item)
if err != nil {
return "", err
}
if affected != 1 {
return "", ErrConflict
}
return code, nil
}
type Grant struct {
engine *xorm.Engine
userID int
version int
hash string
sessionVersion int
securityVersion int
}
func Authenticate(engine *xorm.Engine, user models.User, plain string) (*Grant, error) {
if len(plain) != 46 || !strings.HasPrefix(plain, "sn_") {
return nil, ErrDenied
}
item, err := Load(engine, user.ID)
if err != nil || !Configured(item, user) {
return nil, ErrDenied
}
if subtle.ConstantTimeCompare([]byte(item.CodeHash), []byte(digest(plain))) != 1 {
return nil, ErrDenied
}
return &Grant{engine, user.ID, item.CodeVersion, item.CodeHash, item.SessionVersion, item.SecurityVersion}, nil
}
func (g *Grant) Valid(engine *xorm.Engine) bool {
if g == nil || engine == nil || engine != g.engine {
return false
}
valid, err := engine.ID(g.userID).Where("enabled = 1 AND code_version = ? AND code_hash = ?", g.version, g.hash).
Exist(&models.NotificationGrant{})
if err != nil || !valid {
return false
}
valid, err = engine.ID(g.userID).Where("disabled = 0 AND must_change_password = 0 AND session_version = ? AND security_version = ?", g.sessionVersion, g.securityVersion).
Exist(&models.User{})
return err == nil && valid
}
// Reserve 将收件人数计入配额,重试和失败也计数;并发连接和服务重启不能绕过限制。
func (g *Grant) Reserve(engine *xorm.Engine, recipients int, now time.Time) error {
if !g.Valid(engine) {
return ErrDenied
}
if recipients < 1 || recipients > MaxRecipients {
return ErrLimits
}
minute, day := now.UTC().Format("2006-01-02T15:04"), now.UTC().Format("2006-01-02")
result, err := engine.Exec(`UPDATE notification_grant SET
minute_count = CASE WHEN minute_key = ? THEN minute_count + ? ELSE ? END,
day_count = CASE WHEN day_key = ? THEN day_count + ? ELSE ? END,
minute_key = ?, day_key = ?
WHERE user_id = ? AND enabled = 1 AND code_version = ? AND code_hash = ?
AND ? <= minute_limit AND ? <= day_limit
AND (minute_key <> ? OR minute_count + ? <= minute_limit)
AND (day_key <> ? OR day_count + ? <= day_limit)`,
minute, recipients, recipients, day, recipients, recipients, minute, day,
g.userID, g.version, g.hash, recipients, recipients, minute, recipients, day, recipients)
if err != nil {
return ErrUnavailable
}
affected, err := result.RowsAffected()
if err != nil {
return ErrUnavailable
}
if affected != 1 {
return ErrQuota
}
return nil
}
func digest(plain string) string {
hash := sha256.Sum256([]byte(plain))
return hex.EncodeToString(hash[:])
}