intelligent_test_protection.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package service
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/gin-gonic/gin"
  6. "github.com/google/uuid"
  7. )
  8. const intelligentTestIdentityKey = "intelligent_test_identity"
  9. type intelligentTestIdentity struct {
  10. sessionID string
  11. threadID string
  12. }
  13. // Connectivity and capability tests share the gateway's configured identity.
  14. // Independent probes get fresh source sessions; session/full strategies then
  15. // apply their explicit convergence rules to those sessions.
  16. func prepareIntelligentTestProtection(c *gin.Context, account *Account, payload map[string]any) error {
  17. if c == nil || c.Request == nil || !account.AntiDegradationEnabled() {
  18. return nil
  19. }
  20. if err := ValidateAccountProtectionConfiguration(account); err != nil {
  21. return err
  22. }
  23. if !isOpenAIOAuthLike(account) || account.GetCodexFingerprintMode() == codexFingerprintOff {
  24. return nil
  25. }
  26. if _, err := resolveMode1TLSProfile(account); err != nil {
  27. return err
  28. }
  29. original, err := json.Marshal(payload)
  30. if err != nil {
  31. return err
  32. }
  33. stageMode1Request(c, account, original)
  34. rawSession := uuid.NewString()
  35. ids := resolveCodexFingerprintIDs(account, rawSession, account.GetCodexFingerprintMode())
  36. stageCodexFingerprintIDs(c, ids)
  37. identity := intelligentTestIdentity{
  38. sessionID: isolateOpenAIUpstreamSessionID(0, account, rawSession),
  39. threadID: scopeCodexAccountIdentityValue(account, 0, "thread", rawSession),
  40. }
  41. if ids != nil && ids.mode != codexFingerprintDevice {
  42. identity.sessionID, identity.threadID = ids.sessionID, ids.threadID
  43. }
  44. c.Request.Header.Set("session-id", rawSession)
  45. c.Set(intelligentTestIdentityKey, identity)
  46. applyStagedCodexFingerprintClientMetadata(c, account, payload)
  47. metadata, _ := payload["client_metadata"].(map[string]any)
  48. metadata["session_id"] = identity.sessionID
  49. metadata["thread_id"] = identity.threadID
  50. return nil
  51. }
  52. func applyIntelligentTestProtection(c *gin.Context, account *Account, headers http.Header, payload []byte) error {
  53. if c == nil {
  54. return nil
  55. }
  56. value, exists := c.Get(intelligentTestIdentityKey)
  57. identity, ok := value.(intelligentTestIdentity)
  58. if !exists || !ok {
  59. return nil
  60. }
  61. // Apply after account header overrides, matching the protected gateway.
  62. applyStagedCodexFingerprintHeaders(c, account, headers)
  63. headers.Set("conversation_id", identity.sessionID)
  64. headers.Set("thread-id", identity.threadID)
  65. return validateMode1StagedRequest(c, account, payload)
  66. }