fix: harden identity, live access, drafts and setup (review only)

Source-reviewed hardening changes and regression tests. UNBUILT / UNTESTED: not a deployable release. Go formatting, compilation, automated regression tests, full frontend validation and staging acceptance remain required. See docs/hardening/VALIDATION.md. Main remains the original clean snapshot; no upstream Git history imported.
This commit is contained in:
2026-10-16 12:15:20 +00:00
parent e57610a27c
commit 63e0457886
86 changed files with 5174 additions and 1929 deletions

View File

@@ -0,0 +1,68 @@
package repositories
import (
"agent-desk/internal/models"
"agent-desk/internal/pkg/enums"
"time"
"gorm.io/gorm"
)
// These handwritten queries supplement the generated CRUD repositories.
func (r *roleRepository) FindEnabledByUser(db *gorm.DB, userID int64) ([]models.Role, error) {
roles := make([]models.Role, 0)
err := db.Table("t_role AS r").
Select("r.*").
Joins("JOIN t_user_role AS ur ON ur.role_id = r.id").
Where("ur.user_id = ? AND r.status = ?", userID, enums.StatusOk).
Order("r.sort_no ASC, r.id ASC").
Scan(&roles).Error
return roles, err
}
func (r *permissionRepository) FindEnabledCodesByUserRoles(db *gorm.DB, userID int64) ([]string, error) {
codes := make([]string, 0)
err := db.Table("t_permission AS p").
Joins("JOIN t_role_permission AS rp ON rp.permission_id = p.id").
Joins("JOIN t_role AS r ON r.id = rp.role_id").
Joins("JOIN t_user_role AS ur ON ur.role_id = r.id").
Where("ur.user_id = ? AND r.status = ? AND p.status = ?", userID, enums.StatusOk, enums.StatusOk).
Distinct().Pluck("p.code", &codes).Error
return codes, err
}
type UserPermissionOverride struct {
Code string
Effect int
}
func (r *userPermissionRepository) FindActiveEnabledOverrides(db *gorm.DB, userID int64, now time.Time) ([]UserPermissionOverride, error) {
overrides := make([]UserPermissionOverride, 0)
err := db.Table("t_user_permission AS up").
Select("p.code, up.effect").
Joins("JOIN t_permission AS p ON p.id = up.permission_id").
Where("up.user_id = ? AND p.status = ?", userID, enums.StatusOk).
Where("up.expired_at IS NULL OR up.expired_at > ?", now).
Scan(&overrides).Error
return overrides, err
}
// GetAuthState deliberately excludes the bearer token; revalidation only needs
// the identity binding, revocation status, and absolute expiry.
func (r *loginSessionRepository) GetAuthState(db *gorm.DB, sessionID, userID int64) (*models.LoginSession, error) {
session := &models.LoginSession{}
if err := db.Select("id", "user_id", "expired_at", "revoked_at").
Take(session, "id = ? AND user_id = ?", sessionID, userID).Error; err != nil {
return nil, err
}
return session, nil
}
func (r *userRepository) GetAuthState(db *gorm.DB, userID int64) (*models.User, error) {
user := &models.User{}
if err := db.Select("id", "username", "nickname", "avatar", "user_type", "status", "deleted_at").
Take(user, "id = ?", userID).Error; err != nil {
return nil, err
}
return user, nil
}

View File

@@ -0,0 +1,20 @@
package repositories
import (
"agent-desk/internal/models"
"agent-desk/internal/pkg/enums"
"gorm.io/gorm"
)
// UpdatesConfigIfUnchanged prevents a stale read/modify/write from replacing a
// concurrently tightened authentication policy or rotated channel secret. HEX is
// available in SQLite and MySQL and compares exact bytes even when MySQL's text
// column uses a case-insensitive or trailing-space-insensitive collation.
func (r *channelRepository) UpdatesConfigIfUnchanged(db *gorm.DB, expected *models.Channel, columns map[string]any) (bool, error) {
if expected == nil || expected.ID <= 0 { return false, nil }
result := db.Model(&models.Channel{}).
Where("id = ? AND status <> ? AND updated_at = ?", expected.ID, enums.StatusDeleted, expected.UpdatedAt).
Where("HEX(COALESCE(config_json, '')) = HEX(?)", expected.ConfigJSON).
Updates(columns)
return result.RowsAffected == 1, result.Error
}

View File

