feat(auth): enhance security with token hashing and sync integration

- Add token hash fields to Master and Key models for indexed lookups
- Implement SyncService integration in admin and master handlers
- Update master key validation with backward-compatible digest lookup
- Hash child keys in database and store token digests for Redis sync
- Add master metadata sync to Redis for balancer validation
- Ensure backward compatibility with legacy rows during migration
This commit is contained in:
zenfun
2025-12-05 00:17:22 +08:00
parent 8645b22b83
commit 25e5e105b3
7 changed files with 123 additions and 41 deletions

View File

@@ -23,7 +23,13 @@ func NewSyncService(rdb *redis.Client) *SyncService {
// SyncKey writes a single key into Redis without rebuilding the entire snapshot.
func (s *SyncService) SyncKey(key *model.Key) error {
ctx := context.Background()
tokenHash := util.HashToken(key.KeySecret)
tokenHash := key.TokenHash
if strings.TrimSpace(tokenHash) == "" {
tokenHash = util.HashToken(key.KeySecret) // backward compatibility
}
if strings.TrimSpace(tokenHash) == "" {
return fmt.Errorf("token hash missing for key %d", key.ID)
}
fields := map[string]interface{}{
"master_id": key.MasterID,
@@ -38,6 +44,20 @@ func (s *SyncService) SyncKey(key *model.Key) error {
return nil
}
// SyncMaster writes master metadata into Redis used by the balancer for validation.
func (s *SyncService) SyncMaster(master *model.Master) error {
ctx := context.Background()
key := fmt.Sprintf("auth:master:%d", master.ID)
if err := s.rdb.HSet(ctx, key, map[string]interface{}{
"epoch": master.Epoch,
"status": master.Status,
"global_qps": master.GlobalQPS,
}).Err(); err != nil {
return fmt.Errorf("write master metadata: %w", err)
}
return nil
}
// SyncProvider writes a single provider into Redis hash storage and updates routing tables.
func (s *SyncService) SyncProvider(provider *model.Provider) error {
ctx := context.Background()
@@ -187,7 +207,13 @@ func (s *SyncService) SyncAll(db *gorm.DB) error {
}
for _, k := range keys {
tokenHash := util.HashToken(k.KeySecret)
tokenHash := strings.TrimSpace(k.TokenHash)
if tokenHash == "" {
tokenHash = util.HashToken(k.KeySecret) // fallback for legacy rows
}
if tokenHash == "" {
return fmt.Errorf("token hash missing for key %d", k.ID)
}
pipe.HSet(ctx, fmt.Sprintf("auth:token:%s", tokenHash), map[string]interface{}{
"master_id": k.MasterID,
"issued_at_epoch": k.IssuedAtEpoch,