openai_images_b64_backfill.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package service
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "github.com/Wei-Shaw/sub2api/internal/pkg/logger"
  13. "github.com/Wei-Shaw/sub2api/internal/util/urlvalidator"
  14. "github.com/tidwall/gjson"
  15. "github.com/tidwall/sjson"
  16. )
  17. // AccountExtraImagesURLToB64JSON 是账户 extra 中的开关键。开启后,Images 端点的非流式响应里
  18. // b64_json 缺失或为空但 url 非空的图片项,由网关下载 url 内容并以 base64 回填到 b64_json。
  19. const AccountExtraImagesURLToB64JSON = "images_url_to_b64_json"
  20. // openAIImageURLDownloadTimeout 是单张图片 url 下载的超时上限。
  21. const openAIImageURLDownloadTimeout = 60 * time.Second
  22. // ImagesURLToB64JSONEnabled 返回账户是否开启了 url 转 b64_json 回填。
  23. func ImagesURLToB64JSONEnabled(account *Account) bool {
  24. return account != nil && account.getExtraBool(AccountExtraImagesURLToB64JSON)
  25. }
  26. // backfillOpenAIImagesB64JSON 对 Images 端点的非流式响应做 url 转 b64_json 回填。
  27. //
  28. // 只处理 data[i].b64_json 缺失或为空且 url 非空的项;url 字段原样保留。
  29. // 单项失败仅记日志并保留该项原样,响应整体照常返回。
  30. // 客户端显式要求 response_format=url 时不做回填。
  31. func (s *OpenAIGatewayService) backfillOpenAIImagesB64JSON(
  32. ctx context.Context,
  33. account *Account,
  34. parsed *OpenAIImagesRequest,
  35. body []byte,
  36. ) []byte {
  37. if !ImagesURLToB64JSONEnabled(account) {
  38. return body
  39. }
  40. if parsed != nil && parsed.ResponseFormat == "url" {
  41. return body
  42. }
  43. if len(body) == 0 || !gjson.ValidBytes(body) {
  44. return body
  45. }
  46. items := gjson.GetBytes(body, "data")
  47. if !items.IsArray() {
  48. return body
  49. }
  50. for index, item := range items.Array() {
  51. if !item.IsObject() {
  52. continue
  53. }
  54. if strings.TrimSpace(item.Get("b64_json").String()) != "" {
  55. continue
  56. }
  57. rawURL := strings.TrimSpace(item.Get("url").String())
  58. if rawURL == "" {
  59. continue
  60. }
  61. encoded, err := s.fetchOpenAIImageURLBase64(ctx, account, rawURL)
  62. if err != nil {
  63. logger.LegacyPrintf(
  64. "service.openai_gateway",
  65. "[OpenAI] Images b64_json backfill skipped account_id=%d index=%d err=%s",
  66. account.ID,
  67. index,
  68. sanitizeUpstreamErrorMessage(err.Error()),
  69. )
  70. continue
  71. }
  72. updated, err := sjson.SetBytes(body, fmt.Sprintf("data.%d.b64_json", index), encoded)
  73. if err != nil {
  74. logger.LegacyPrintf(
  75. "service.openai_gateway",
  76. "[OpenAI] Images b64_json backfill skipped account_id=%d index=%d err=%s",
  77. account.ID,
  78. index,
  79. sanitizeUpstreamErrorMessage(err.Error()),
  80. )
  81. continue
  82. }
  83. body = updated
  84. }
  85. return body
  86. }
  87. // fetchOpenAIImageURLBase64 取得图片 url 内容的标准 base64 编码。
  88. // data: 形式的 url 直接取其 base64 载荷;其余 url 先沿用 base_url 的出站 URL 策略校验,
  89. // 再无条件拒绝回环、私网、链路本地等目的地(含重定向的每一跳),经账户代理下载,
  90. // 大小上限与 OAuth 路径的单图下载一致,且前 512 字节须嗅探为 png/jpeg/webp/gif。
  91. func (s *OpenAIGatewayService) fetchOpenAIImageURLBase64(ctx context.Context, account *Account, rawURL string) (string, error) {
  92. if strings.HasPrefix(strings.ToLower(rawURL), "data:") {
  93. if encoded := normalizeOpenAIImageBase64(rawURL); encoded != "" {
  94. return encoded, nil
  95. }
  96. return "", errors.New("data url payload is not valid base64")
  97. }
  98. if s == nil || s.httpUpstream == nil {
  99. return "", errors.New("http upstream is not configured")
  100. }
  101. downloadURL, err := s.validateOutboundURL(rawURL)
  102. if err != nil {
  103. return "", fmt.Errorf("invalid image url: %w", err)
  104. }
  105. if err := rejectPrivateImageHost(downloadURL); err != nil {
  106. return "", err
  107. }
  108. ctx, cancel := context.WithTimeout(WithHTTPUpstreamPublicHostsOnly(ctx), openAIImageURLDownloadTimeout)
  109. defer cancel()
  110. req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil)
  111. if err != nil {
  112. return "", fmt.Errorf("build image download request: %w", err)
  113. }
  114. req.Header.Set("Accept", "image/*,*/*;q=0.8")
  115. proxyURL := ""
  116. if account.ProxyID != nil && account.Proxy != nil {
  117. proxyURL = account.Proxy.URL()
  118. }
  119. resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency)
  120. if err != nil {
  121. return "", fmt.Errorf("download image: %w", err)
  122. }
  123. defer func() { _ = resp.Body.Close() }()
  124. if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
  125. return "", fmt.Errorf("download image: unexpected status %d", resp.StatusCode)
  126. }
  127. data, err := io.ReadAll(io.LimitReader(resp.Body, openAIImageMaxDownloadBytes+1))
  128. if err != nil {
  129. return "", fmt.Errorf("read image body: %w", err)
  130. }
  131. if int64(len(data)) > openAIImageMaxDownloadBytes {
  132. return "", fmt.Errorf("downloaded image exceeds %d bytes", openAIImageMaxDownloadBytes)
  133. }
  134. if len(data) == 0 {
  135. return "", errors.New("download image: empty body")
  136. }
  137. if !isBackfillImageContent(data) {
  138. return "", errors.New("download image: content is not an allowed image format")
  139. }
  140. return base64.StdEncoding.EncodeToString(data), nil
  141. }
  142. // rejectPrivateImageHost 拒绝主机为 localhost 或回环、私网、链路本地、未指定地址字面量的下载 URL。
  143. // 不受 security.url_allowlist 配置影响;域名的解析结果与重定向的每一跳由上游客户端按
  144. // WithHTTPUpstreamPublicHostsOnly 标记校验。
  145. func rejectPrivateImageHost(downloadURL string) error {
  146. parsed, err := url.Parse(downloadURL)
  147. if err != nil {
  148. return fmt.Errorf("invalid image url: %w", err)
  149. }
  150. if host := parsed.Hostname(); urlvalidator.IsBlockedHost(host) {
  151. return fmt.Errorf("image url host is not allowed: %s", host)
  152. }
  153. return nil
  154. }
  155. // openAIImageBackfillContentTypes 是允许回填的图片格式,以字节嗅探结果为准,响应头不作为依据。
  156. var openAIImageBackfillContentTypes = map[string]struct{}{
  157. "image/png": {},
  158. "image/jpeg": {},
  159. "image/webp": {},
  160. "image/gif": {},
  161. }
  162. // isBackfillImageContent 报告 data 的前 512 字节是否嗅探为允许回填的图片格式。
  163. func isBackfillImageContent(data []byte) bool {
  164. _, ok := openAIImageBackfillContentTypes[detectedImageContentType(data)]
  165. return ok
  166. }