@@ -0,0 +1,17 @@
package repositories
import (
"agent-desk/internal/models"
"agent-desk/internal/pkg/enums"
"gorm.io/gorm"
)
// FindPendingDispatchBatch returns a bounded, checked page. A failed read must
// not be mistaken for an empty queue by setup or the periodic dispatcher.
func (r *conversationRepository) FindPendingDispatchBatch(db *gorm.DB, limit int) ([]models.Conversation, error) {
conversations := make([]models.Conversation, 0)
err := db.Where("status = ? AND current_assignee_id = ?", enums.IMConversationStatusPending, 0).
Order("id DESC").Limit(limit).Find(&conversations).Error
return conversations, err
}

View File

@@ -1,3 +1,5 @@
// Modified in the independent hardening fork; see docs/hardening.
package repositories
import (
@@ -6,7 +8,6 @@ import (
"agent-desk/internal/pkg/httpx/params"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/sqls"
"gorm.io/gorm"
)
@@ -36,14 +37,11 @@ func (r *customerIdentityRepository) Take(db *gorm.DB, where ...interface{}) *mo
return ret
}
// GetBy 按外部来源 + 外部用户标识查询身份映射(与 uk_customer_external 一致)。
// GetBy is the legacy/internal-integration lookup. Ambiguous mappings fail closed.
func (r *customerIdentityRepository) GetBy(db *gorm.DB, externalSource enums.ExternalSource, externalID string) *models.CustomerIdentity {
if strs.IsAnyBlank(string(externalSource), externalID) {
return nil
}
return r.FindOne(db, sqls.NewCnd().
Eq("external_source", externalSource).
Eq("external_id", externalID))
identity, err := r.GetUniqueBy(db, "", externalSource, externalID)
if err != nil { return nil }
return identity
}
func (r *customerIdentityRepository) FindByCustomerID(db *gorm.DB, customerID int64) []models.CustomerIdentity {

View File

@@ -0,0 +1,51 @@
package repositories
import (
"errors"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"strings"
"agent-desk/internal/models"
"agent-desk/internal/pkg/enums"
"gorm.io/gorm"
)
// ErrAmbiguousCustomerIdentity requires deliberate operator reconciliation. Never
// choose the first row: the historical unique index also includes customer_id.
var ErrAmbiguousCustomerIdentity = errors.New("ambiguous customer identity")
// GetUniqueBy includes disabled rows when detecting conflicts. A disabled mapping
// must not let a caller create a replacement customer and reacquire the identity.
func (r *customerIdentityRepository) GetUniqueBy(db *gorm.DB, scope string, source enums.ExternalSource, externalID string) (*models.CustomerIdentity, error) {
if strings.TrimSpace(string(source)) == "" || strings.TrimSpace(externalID) == "" {
return nil, errors.New("invalid customer identity")
}
var identities []models.CustomerIdentity
query := db.Where("identity_scope = ? AND external_source = ? AND external_id = ?", scope, source, strings.TrimSpace(externalID))
if key := ScopedCustomerIdentityKey(scope, source, externalID); key != nil {
// Digest comparison is independent of MySQL's external_id collation. The
// NULL branch also detects manually migrated/inconsistent scoped mappings.
query = db.Where("scoped_key = ? OR (scoped_key IS NULL AND identity_scope = ? AND external_source = ? AND external_id = ?)", *key, scope, source, strings.TrimSpace(externalID))
}
err := query.Limit(2).Find(&identities).Error
if err != nil { return nil, err }
if len(identities) > 1 { return nil, ErrAmbiguousCustomerIdentity }
if len(identities) == 0 { return nil, nil }
if identities[0].IdentityScope != scope || identities[0].ExternalSource != source || identities[0].ExternalID != strings.TrimSpace(externalID) { return nil, ErrAmbiguousCustomerIdentity }
if identities[0].Status != enums.StatusOk { return nil, errors.New("inactive customer identity") }
return &identities[0], nil
}
// ScopedCustomerIdentityKey gives new scoped registrations a database-enforced
// claim without imposing a new unique constraint on dirty legacy data. Both
// SQLite and MySQL permit multiple NULL values in a unique index. Encoding an
// array avoids delimiter collisions and hashing avoids collation ambiguity.
func ScopedCustomerIdentityKey(scope string, source enums.ExternalSource, externalID string) *string {
if scope == "" { return nil }
encoded, _ := json.Marshal([]string{scope, string(source), strings.TrimSpace(externalID)})
digest := sha256.Sum256(encoded)
key := hex.EncodeToString(digest[:])
return &key
}