mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
Merge pull request #9117 from Wei-Shaw/fix/issue-8992-image-safety-risk-control
fix(risk-control): 生图安全系统拒绝纳入风控中心(仅留证)
This commit is contained in:
11 files changed
+626
-3
No files matched your search
@@ -292,6 +292,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), false, nil, err)
|
||||
} else {
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), true, nil)
|
||||
h.recordOpenAIImagesSafetyRefusal(c, apiKey, account, clientRequestModel, parsed.Prompt, imageUpstreamErr)
|
||||
}
|
||||
logEvent := "openai.images.upstream_user_error"
|
||||
if retryableServerError {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const imageSafetyRecordTimeout = 30 * time.Second
|
||||
|
||||
// recordOpenAIImagesSafetyRefusal 在图像上游以安全系统拒绝终结请求时,异步把事件
|
||||
// 写入风控中心。拒绝已经返回给用户,这里只做留证,不影响响应。
|
||||
func (h *OpenAIGatewayHandler) recordOpenAIImagesSafetyRefusal(c *gin.Context, apiKey *service.APIKey, account *service.Account, model string, prompt string, upErr *service.OpenAIImagesUpstreamError) {
|
||||
cmSvc := h.contentModerationService
|
||||
if cmSvc == nil || c == nil || !service.IsOpenAIImagesSafetyRefusal(upErr) {
|
||||
return
|
||||
}
|
||||
// 在 gin.Context 回收前把需要的值拍成标量。
|
||||
// request_id 取 context 中网关自己的 ID(与运维错误日志、转发前审核日志同源):
|
||||
// 响应头里的 X-Request-Id 属于可透传头,可能已被上游的 x-request-id 覆盖。
|
||||
requestID := ""
|
||||
if c.Request != nil {
|
||||
requestID = contentModerationRequestID(c.Request.Context())
|
||||
}
|
||||
if requestID == "" {
|
||||
requestID = c.Writer.Header().Get("X-Request-Id")
|
||||
}
|
||||
in := service.ImageSafetyRecordInput{
|
||||
RequestID: requestID,
|
||||
Endpoint: GetInboundEndpoint(c),
|
||||
Model: model,
|
||||
Prompt: prompt,
|
||||
UpstreamStatus: upErr.StatusCode,
|
||||
UpstreamType: upErr.ErrorType,
|
||||
UpstreamCode: upErr.Code,
|
||||
UpstreamMessage: upErr.Message,
|
||||
UpstreamRequestID: upErr.UpstreamRequestID,
|
||||
}
|
||||
if apiKey != nil {
|
||||
in.APIKeyID = apiKey.ID
|
||||
in.APIKeyName = apiKey.Name
|
||||
in.GroupID = apiKey.GroupID
|
||||
if apiKey.User != nil {
|
||||
in.UserID = apiKey.User.ID
|
||||
in.UserEmail = apiKey.User.Email
|
||||
}
|
||||
if apiKey.Group != nil {
|
||||
in.GroupName = apiKey.Group.Name
|
||||
}
|
||||
}
|
||||
if account != nil {
|
||||
in.Provider = account.Platform
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), imageSafetyRecordTimeout)
|
||||
defer cancel()
|
||||
cmSvc.RecordImageSafetyEvent(ctx, in)
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type openAIImagesStaticHTTPUpstream struct {
|
||||
service.HTTPUpstream
|
||||
status int
|
||||
body string
|
||||
}
|
||||
|
||||
func (u *openAIImagesStaticHTTPUpstream) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: u.status,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"application/json"},
|
||||
"X-Request-Id": []string{"upstream-req-1"},
|
||||
},
|
||||
Body: io.NopCloser(bytes.NewBufferString(u.body)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func runOpenAIImagesWithUpstream(t *testing.T, status int, upstreamBody string) (*httptest.ResponseRecorder, *contentModerationHandlerTestRepo) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
groupID := int64(8992)
|
||||
accountRepo := openAIImagesFailoverAccountRepo{accounts: []service.Account{{
|
||||
ID: 1,
|
||||
Name: "image-apikey",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
}}}
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
gatewayService := service.NewOpenAIGatewayService(
|
||||
accountRepo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil,
|
||||
&openAIImagesStaticHTTPUpstream{status: status, body: upstreamBody},
|
||||
nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
billingService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingService.Stop)
|
||||
h := NewOpenAIGatewayHandler(
|
||||
gatewayService,
|
||||
service.NewConcurrencyService(nil),
|
||||
billingService,
|
||||
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg),
|
||||
nil, nil, nil, nil,
|
||||
cfg,
|
||||
)
|
||||
repo := &contentModerationHandlerTestRepo{}
|
||||
h.contentModerationService = service.NewContentModerationService(
|
||||
&contentModerationHandlerSettingRepo{values: map[string]string{
|
||||
service.SettingKeyRiskControlEnabled: "true",
|
||||
service.SettingKeyContentModerationConfig: `{"enabled":false,"mode":"off","all_groups":true}`,
|
||||
}},
|
||||
repo, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
body := []byte(`{"model":"gpt-image-1","prompt":"draw a forbidden thing","size":"1024x1024"}`)
|
||||
ctx := context.WithValue(context.Background(), ctxkey.RequestID, "gateway-req-8992")
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)).WithContext(ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: 99,
|
||||
Name: "issue-key",
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Name: "img-group", AllowImageGeneration: true},
|
||||
User: &service.User{ID: 100, Email: "user@example.com"},
|
||||
})
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100})
|
||||
|
||||
h.Images(c)
|
||||
return rec, repo
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerImages_SafetySystemRejectionRecordedInRiskControl(t *testing.T) {
|
||||
const msg = "Your request was rejected by the safety system. If you believe this is an error, contact us at help.openai.com and include the request ID b553d2f5-3906-4f26-aa3a-e3bb7e24396c."
|
||||
rec, repo := runOpenAIImagesWithUpstream(t, http.StatusBadRequest, `{"error":{"message":"`+msg+`"}}`)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "safety system")
|
||||
|
||||
require.Eventually(t, func() bool { return len(repo.logSnapshot()) == 1 }, 2*time.Second, 10*time.Millisecond)
|
||||
log := repo.logSnapshot()[0]
|
||||
require.Equal(t, service.ContentModerationActionImageSafety, log.Action)
|
||||
require.Equal(t, service.ContentModerationModeRiskControlLogOnly, log.Mode)
|
||||
require.True(t, log.Flagged)
|
||||
require.Equal(t, "gateway-req-8992", log.RequestID, "must join with the ops error log, not the upstream request id")
|
||||
require.Contains(t, log.Error, "upstream_request_id=upstream-req-1")
|
||||
require.NotNil(t, log.UserID)
|
||||
require.Equal(t, int64(100), *log.UserID)
|
||||
require.Equal(t, "user@example.com", log.UserEmail)
|
||||
require.Equal(t, "issue-key", log.APIKeyName)
|
||||
require.Equal(t, "img-group", log.GroupName)
|
||||
require.Equal(t, "gpt-image-1", log.Model)
|
||||
require.Equal(t, service.PlatformOpenAI, log.Provider)
|
||||
require.Equal(t, "draw a forbidden thing", log.InputExcerpt)
|
||||
require.Contains(t, log.Error, "safety system")
|
||||
require.Contains(t, log.Error, "upstream_status=400")
|
||||
require.False(t, log.AutoBanned)
|
||||
require.False(t, log.EmailSent)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerImages_NonSafety400NotRecorded(t *testing.T) {
|
||||
rec, repo := runOpenAIImagesWithUpstream(t, http.StatusBadRequest, `{"error":{"message":"Invalid size","type":"invalid_request_error","param":"size"}}`)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
require.Never(t, func() bool { return len(repo.logSnapshot()) > 0 }, 200*time.Millisecond, 10*time.Millisecond)
|
||||
}
|
||||
@@ -280,7 +280,9 @@ func buildContentModerationLogWhere(filter service.ContentModerationLogFilter) (
|
||||
case "pass", "allow":
|
||||
where = append(where, "l.flagged = FALSE AND l.error = ''")
|
||||
case "error":
|
||||
where = append(where, "l.error <> ''")
|
||||
// image_safety keeps the upstream rejection in error; it is a hit, not an
|
||||
// audit failure. Literal must match service.ContentModerationActionImageSafety.
|
||||
where = append(where, "l.error <> '' AND l.action <> 'image_safety'")
|
||||
}
|
||||
if filter.GroupID != nil {
|
||||
add("l.group_id = $%d", *filter.GroupID)
|
||||
|
||||
@@ -67,6 +67,15 @@ func TestBuildContentModerationLogWhere_BlockedIncludesAllBlockActions(t *testin
|
||||
require.NotContains(t, sql, "l.action = 'block'")
|
||||
}
|
||||
|
||||
func TestBuildContentModerationLogWhere_ErrorExcludesImageSafetyEvidence(t *testing.T) {
|
||||
where, args := buildContentModerationLogWhere(service.ContentModerationLogFilter{Result: "error"})
|
||||
|
||||
require.Empty(t, args)
|
||||
sql := strings.Join(where, " AND ")
|
||||
require.Contains(t, sql, "l.error <> ''")
|
||||
require.Contains(t, sql, "l.action <> '"+service.ContentModerationActionImageSafety+"'")
|
||||
}
|
||||
|
||||
func TestContentModerationRepositoryCountFlaggedByUserSince_ExcludesHashBlock(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ContentModerationActionImageSafety 是上游图像安全系统拒绝生图时写入风控中心的 action。
|
||||
const ContentModerationActionImageSafety = "image_safety"
|
||||
|
||||
// IsOpenAIImagesSafetyRefusal 判断一次终态图像上游错误是否为上游安全系统拒绝。
|
||||
//
|
||||
// 只认 400:上游安全拒绝(如 "Your request was rejected by the safety system")
|
||||
// 与 Responses 生图兜底合成的 content_policy_violation 都是 400;其余状态码
|
||||
// 描述的是账号/上游故障而不是用户内容。
|
||||
//
|
||||
// 判定顺序:
|
||||
// 1. 明确的安全类 error.code 直接认定(包括 Azure 带 param=prompt 的
|
||||
// content_filter);response.incomplete 只有在 content_filter/moderation
|
||||
// 原因下才会是 400,同样认定。
|
||||
// 2. 只能看文案时更保守:带 error.param 的 400 是参数校验错误,排除;文案
|
||||
// 是"未知/不支持的参数"之类时排除;关键词表不含单独的 "moderation"——
|
||||
// images 接口自身有 moderation 参数,兼容上游常回
|
||||
// "Unrecognized request argument supplied: moderation" 且 param 为 null。
|
||||
// 误报会留存无辜用户的提示词,宁可漏记也不误记。
|
||||
func IsOpenAIImagesSafetyRefusal(err *OpenAIImagesUpstreamError) bool {
|
||||
if err == nil || err.StatusCode != http.StatusBadRequest {
|
||||
return false
|
||||
}
|
||||
code := strings.ToLower(strings.TrimSpace(err.Code))
|
||||
if code == "response_incomplete" ||
|
||||
code == "moderation_blocked" ||
|
||||
code == "contentfilter" ||
|
||||
strings.Contains(code, "content_filter") ||
|
||||
strings.Contains(code, "content_policy") ||
|
||||
strings.Contains(code, "policy_violation") ||
|
||||
strings.Contains(code, "safety_violation") ||
|
||||
strings.Contains(code, "responsibleaipolicyviolation") {
|
||||
return true
|
||||
}
|
||||
if strings.TrimSpace(err.Param) != "" {
|
||||
return false
|
||||
}
|
||||
return isImageSafetyRefusalMessage(err.Message)
|
||||
}
|
||||
|
||||
var imageSafetyParameterErrorMarkers = []string{
|
||||
"unrecognized request argument",
|
||||
"unknown parameter",
|
||||
"unsupported parameter",
|
||||
"unexpected parameter",
|
||||
"invalid parameter",
|
||||
"invalid value",
|
||||
"unrecognized parameter",
|
||||
}
|
||||
|
||||
var imageSafetyRefusalMarkers = []string{
|
||||
"safety system", "safety policy", "safety violation",
|
||||
"content policy", "content_policy", "content filter", "content_filter",
|
||||
"content management policy", "moderation_blocked",
|
||||
"安全系统", "安全策略", "安全政策", "内容政策", "内容审核", "违规内容", "不适合生成",
|
||||
}
|
||||
|
||||
func isImageSafetyRefusalMessage(message string) bool {
|
||||
lower := strings.ToLower(message)
|
||||
for _, marker := range imageSafetyParameterErrorMarkers {
|
||||
if strings.Contains(lower, marker) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, marker := range imageSafetyRefusalMarkers {
|
||||
if strings.Contains(lower, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ImageSafetyRecordInput 是一次图像上游安全拒绝的风控记录入参。
|
||||
type ImageSafetyRecordInput struct {
|
||||
RequestID string
|
||||
UserID int64
|
||||
UserEmail string
|
||||
APIKeyID int64
|
||||
APIKeyName string
|
||||
GroupID *int64
|
||||
GroupName string
|
||||
Endpoint string
|
||||
Provider string
|
||||
Model string
|
||||
Prompt string
|
||||
UpstreamStatus int
|
||||
UpstreamType string
|
||||
UpstreamCode string
|
||||
UpstreamMessage string
|
||||
UpstreamRequestID string
|
||||
}
|
||||
|
||||
// RecordImageSafetyEvent 把一次图像上游安全拒绝写入风控中心日志,仅作留证。
|
||||
//
|
||||
// 拒绝已由网关原样返回给用户;本方法是事后记录,不改变响应。上游安全系统对
|
||||
// 图像存在误判,因此记录固定为 risk_control_log_only:不写哈希黑名单、不计入
|
||||
// 自动封号次数、不发邮件。受 risk_control_enabled 总开关与内容审核
|
||||
// group/model scope 约束,不受内容审核 Enabled/Mode/sample 约束(与
|
||||
// cyber_policy 记录一致)。
|
||||
func (s *ContentModerationService) RecordImageSafetyEvent(ctx context.Context, in ImageSafetyRecordInput) {
|
||||
if s == nil || s.repo == nil {
|
||||
return
|
||||
}
|
||||
runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx)
|
||||
if err != nil {
|
||||
slog.Warn("content_moderation.image_safety_runtime_snapshot_load_failed", "error", err)
|
||||
return
|
||||
}
|
||||
if !runtimeSnapshot.riskControlEnabled {
|
||||
return
|
||||
}
|
||||
cfg := runtimeSnapshot.config
|
||||
if !cfg.includesGroup(in.GroupID) || !cfg.includesModel(in.Model) {
|
||||
return
|
||||
}
|
||||
var userID *int64
|
||||
if in.UserID > 0 {
|
||||
userID = &in.UserID
|
||||
}
|
||||
var apiKeyID *int64
|
||||
if in.APIKeyID > 0 {
|
||||
apiKeyID = &in.APIKeyID
|
||||
}
|
||||
provider := strings.TrimSpace(in.Provider)
|
||||
if provider == "" {
|
||||
provider = PlatformOpenAI
|
||||
}
|
||||
log := &ContentModerationLog{
|
||||
RequestID: in.RequestID,
|
||||
UserID: userID,
|
||||
UserEmail: in.UserEmail,
|
||||
APIKeyID: apiKeyID,
|
||||
APIKeyName: in.APIKeyName,
|
||||
GroupID: cloneInt64Ptr(in.GroupID),
|
||||
GroupName: in.GroupName,
|
||||
Endpoint: in.Endpoint,
|
||||
Provider: provider,
|
||||
Model: in.Model,
|
||||
Mode: ContentModerationModeRiskControlLogOnly,
|
||||
Action: ContentModerationActionImageSafety,
|
||||
Flagged: true,
|
||||
HighestCategory: ContentModerationActionImageSafety,
|
||||
HighestScore: 1.0,
|
||||
InputExcerpt: trimRunes(redactContentModerationSecrets(strings.TrimSpace(in.Prompt)), maxModerationExcerptRunes),
|
||||
Error: trimRunes(redactContentModerationSecrets(formatImageSafetyUpstreamDetail(in)), maxModerationExcerptRunes*4),
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
if err := s.repo.CreateLog(ctx, log); err != nil {
|
||||
slog.Warn("content_moderation.image_safety_create_log_failed", "user_id", in.UserID, "endpoint", in.Endpoint, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func formatImageSafetyUpstreamDetail(in ImageSafetyRecordInput) string {
|
||||
parts := make([]string, 0, 4)
|
||||
if in.UpstreamStatus > 0 {
|
||||
parts = append(parts, fmt.Sprintf("upstream_status=%d", in.UpstreamStatus))
|
||||
}
|
||||
if v := strings.TrimSpace(in.UpstreamType); v != "" {
|
||||
parts = append(parts, "type="+v)
|
||||
}
|
||||
if v := strings.TrimSpace(in.UpstreamCode); v != "" {
|
||||
parts = append(parts, "code="+v)
|
||||
}
|
||||
if v := strings.TrimSpace(in.UpstreamRequestID); v != "" {
|
||||
parts = append(parts, "upstream_request_id="+v)
|
||||
}
|
||||
detail := strings.Join(parts, " ")
|
||||
if msg := strings.TrimSpace(in.UpstreamMessage); msg != "" {
|
||||
if detail != "" {
|
||||
detail += "\n"
|
||||
}
|
||||
detail += msg
|
||||
}
|
||||
return detail
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestIsOpenAIImagesSafetyRefusal(t *testing.T) {
|
||||
const safetyMsg = "Your request was rejected by the safety system. If you believe this is an error, contact us at help.openai.com and include the request ID b553d2f5."
|
||||
tests := []struct {
|
||||
name string
|
||||
err *OpenAIImagesUpstreamError
|
||||
want bool
|
||||
}{
|
||||
{name: "nil", err: nil, want: false},
|
||||
{
|
||||
name: "issue 8992: 400 safety system message without type or code",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"message":"`+safetyMsg+`"}}`)),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "400 safety system message with numeric code 400",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"message":"`+safetyMsg+`","code":400}}`)),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "moderation_blocked code",
|
||||
err: &OpenAIImagesUpstreamError{StatusCode: http.StatusBadRequest, ErrorType: "image_generation_user_error", Code: "moderation_blocked", Message: "blocked"},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "responses text fallback refusal",
|
||||
err: openAIImagesTextFallbackErrorForText("I can't help with that because it violates our content policy."),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "response.incomplete content_filter",
|
||||
err: &OpenAIImagesUpstreamError{StatusCode: http.StatusBadRequest, ErrorType: "image_generation_user_error", Code: "response_incomplete", Message: "Upstream image generation incomplete: content_filter"},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "invalid moderation parameter is a validation error",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"message":"Invalid value: 'strict'. Supported values for moderation are: 'low' and 'auto'.","type":"invalid_request_error","param":"moderation","code":"invalid_value"}}`)),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "plain invalid size 400",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"message":"Invalid size","code":400}}`)),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "safety wording on non-400 status",
|
||||
err: &OpenAIImagesUpstreamError{StatusCode: http.StatusBadGateway, Message: safetyMsg},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "azure: unrecognized moderation argument with null param",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"message":"Unrecognized request argument supplied: moderation","type":"invalid_request_error","param":null,"code":null}}`)),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "unknown moderation parameter without param field",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"message":"Unknown parameter: 'moderation'."}}`)),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "error passthrough rewrite drops param and code",
|
||||
err: &OpenAIImagesUpstreamError{StatusCode: http.StatusBadRequest, ErrorType: "upstream_error", Message: "Invalid moderation setting for this model"},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "azure content filter with param prompt",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"message":"The response was filtered due to the prompt triggering Azure OpenAI's content management policy.","type":null,"param":"prompt","code":"content_filter"}}`)),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "azure contentFilter code",
|
||||
err: openAIImagesUpstreamErrorFromHTTP(http.StatusBadRequest, nil, []byte(`{"error":{"code":"contentFilter","message":"Your task failed as a result of our safety system."}}`)),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "response.incomplete moderation reason",
|
||||
err: openAIImagesIncompleteUpstreamError(gjson.Parse(`{"id":"resp_1","incomplete_details":{"reason":"moderation"}}`)),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "response.incomplete max_output_tokens is retryable, not safety",
|
||||
err: openAIImagesIncompleteUpstreamError(gjson.Parse(`{"id":"resp_1","incomplete_details":{"reason":"max_output_tokens"}}`)),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "safety wording with param set is excluded on the message path",
|
||||
err: &OpenAIImagesUpstreamError{StatusCode: http.StatusBadRequest, Param: "size", Message: "content policy for size values"},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "text fallback capability failure",
|
||||
err: openAIImagesTextFallbackErrorForText("Here is a description of the picture instead."),
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, IsOpenAIImagesSafetyRefusal(tt.err))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newImageSafetyTestService(t *testing.T, settings map[string]string) (*ContentModerationService, *contentModerationTestRepo) {
|
||||
t.Helper()
|
||||
repo := &contentModerationTestRepo{}
|
||||
svc := NewContentModerationService(
|
||||
&contentModerationTestSettingRepo{values: settings},
|
||||
repo,
|
||||
&contentModerationTestHashCache{},
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
return svc, repo
|
||||
}
|
||||
|
||||
func imageSafetyTestInput(groupID *int64) ImageSafetyRecordInput {
|
||||
return ImageSafetyRecordInput{
|
||||
RequestID: "req-1",
|
||||
UserID: 42,
|
||||
UserEmail: "u@example.com",
|
||||
APIKeyID: 9,
|
||||
APIKeyName: "key",
|
||||
GroupID: groupID,
|
||||
GroupName: "g",
|
||||
Endpoint: "/v1/images/generations",
|
||||
Provider: PlatformOpenAI,
|
||||
Model: "gpt-image-2",
|
||||
Prompt: "draw something sk-abcdefghijklmnopqrstuvwxyz0123456789",
|
||||
UpstreamStatus: http.StatusBadRequest,
|
||||
UpstreamType: "invalid_request_error",
|
||||
UpstreamMessage: "Your request was rejected by the safety system.",
|
||||
UpstreamRequestID: "b553d2f5",
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordImageSafetyEvent_DisabledWhenRiskControlOff(t *testing.T) {
|
||||
svc, repo := newImageSafetyTestService(t, map[string]string{SettingKeyRiskControlEnabled: "false"})
|
||||
svc.RecordImageSafetyEvent(context.Background(), imageSafetyTestInput(nil))
|
||||
require.Empty(t, repo.snapshotLogs())
|
||||
}
|
||||
|
||||
func TestRecordImageSafetyEvent_WritesLogOnlyEvidence(t *testing.T) {
|
||||
svc, repo := newImageSafetyTestService(t, map[string]string{
|
||||
SettingKeyRiskControlEnabled: "true",
|
||||
SettingKeyContentModerationConfig: `{"enabled":false,"mode":"off","all_groups":true,"auto_ban_enabled":true,"ban_threshold":1}`,
|
||||
})
|
||||
svc.RecordImageSafetyEvent(context.Background(), imageSafetyTestInput(nil))
|
||||
|
||||
logs := repo.snapshotLogs()
|
||||
require.Len(t, logs, 1)
|
||||
log := logs[0]
|
||||
require.Equal(t, ContentModerationActionImageSafety, log.Action)
|
||||
require.Equal(t, ContentModerationModeRiskControlLogOnly, log.Mode, "image safety evidence must never feed the auto-ban count")
|
||||
require.True(t, log.Flagged)
|
||||
require.Equal(t, ContentModerationActionImageSafety, log.HighestCategory)
|
||||
require.Equal(t, 1.0, log.HighestScore)
|
||||
require.NotNil(t, log.UserID)
|
||||
require.Equal(t, int64(42), *log.UserID)
|
||||
require.Equal(t, "u@example.com", log.UserEmail)
|
||||
require.Equal(t, "/v1/images/generations", log.Endpoint)
|
||||
require.Equal(t, PlatformOpenAI, log.Provider)
|
||||
require.Equal(t, "gpt-image-2", log.Model)
|
||||
require.Contains(t, log.InputExcerpt, "draw something")
|
||||
require.NotContains(t, log.InputExcerpt, "sk-abcdefghijklmnopqrstuvwxyz0123456789", "prompt excerpt must be redacted")
|
||||
require.Contains(t, log.Error, "upstream_status=400")
|
||||
require.Contains(t, log.Error, "upstream_request_id=b553d2f5")
|
||||
require.Contains(t, log.Error, "safety system")
|
||||
require.False(t, log.AutoBanned)
|
||||
require.False(t, log.EmailSent)
|
||||
require.Zero(t, log.ViolationCount)
|
||||
}
|
||||
|
||||
func TestRecordImageSafetyEvent_RespectsScope(t *testing.T) {
|
||||
groupID := int64(7)
|
||||
tests := []struct {
|
||||
name string
|
||||
config string
|
||||
groupID *int64
|
||||
wantLogs int
|
||||
}{
|
||||
{name: "excluded group", config: `{"all_groups":false,"group_ids":[8]}`, groupID: &groupID, wantLogs: 0},
|
||||
{name: "excluded model", config: `{"all_groups":true,"model_filter":{"type":"include","models":["gpt-5"]}}`, groupID: &groupID, wantLogs: 0},
|
||||
{name: "included", config: `{"all_groups":false,"group_ids":[7],"model_filter":{"type":"include","models":["gpt-image-2"]}}`, groupID: &groupID, wantLogs: 1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
svc, repo := newImageSafetyTestService(t, map[string]string{
|
||||
SettingKeyRiskControlEnabled: "true",
|
||||
SettingKeyContentModerationConfig: tt.config,
|
||||
})
|
||||
svc.RecordImageSafetyEvent(context.Background(), imageSafetyTestInput(tt.groupID))
|
||||
require.Len(t, repo.snapshotLogs(), tt.wantLogs)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -528,6 +528,7 @@ export default {
|
||||
block: 'Blocked',
|
||||
keywordBlock: 'Keyword Blocked',
|
||||
cyberPolicy: 'Cyber policy',
|
||||
imageSafety: 'Image safety rejection',
|
||||
error: 'Error',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -528,6 +528,7 @@ export default {
|
||||
block: '拦截',
|
||||
keywordBlock: '关键词拦截',
|
||||
cyberPolicy: '网络安全策略',
|
||||
imageSafety: '生图安全拒绝',
|
||||
error: '异常',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1091,7 +1091,7 @@
|
||||
{{ engineLabel(inputDetailRow.engine_meta.engine) }} · {{ inputDetailRow.engine_meta.model || '-' }} · {{ inputDetailRow.engine_meta.rules_version || '-' }}
|
||||
<span v-if="inputDetailRow.engine_meta.skipped_images"> · {{ t('admin.riskControl.skippedImages', { count: inputDetailRow.engine_meta.skipped_images }) }}</span>
|
||||
</template>
|
||||
<template v-else>{{ ['cyber_policy', 'keyword_block', 'hash_block'].includes(inputDetailRow.action) ? '-' : t('admin.riskControl.legacyAuditSource') }}</template>
|
||||
<template v-else>{{ ['cyber_policy', 'image_safety', 'keyword_block', 'hash_block'].includes(inputDetailRow.action) ? '-' : t('admin.riskControl.legacyAuditSource') }}</template>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div class="rounded-lg border border-gray-100 bg-gray-50 p-4 dark:border-dark-700 dark:bg-dark-800/70">
|
||||
@@ -2231,6 +2231,7 @@ function modeDescription(mode: ModerationMode): string {
|
||||
|
||||
function resultLabel(row: ContentModerationLog): string {
|
||||
if (row.action === 'cyber_policy') return t('admin.riskControl.action.cyberPolicy')
|
||||
if (row.action === 'image_safety') return t('admin.riskControl.action.imageSafety')
|
||||
if (row.action === 'keyword_block') return t('admin.riskControl.action.keywordBlock')
|
||||
if (row.action === 'block') return t('admin.riskControl.action.block')
|
||||
if (row.action === 'error' || row.error) return t('admin.riskControl.action.error')
|
||||
@@ -2240,6 +2241,8 @@ function resultLabel(row: ContentModerationLog): string {
|
||||
|
||||
function resultBadgeClass(row: ContentModerationLog): string {
|
||||
if (row.action === 'block' || row.action === 'keyword_block' || row.action === 'cyber_policy') return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300'
|
||||
// image_safety stores the upstream rejection in `error`; it is a log-only hit, not an audit failure.
|
||||
if (row.action === 'image_safety') return 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300'
|
||||
if (row.action === 'error' || row.error) return 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'
|
||||
if (row.flagged) return 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300'
|
||||
return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'
|
||||
|
||||
@@ -4,7 +4,7 @@ import { flushPromises, mount } from '@vue/test-utils'
|
||||
import type { DOMWrapper, VueWrapper } from '@vue/test-utils'
|
||||
|
||||
import RiskControlView from '../RiskControlView.vue'
|
||||
import type { ContentModerationAPIKeyStatus, ContentModerationConfig, UpdateContentModerationConfig } from '@/api/admin/riskControl'
|
||||
import type { ContentModerationAPIKeyStatus, ContentModerationConfig, ContentModerationLog, UpdateContentModerationConfig } from '@/api/admin/riskControl'
|
||||
|
||||
const {
|
||||
getConfig,
|
||||
@@ -257,6 +257,27 @@ describe('admin RiskControlView', () => {
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('renders image safety rejections as log-only hits, not audit errors', async () => {
|
||||
const row: ContentModerationLog = {
|
||||
engine_meta: null, id: 1, request_id: 'req-1', user_id: 100, user_email: 'u@example.com',
|
||||
api_key_id: 9, api_key_name: 'key', group_id: 7, group_name: 'img', endpoint: '/v1/images/generations',
|
||||
provider: 'openai', model: 'gpt-image-2', mode: 'risk_control_log_only', action: 'image_safety', flagged: true,
|
||||
highest_category: 'image_safety', highest_score: 1, matched_keyword: '', category_scores: {}, threshold_snapshot: {},
|
||||
input_excerpt: 'draw something', upstream_latency_ms: null,
|
||||
error: 'upstream_status=400\nYour request was rejected by the safety system.',
|
||||
violation_count: 0, auto_banned: false, email_sent: false, user_status: 'active', queue_delay_ms: null,
|
||||
created_at: '2026-11-27T00:00:00Z',
|
||||
}
|
||||
listLogs.mockResolvedValue({ items: [row], total: 1, page: 1, page_size: 20, pages: 1 })
|
||||
const wrapper = mount(RiskControlView, { global: { stubs: { AppLayout: AppLayoutStub, BaseDialog: BaseDialogStub, Icon: true, Select: true, Toggle: true, Pagination: true, ModelWhitelistSelector: ModelWhitelistSelectorStub, ProxySelector: true } } })
|
||||
await flushPromises()
|
||||
|
||||
const badge = wrapper.findAll('span.rounded-md').find((el) => el.text() === 'admin.riskControl.action.imageSafety')
|
||||
expect(badge).toBeDefined()
|
||||
expect(badge!.classes()).toContain('bg-pink-100')
|
||||
expect(badge!.classes()).not.toContain('bg-amber-100')
|
||||
})
|
||||
|
||||
it('shows an empty key panel for an unconfigured draft engine', async () => {
|
||||
getStatus.mockResolvedValue({ ...runtimeStatus(), api_key_statuses: [{ masked: '********oa01', configured: true, status: 'ok' }] })
|
||||
const wrapper = mount(RiskControlView, { global: { stubs: { AppLayout: AppLayoutStub, BaseDialog: BaseDialogStub, Icon: true, Select: true, Toggle: true, Pagination: true, ModelWhitelistSelector: ModelWhitelistSelectorStub, ProxySelector: true } } })
|
||||
|
||||
Reference in new issue
Block a user