mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
fix(risk-control): tighten image safety detection and display
Review follow-up: - Stop treating parameter errors as safety rejections. The message matcher no longer uses a bare "moderation" keyword and rejects "unknown/unrecognized/unsupported parameter" style messages, so Azure-style "Unrecognized request argument supplied: moderation" (param null) and error-passthrough rewrites (which drop param/code) are not recorded with the user's prompt. - Check explicit safety codes before the param exclusion, so Azure content filtering (code=content_filter, param=prompt), contentFilter and ResponsibleAIPolicyViolation are recorded; response_incomplete is only a 400 for content_filter/moderation reasons and counts as well. - Show image_safety rows with the hit badge instead of the amber error badge, and exclude them from the "error" result filter.
This commit is contained in:
1 parent
75e6df8f4a
commit
397f66aebf
6 files changed
+131
-12
No files matched your search
@@ -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)
|
||||
|
||||
@@ -16,24 +16,68 @@ const ContentModerationActionImageSafety = "image_safety"
|
||||
//
|
||||
// 只认 400:上游安全拒绝(如 "Your request was rejected by the safety system")
|
||||
// 与 Responses 生图兜底合成的 content_policy_violation 都是 400;其余状态码
|
||||
// 描述的是账号/上游故障而不是用户内容。带 error.param 的 400 是参数校验错误
|
||||
// (例如 images 接口自身的 moderation 参数取值非法),即便文案含 moderation
|
||||
// 也不是内容拒绝,一律排除。
|
||||
// 描述的是账号/上游故障而不是用户内容。
|
||||
//
|
||||
// 判定顺序:
|
||||
// 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
|
||||
}
|
||||
code := strings.ToLower(strings.TrimSpace(err.Code))
|
||||
if code == "moderation_blocked" ||
|
||||
strings.Contains(code, "content_policy") ||
|
||||
strings.Contains(code, "policy_violation") ||
|
||||
strings.Contains(code, "safety_violation") {
|
||||
return true
|
||||
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
|
||||
}
|
||||
}
|
||||
return isOpenAIImagesContentPolicyRefusal(err.Message)
|
||||
for _, marker := range imageSafetyRefusalMarkers {
|
||||
if strings.Contains(lower, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ImageSafetyRecordInput 是一次图像上游安全拒绝的风控记录入参。
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestIsOpenAIImagesSafetyRefusal(t *testing.T) {
|
||||
@@ -56,6 +57,46 @@ func TestIsOpenAIImagesSafetyRefusal(t *testing.T) {
|
||||
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."),
|
||||
|
||||
@@ -2241,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