Files
sub2api/backend/internal/service/openai_cyber_session_block.go
T
shaw 7e3b6c72fa fix(openai): 按已屏蔽前缀长度精确匹配 cyber transcript,修复长会话误拦 (#8519)
同一来源触发 cyber 屏蔽后,scope 激活期间任何历史超过 256 个 item 的
会话都会因 lookup 截断被 fail-closed 判为 transcript_lookup_limit_exceeded,
即使与被屏蔽会话毫无关系、且带有不同的显式 session_id。

改为在命中时记录 transcript 屏蔽 key 覆盖的历史长度(按 API Key 建 Redis
SET 索引,随 scope 同 TTL),查询时仅在这些长度处重算前缀哈希:
- 无关长会话不再被误拦,历史长度本身不再决定屏蔽
- 追加任意数量 item 仍能命中被屏蔽前缀,防逃逸能力不降
- 查询 MGET 由最多 256 key 降为记录长度数,遍历在最长记录长度处提前终止
- scope 门控、API Key 命名空间与 cyber-transcript:v3 哈希格式均不变
2026-11-05 21:51:26 +08:00

148 lines
5.3 KiB
Go

package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"strconv"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/gin-gonic/gin"
)
// CyberSessionBlockStore 是 cyber 会话屏蔽表的存取接口。
// repository 层 gatewayCache 附带实现(类型断言探测接入,不改 GatewayCache
// 共享接口);测试 stub 不实现时屏蔽能力自动降级关闭。
type CyberSessionBlockStore interface {
SetCyberSessionBlocked(ctx context.Context, block CyberSessionBlock, ttl time.Duration) error
// CyberSessionTranscriptLengths returns the recorded transcript block
// lengths of the API key, or none when the source scope is inactive.
CyberSessionTranscriptLengths(ctx context.Context, apiKeyID int64, scopeKey string) ([]int, error)
FindCyberSessionBlocked(ctx context.Context, keys []string) (string, error)
}
// CyberSessionBlock is one cyber hit to persist. Keys are exact block keys;
// TranscriptLengths records the history length of each transcript key among
// them and, like ScopeKey, is only meaningful for transcript matching.
type CyberSessionBlock struct {
APIKeyID int64
ScopeKey string
Keys []string
TranscriptLengths []int
}
// CyberSessionExplicitBlockKey returns an inexpensive exact key when the
// client supplies a stable session signal.
func CyberSessionExplicitBlockKey(apiKeyID int64, c *gin.Context, body []byte) string {
return hashCyberSessionBlockKey(apiKeyID, explicitOpenAISessionID(c, body))
}
// CyberSessionScopeKey is a coarse, non-blocking fingerprint used only to
// avoid transcript parsing and MGET for sources that never produced a hit.
func CyberSessionScopeKey(apiKeyID int64, clientIP, userAgent string) string {
if apiKeyID <= 0 {
return ""
}
raw := "cyber-scope:v1|api_key=" + strconv.FormatInt(apiKeyID, 10) +
"|ip=" + strings.TrimSpace(clientIP) +
"|ua=" + NormalizeSessionUserAgent(userAgent)
sum := sha256.Sum256([]byte(raw))
return hex.EncodeToString(sum[:])
}
func hashCyberSessionBlockKey(apiKeyID int64, raw string) string {
if raw == "" {
return ""
}
isolated := isolateOpenAISessionID(apiKeyID, raw)
sum := sha256.Sum256([]byte(isolated))
return hex.EncodeToString(sum[:])
}
// cyberSessionBlockStore 探测 cache 是否具备屏蔽存储能力。
// 注意:若未来以装饰器包装 GatewayCache(如日志/指标装饰器),该装饰器必须同时实现
// CyberSessionBlockStore,否则会话屏蔽能力将静默降级关闭
// (编译断言 var _ service.CyberSessionBlockStore = (*gatewayCache)(nil) 只覆盖
// *gatewayCache 本体,无法覆盖其外层包装)。
func (s *OpenAIGatewayService) cyberSessionBlockStore() CyberSessionBlockStore {
if s == nil || s.cache == nil {
return nil
}
store, ok := s.cache.(CyberSessionBlockStore)
if !ok {
return nil
}
return store
}
// CyberSessionBlockRuntime 返回 (开关, TTL)。开关默认关。
// 委托给 SettingService.GetCyberSessionBlockRuntime,进程内缓存避免热路径 DB 往返。
func (s *OpenAIGatewayService) CyberSessionBlockRuntime(ctx context.Context) (bool, time.Duration) {
if s == nil || s.settingService == nil {
return false, time.Hour
}
return s.settingService.GetCyberSessionBlockRuntime(ctx)
}
// MarkCyberSessionBlocked 把会话写入屏蔽表(写入点:cyber 命中后)。
// 开关关闭、key 为空或存储不可用时静默跳过。
func (s *OpenAIGatewayService) MarkCyberSessionBlocked(ctx context.Context, block CyberSessionBlock) {
if s == nil || len(block.Keys) == 0 {
return
}
enabled, ttl := s.CyberSessionBlockRuntime(ctx)
if !enabled {
return
}
store := s.cyberSessionBlockStore()
if store == nil {
return
}
if err := store.SetCyberSessionBlocked(ctx, block, ttl); err != nil {
logger.LegacyPrintf("service.openai_gateway", "cyber session block write failed: err=%v", err)
}
}
// FindCyberSessionBlockedForRequest applies explicit-first lookup followed by
// scope-gated transcript matching. All failures remain fail-open.
func (s *OpenAIGatewayService) FindCyberSessionBlockedForRequest(ctx context.Context, apiKeyID int64, c *gin.Context, body []byte, clientIP, userAgent string) string {
enabled, _ := s.CyberSessionBlockRuntime(ctx)
if !enabled {
return ""
}
store := s.cyberSessionBlockStore()
if store == nil {
return ""
}
if explicitKey := CyberSessionExplicitBlockKey(apiKeyID, c, body); explicitKey != "" {
key, err := store.FindCyberSessionBlocked(ctx, []string{explicitKey})
if err != nil {
logger.LegacyPrintf("service.openai_gateway", "cyber explicit session read failed: err=%v", err)
return ""
}
if key != "" {
return key
}
}
lengths, err := store.CyberSessionTranscriptLengths(ctx, apiKeyID, CyberSessionScopeKey(apiKeyID, clientIP, userAgent))
if err != nil {
logger.LegacyPrintf("service.openai_gateway", "cyber session scope read failed: err=%v", err)
return ""
}
// Blocked prefixes are recomputed only at their recorded lengths, so any
// number of appended items still reaches them and history length alone
// never decides a block.
keys := cyberSessionTranscriptKeysAt(apiKeyID, body, lengths)
if len(keys) == 0 {
return ""
}
key, err := store.FindCyberSessionBlocked(ctx, keys)
if err != nil {
logger.LegacyPrintf("service.openai_gateway", "cyber session block batch read failed: err=%v", err)
return ""
}
return key
}