1 parent
3456b9d481
commit
31ee54942a
22 files changed
+1728
-5
No files matched your search
@@ -32,6 +32,10 @@ func TestRoleBoundaries(t *testing.T) {
|
||||
{name: "admin resets user", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPasswordReset, TargetRole: RoleUser, RecentAuth: true, RecoveryCodeConfigured: true}},
|
||||
{name: "admin cannot reset admin", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPasswordReset, TargetRole: RoleAdmin, RecentAuth: true, RecoveryCodeConfigured: true}, code: CodeTargetRoleDenied},
|
||||
{name: "user cannot reset another user", req: Request{ActorRole: RoleUser, Capability: CapabilityPasswordReset, TargetRole: RoleUser, RecentAuth: true, RecoveryCodeConfigured: true}, code: CodeAccessDenied},
|
||||
{name: "super admin manages user security", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityUserSecurityManage, TargetRole: RoleUser, RecentAuth: true}},
|
||||
{name: "admin manages user security", req: Request{ActorRole: RoleAdmin, Capability: CapabilityUserSecurityManage, TargetRole: RoleUser, RecentAuth: true, RecoveryCodeConfigured: true}},
|
||||
{name: "admin cannot manage admin security", req: Request{ActorRole: RoleAdmin, Capability: CapabilityUserSecurityManage, TargetRole: RoleAdmin, RecentAuth: true, RecoveryCodeConfigured: true}, code: CodeTargetRoleDenied},
|
||||
{name: "web cannot manage super admin security", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityUserSecurityManage, TargetRole: RoleSuperAdmin, RecentAuth: true}, code: CodeTargetRoleDenied},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
@@ -90,7 +94,7 @@ func TestAdminPluginRestartScope(t *testing.T) {
|
||||
|
||||
func TestManagementEndpointCatalog(t *testing.T) {
|
||||
endpoints := ManagementEndpoints()
|
||||
if len(endpoints) != 32 {
|
||||
if len(endpoints) != 34 {
|
||||
t.Fatalf("unexpected endpoint count: %d", len(endpoints))
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
@@ -128,6 +132,10 @@ func TestManagementEndpointCatalog(t *testing.T) {
|
||||
if !ok || endpoint.Capability != CapabilityConfigRollback {
|
||||
t.Fatal("configuration backup endpoint did not require rollback capability")
|
||||
}
|
||||
endpoint, ok = LookupEndpoint("POST", "/api/v1/user/security/external-email/change")
|
||||
if !ok || endpoint.Capability != CapabilityUserSecurityManage {
|
||||
t.Fatal("managed user security endpoint was not matched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryManagementEndpointHasAllowAndDeny(t *testing.T) {
|
||||
|
||||
@@ -78,7 +78,7 @@ func authorizeResource(request Request) error {
|
||||
if request.ActorRole == RoleAdmin && !request.OwnResource && !request.AuditScopeAuthorized {
|
||||
return deny(CodeAccessDenied)
|
||||
}
|
||||
case CapabilityUserManage, CapabilityPasswordReset:
|
||||
case CapabilityUserManage, CapabilityUserSecurityManage, CapabilityPasswordReset:
|
||||
if !canManageAccountTarget(request.ActorRole, request.TargetRole) {
|
||||
return deny(CodeTargetRoleDenied)
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ const (
|
||||
CapabilityPluginWriteOwn Capability = "plugin.write_own"
|
||||
CapabilityUserRead Capability = "user.read"
|
||||
CapabilityUserManage Capability = "user.manage"
|
||||
CapabilityUserSecurityManage Capability = "user.security_manage"
|
||||
CapabilityRoleManage Capability = "role.manage"
|
||||
CapabilityPasswordChangeOwn Capability = "password.change_own"
|
||||
CapabilityPasswordReset Capability = "password.reset"
|
||||
@@ -45,6 +46,7 @@ var policies = map[Capability]Policy{
|
||||
CapabilityPluginWriteOwn: {Capability: CapabilityPluginWriteOwn},
|
||||
CapabilityUserRead: {Capability: CapabilityUserRead},
|
||||
CapabilityUserManage: {Capability: CapabilityUserManage, RequiresTarget: true},
|
||||
CapabilityUserSecurityManage: {Capability: CapabilityUserSecurityManage, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true},
|
||||
CapabilityRoleManage: {Capability: CapabilityRoleManage, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true},
|
||||
CapabilityPasswordChangeOwn: {Capability: CapabilityPasswordChangeOwn},
|
||||
CapabilityPasswordReset: {Capability: CapabilityPasswordReset, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true},
|
||||
@@ -58,13 +60,13 @@ var grants = map[Role]map[Capability]struct{}{
|
||||
CapabilityDatabaseMigrate, CapabilityPluginRead, CapabilityPluginControl,
|
||||
CapabilityPluginRestart, CapabilityServiceRestart, CapabilityPluginWriteGlobal, CapabilityPluginWriteAnyUser,
|
||||
CapabilityPluginWriteOwn, CapabilityUserRead, CapabilityUserManage,
|
||||
CapabilityRoleManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset,
|
||||
CapabilityUserSecurityManage, CapabilityRoleManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset,
|
||||
CapabilityAuditRead, CapabilityAuditExport,
|
||||
),
|
||||
RoleAdmin: grant(
|
||||
CapabilityConfigRead, CapabilityPluginRead, CapabilityPluginRestart,
|
||||
CapabilityPluginWriteAnyUser, CapabilityPluginWriteOwn, CapabilityUserRead,
|
||||
CapabilityUserManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset,
|
||||
CapabilityUserManage, CapabilityUserSecurityManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset,
|
||||
CapabilityAuditRead,
|
||||
),
|
||||
RoleUser: grant(
|
||||
|
||||
@@ -12,6 +12,7 @@ var managementEndpoints = []Endpoint{
|
||||
{Method: "POST", Path: "/api/settings/modify_password", Capability: CapabilityPasswordChangeOwn},
|
||||
{Method: "POST", Path: "/api/user/create", Capability: CapabilityUserManage},
|
||||
{Method: "POST", Path: "/api/user/edit", Capability: CapabilityUserManage},
|
||||
{Method: "*", Path: "/api/user/security/", Capability: CapabilityUserSecurityManage},
|
||||
{Method: "POST", Path: "/api/user/info", Capability: CapabilityUserRead},
|
||||
{Method: "POST", Path: "/api/user/list", Capability: CapabilityUserRead},
|
||||
{Method: "GET", Path: "/api/plugin/list", Capability: CapabilityPluginRead},
|
||||
@@ -37,6 +38,7 @@ var managementEndpoints = []Endpoint{
|
||||
{Method: "GET", Path: "/api/v1/database/migrations/:id", Capability: CapabilityDatabaseMigrate},
|
||||
{Method: "POST", Path: "/api/v1/user/create", Capability: CapabilityUserManage},
|
||||
{Method: "POST", Path: "/api/v1/user/edit", Capability: CapabilityUserManage},
|
||||
{Method: "*", Path: "/api/v1/user/security/", Capability: CapabilityUserSecurityManage},
|
||||
{Method: "POST", Path: "/api/v1/user/info", Capability: CapabilityUserRead},
|
||||
{Method: "POST", Path: "/api/v1/user/list", Capability: CapabilityUserRead},
|
||||
{Method: "GET", Path: "/api/v1/plugin/list", Capability: CapabilityPluginRead},
|
||||
|
||||
@@ -31,6 +31,93 @@ type BindRequest struct {
|
||||
Type string
|
||||
}
|
||||
|
||||
// BeginReplacement 创建或更新待验证邮箱。旧邮箱会一直保留到新邮箱验证成功。
|
||||
func (r *Repository) BeginReplacement(request BindRequest) (*models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || r.vault == nil || request.UserID <= 0 {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
if request.Type != models.ExternalEmailTypePrimary && request.Type != models.ExternalEmailTypeBackup {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
normalized, err := NormalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
fingerprint, err := r.vault.Fingerprint(normalized)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ciphertext, err := r.vault.Encrypt(normalized)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var sameAddress models.ExternalEmail
|
||||
hasSameAddress, err := r.engine.Where("email_fingerprint = ?", fingerprint).Get(&sameAddress)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("check replacement external email: %w", err)
|
||||
}
|
||||
if hasSameAddress {
|
||||
if sameAddress.UserID != request.UserID || sameAddress.Status == models.ExternalEmailStatusVerified {
|
||||
return nil, ErrBindingExists
|
||||
}
|
||||
if sameAddress.EmailType != request.Type {
|
||||
return nil, ErrBindingExists
|
||||
}
|
||||
if sameAddress.Status == models.ExternalEmailStatusPending {
|
||||
return &sameAddress, nil
|
||||
}
|
||||
}
|
||||
|
||||
now := r.now().UTC()
|
||||
if hasSameAddress && sameAddress.Status == models.ExternalEmailStatusDisabled {
|
||||
sameAddress.Status = models.ExternalEmailStatusPending
|
||||
sameAddress.VerifiedAt = nil
|
||||
sameAddress.CredentialVersion++
|
||||
sameAddress.UpdatedAt = now
|
||||
if _, err := r.engine.ID(sameAddress.ID).Cols("status", "verified_at", "credential_version", "updated_at").Update(&sameAddress); err != nil {
|
||||
return nil, fmt.Errorf("reuse disabled replacement external email: %w", err)
|
||||
}
|
||||
return &sameAddress, nil
|
||||
}
|
||||
|
||||
var pending models.ExternalEmail
|
||||
hasPending, err := r.engine.Where(
|
||||
"user_id = ? AND email_type = ? AND status = ?",
|
||||
request.UserID,
|
||||
request.Type,
|
||||
models.ExternalEmailStatusPending,
|
||||
).Get(&pending)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load pending replacement external email: %w", err)
|
||||
}
|
||||
if hasPending {
|
||||
pending.EmailCiphertext = ciphertext
|
||||
pending.EmailFingerprint = fingerprint
|
||||
pending.CredentialVersion++
|
||||
pending.UpdatedAt = now
|
||||
if _, err := r.engine.ID(pending.ID).Cols("email_ciphertext", "email_fingerprint", "credential_version", "updated_at").Update(&pending); err != nil {
|
||||
return nil, fmt.Errorf("update pending replacement external email: %w", err)
|
||||
}
|
||||
return &pending, nil
|
||||
}
|
||||
|
||||
item := &models.ExternalEmail{
|
||||
UserID: request.UserID,
|
||||
EmailCiphertext: ciphertext,
|
||||
EmailFingerprint: fingerprint,
|
||||
EmailType: request.Type,
|
||||
Status: models.ExternalEmailStatusPending,
|
||||
CredentialVersion: 1,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if _, err := r.engine.Insert(item); err != nil {
|
||||
return nil, fmt.Errorf("create replacement external email: %w", err)
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func NewRepository(engine *xorm.Engine, vault *Vault) (*Repository, error) {
|
||||
if engine == nil || vault == nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
@@ -200,6 +287,65 @@ func (r *Repository) Verify(userID, id int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyReplacement 验证新邮箱后原子停用同用途旧邮箱,并启用新邮箱。
|
||||
func (r *Repository) VerifyReplacement(userID, id int) error {
|
||||
if r == nil || r.engine == nil || userID <= 0 || id <= 0 {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
session := r.engine.NewSession()
|
||||
if session == nil {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
defer session.Close()
|
||||
if err := session.Begin(); err != nil {
|
||||
return fmt.Errorf("begin external email replacement: %w", err)
|
||||
}
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
_ = session.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
item := &models.ExternalEmail{}
|
||||
has, err := session.Where("id = ? AND user_id = ? AND status = ?", id, userID, models.ExternalEmailStatusPending).Get(item)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load replacement external email: %w", err)
|
||||
}
|
||||
if !has {
|
||||
return ErrBindingOwnership
|
||||
}
|
||||
now := r.now().UTC()
|
||||
if _, err := session.Where(
|
||||
"user_id = ? AND email_type = ? AND id != ? AND status != ?",
|
||||
userID,
|
||||
item.EmailType,
|
||||
id,
|
||||
models.ExternalEmailStatusDisabled,
|
||||
).Cols("status", "updated_at").Update(&models.ExternalEmail{
|
||||
Status: models.ExternalEmailStatusDisabled,
|
||||
UpdatedAt: now,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("disable old external email: %w", err)
|
||||
}
|
||||
item.Status = models.ExternalEmailStatusVerified
|
||||
item.VerifiedAt = timePtr(now)
|
||||
item.UpdatedAt = now
|
||||
updated, err := session.ID(id).Where("user_id = ? AND status = ?", userID, models.ExternalEmailStatusPending).
|
||||
Cols("status", "verified_at", "updated_at").Update(item)
|
||||
if err != nil {
|
||||
return fmt.Errorf("verify replacement external email: %w", err)
|
||||
}
|
||||
if updated != 1 {
|
||||
return ErrBindingOwnership
|
||||
}
|
||||
if err := session.Commit(); err != nil {
|
||||
return fmt.Errorf("commit external email replacement: %w", err)
|
||||
}
|
||||
committed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// AbandonPending 删除当前请求刚创建且尚未验证的绑定,供投递失败时回滚。
|
||||
func (r *Repository) AbandonPending(userID, id int) error {
|
||||
if r == nil || r.engine == nil || userID <= 0 || id <= 0 {
|
||||
|
||||
@@ -113,3 +113,55 @@ func TestRepositoryAbandonsOnlyOwnedPendingBinding(t *testing.T) {
|
||||
t.Fatalf("verified binding was abandoned: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryReplacesExternalEmailOnlyAfterVerification(t *testing.T) {
|
||||
engine, err := xorm.NewEngine("sqlite", filepath.Join(t.TempDir(), "external.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Close()
|
||||
if err := engine.Sync2(&models.ExternalEmail{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vault := NewVaultWithKeys([]byte("01234567890123456789012345678901"), []byte("abcdefabcdefabcdefabcdefabcdefab"))
|
||||
repo, err := NewRepository(engine, vault)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldBinding, err := repo.Bind(BindRequest{UserID: 1, Email: "old@example.com", Type: models.ExternalEmailTypePrimary})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.Verify(1, oldBinding.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := repo.BeginReplacement(BindRequest{UserID: 1, Email: "new@example.com", Type: models.ExternalEmailTypePrimary})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := repo.FindVerifiedPrimaryByUser(1)
|
||||
if err != nil || before.ID != oldBinding.ID {
|
||||
t.Fatalf("old binding was not retained before verification: %+v, %v", before, err)
|
||||
}
|
||||
if err := repo.VerifyReplacement(2, pending.ID); err != ErrBindingOwnership {
|
||||
t.Fatalf("cross-user replacement error = %v", err)
|
||||
}
|
||||
if err := repo.VerifyReplacement(1, pending.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := repo.FindVerifiedPrimaryByUser(1)
|
||||
if err != nil || after.ID != pending.ID {
|
||||
t.Fatalf("new binding was not activated: %+v, %v", after, err)
|
||||
}
|
||||
items, err := repo.List(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
statuses := map[int]string{}
|
||||
for _, item := range items {
|
||||
statuses[item.ID] = item.Status
|
||||
}
|
||||
if statuses[oldBinding.ID] != models.ExternalEmailStatusDisabled || statuses[pending.ID] != models.ExternalEmailStatusVerified {
|
||||
t.Fatalf("unexpected replacement statuses: %+v", statuses)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user