jackson vor 1 Woche
Ursprung
Commit
0001921b61

+ 153 - 0
tests/test_goods_ai_pre_audit_tools.py

@@ -68,12 +68,25 @@ def page_values():
     return values
 
 
+def certification_files():
+    return {
+        'battery_file': [
+            {'name': 'battery-second.pdf', 'url': 'https://example.test/battery-2.pdf?key=a%2Bb&download=1'},
+            {'name': '电池报告.pdf', 'url': 'http://example.test:8080/battery-1.pdf'},
+        ],
+        'fda_file': [{'name': '', 'url': 'HTTPS://example.test/fda%20report.pdf'}],
+        'toy_file': [],
+        'other_file': [{'name': 'other.pdf', 'url': 'https://example.test/other.pdf#page=2'}],
+    }
+
+
 def read_data():
     return {
         'goods_id': 17, 'claim_ref': 'Ab' * 32, 'source_ref': 'Cd' * 32,
         'context': {
             'country_code': 'US', 'departure_country': 'CN',
             'selected_labels': {'shipping_method': 'sea', 'category_ids': ['A', 'B']},
+            'certification_files': certification_files(),
         },
         'page_values': page_values(),
     }
@@ -280,6 +293,142 @@ class GoodsAiPreAuditToolsTest(unittest.TestCase):
                     'query_goods_ai_pre_audit', envelope(data),
                 )['is_error'])
 
+    def test_read_certification_files_preserve_names_urls_groups_and_order(self):
+        data = read_data()
+        original = deepcopy(data)
+        result = OutputPresenter().present('query_goods_ai_pre_audit', envelope(data))
+        self.assertFalse(result['is_error'])
+        self.assertEqual(original, result['structured_content'])
+        self.assertEqual(original, json.loads(result['text']))
+        self.assertEqual(original, data)
+        self.assertEqual({'request_id': 'rq_pre_audit'}, result['meta'])
+
+    def test_legacy_read_without_certification_files_does_not_invent_empty_groups(self):
+        data = read_data()
+        del data['context']['certification_files']
+        result = OutputPresenter().present('query_goods_ai_pre_audit', envelope(data))
+        self.assertFalse(result['is_error'])
+        self.assertEqual(data, result['structured_content'])
+        self.assertEqual(data, json.loads(result['text']))
+        self.assertNotIn('certification_files', result['structured_content']['context'])
+
+    def test_read_accepts_four_empty_certification_file_groups(self):
+        data = read_data()
+        data['context']['certification_files'] = {key: [] for key in certification_files()}
+        result = OutputPresenter().present('query_goods_ai_pre_audit', envelope(data))
+        self.assertFalse(result['is_error'])
+        self.assertEqual(data, result['structured_content'])
+        self.assertEqual(data, json.loads(result['text']))
+
+    def test_read_rejects_incomplete_extra_and_mistyped_certification_groups(self):
+        cases = [None, [], '', False, 0, {}]
+        cases.append(dict(certification_files(), internal_token='private-certification'))
+        for group in certification_files():
+            missing = certification_files()
+            del missing[group]
+            cases.append(missing)
+            for value in (None, {}, '', False, 0):
+                cases.append(dict(certification_files(), **{group: value}))
+        for files in cases:
+            with self.subTest(files=files):
+                data = read_data()
+                data['context']['certification_files'] = files
+                result = OutputPresenter().present('query_goods_ai_pre_audit', envelope(data))
+                self.assertTrue(result['is_error'])
+                self.assertNotIn('private-certification', json.dumps(result))
+
+    def test_read_rejects_malformed_certification_items_without_exposing_identity(self):
+        valid = {'name': 'private-certification.pdf', 'url': 'https://example.test/cert.pdf'}
+        cases = [None, [], '', 0, False, {}, {'name': valid['name']}, {'url': valid['url']}]
+        for key, value in (('name', None), ('name', 0), ('name', False),
+                           ('url', None), ('url', 0), ('url', False),
+                           ('company_id', 9), ('employee_id', 3),
+                           ('internal_token', 'private-certification')):
+            cases.append(dict(valid, **{key: value}))
+        for group in certification_files():
+            for item in cases:
+                with self.subTest(group=group, item=item):
+                    data = read_data()
+                    data['context']['certification_files'][group] = [valid, item]
+                    result = OutputPresenter().present('query_goods_ai_pre_audit', envelope(data))
+                    self.assertTrue(result['is_error'])
+                    self.assertNotIn('private-certification', json.dumps(result))
+
+    def test_read_certification_file_urls_reject_unsafe_or_malformed_values(self):
+        urls = (
+            '', ' ', 'javascript:alert(1)', 'data:application/pdf;base64,AA==',
+            'file:///private-certification.pdf', 'ftp://example.test/a.pdf',
+            '/cert.pdf', '//example.test/cert.pdf', 'https://', 'https:///cert.pdf',
+            'https://[invalid', 'https://example.test:not-a-port/a.pdf',
+            'https://example.test:0/a.pdf', 'https://example.test:65536/a.pdf',
+            'https://user@example.test/a.pdf', 'https://user:pass@example.test/a.pdf',
+            ' https://example.test/a.pdf', 'https://example.test/a.pdf ',
+            'https://example.test/a b.pdf', 'https://example.test/a\tb.pdf',
+            'https://example.test/a\nb.pdf', 'https://example.test/a\rb.pdf',
+            'https://example.test/a\x00b.pdf', 'https://example.test/a\x1fb.pdf',
+            'https://example.test/a\x7fb.pdf', 'https://example.test/a\u00a0b.pdf',
+            'https://example.test/a\u2003b.pdf', 'https://example.test/a\\b.pdf',
+        )
+        for url in urls:
+            with self.subTest(url=url):
+                data = read_data()
+                data['context']['certification_files']['other_file'] = [{'name': 'cert.pdf', 'url': url}]
+                self.assertTrue(OutputPresenter().present(
+                    'query_goods_ai_pre_audit', envelope(data),
+                )['is_error'])
+
+    def test_certification_files_are_rejected_outside_readonly_context(self):
+        for key in ('certification_files', *certification_files()):
+            value = certification_files() if key == 'certification_files' else certification_files()[key]
+            for location in ('top', 'page_values', 'selected_labels', 'context'):
+                if location == 'context' and key == 'certification_files':
+                    continue
+                with self.subTest(key=key, location=location):
+                    data = read_data()
+                    target = {'top': data, 'page_values': data['page_values'],
+                              'selected_labels': data['context']['selected_labels'],
+                              'context': data['context']}[location]
+                    target[key] = value
+                    self.assertTrue(OutputPresenter().present(
+                        'query_goods_ai_pre_audit', envelope(data),
+                    )['is_error'])
+        for name, data in (
+            ('claim_goods_ai_pre_audit', claimed()),
+            ('save_goods_ai_pre_audit_result', {'goods_id': 17, 'saved': True,
+                                             'ai_pre_audit_status': 2, 'saved_at': 1794196800}),
+        ):
+            for key in ('context', 'certification_files'):
+                with self.subTest(tool=name, key=key):
+                    self.assertTrue(OutputPresenter().present(
+                        name, envelope(dict(data, **{key: certification_files()})),
+                    )['is_error'])
+
+    def test_local_and_public_inputs_reject_certification_files_and_group_keys(self):
+        local_client, public_client = LocalClient(), PublicClient()
+        local = GatewayApp(api_client=local_client)
+        public = PublicGatewayApp(SessionStore(), public_client)
+        cases = []
+        for name, payload in (
+            ('claim_goods_ai_pre_audit', {}),
+            ('query_goods_ai_pre_audit', {'goods_id': 17, 'claim_ref': 'Ab' * 32}),
+            ('save_goods_ai_pre_audit_result', save_arguments()),
+        ):
+            for key in ('context', 'certification_files', *certification_files()):
+                value = certification_files().get(key, certification_files())
+                cases.append((name, dict(payload, **{key: value})))
+                if name == 'save_goods_ai_pre_audit_result':
+                    nested = deepcopy(payload)
+                    nested['fields'][key] = leaf(value)
+                    cases.append((name, nested))
+        for name, payload in cases:
+            with self.subTest(tool=name, payload=payload):
+                with self.assertRaises(ValueError):
+                    local.call_tool(name, payload)
+                with self.assertRaises(ValueError):
+                    public.call_tool('GWS_TEST', name, payload)
+        self.assertEqual([], local_client.calls)
+        self.assertEqual([], public_client.calls)
+
     def test_metadata_has_closed_top_and_nested_schemas(self):
         app = GatewayApp()
         expected = {
@@ -415,6 +564,8 @@ class GoodsAiPreAuditToolsTest(unittest.TestCase):
             result = response['result']
             self.assertFalse(result['isError'])
             self.assertEqual(result['structuredContent'], json.loads(result['content'][0]['text']))
+            if name == 'query_goods_ai_pre_audit':
+                self.assertEqual(read_data(), result['structuredContent'])
             self.assertIn('request_id', result['_meta'])
 
     def test_cli_forwards_claim_read_and_complete_result_json(self):
@@ -470,6 +621,8 @@ class GoodsAiPreAuditToolsTest(unittest.TestCase):
             result = response['result']
             self.assertFalse(result['isError'])
             self.assertEqual(result['structuredContent'], json.loads(result['content'][0]['text']))
+            if name == 'query_goods_ai_pre_audit':
+                self.assertEqual(read_data(), result['structuredContent'])
             self.assertTrue(result['_meta']['request_id'].startswith('rq_http_'))
         invalid = handler.handle_json_rpc(
             headers={'X-Gateway-Session': 'GWS_TEST'},

+ 10 - 0
tools/goods_ai_pre_audit_common.py

@@ -82,9 +82,19 @@ PAGE_VALUE_SCHEMAS.update({
     for key in CLEARANCE_FIELDS
 })
 PAGE_VALUES_SCHEMA = dict(closed_object(PAGE_VALUE_SCHEMAS), minProperties=1)
+CERTIFICATION_FILE_GROUPS = ('battery_file', 'fda_file', 'toy_file', 'other_file')
+CERTIFICATION_FILE_SCHEMA = closed_object({
+    'name': {'type': 'string'},
+    'url': {'type': 'string', 'format': 'uri', 'pattern': r'[^\s\\\x00-\x1f\x7f]+'},
+}, ('name', 'url'))
+CERTIFICATION_FILES_SCHEMA = closed_object({
+    group: {'type': 'array', 'items': CERTIFICATION_FILE_SCHEMA}
+    for group in CERTIFICATION_FILE_GROUPS
+}, CERTIFICATION_FILE_GROUPS)
 CONTEXT_SCHEMA = closed_object({
     'country_code': {'type': 'string'},
     'departure_country': {'type': 'string'},
+    'certification_files': CERTIFICATION_FILES_SCHEMA,
     'selected_labels': closed_object({
         key: {'anyOf': [
             {'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}},

+ 4 - 1
tools/query_goods_ai_pre_audit.py

@@ -9,7 +9,10 @@ class QueryGoodsAiPreAuditTool(GoodsAiPreAuditTool):
     input_schema = QUERY_INPUT_SCHEMA
     description = (
         '使用场景:Agent 成功领取商品后,按 goods_id 与 claim_ref 读取审核通过模式的 page_values '
-        '和只读 context。'
+        '和只读 context;AI 同时读取其中 certification_files 的认证文件。'
+        'certification_files 为 battery_file/fda_file/toy_file/other_file 四组 name/url 数组,'
+        '空数组表示无文件;历史响应缺少该键表示本次未提供,不能当作无文件。'
+        '认证文件仅作上下文,不加入 page_values 或保存 fields。'
         '保存时使用 save_goods_ai_pre_audit_result,原样带回 claim_ref 和 source_ref'
         ';逐字段回显 page_values 的原值及完整清关行。禁止使用:未领取就读取、猜测资料版本、执行正式审核或改写身份。'
         '响应机器键、编码、空值和数组顺序必须完整保留,不翻译或省略。'

+ 2 - 1
tools/save_goods_ai_pre_audit_result.py

@@ -13,6 +13,7 @@ class SaveGoodsAiPreAuditResultTool(GoodsAiPreAuditTool):
         'alue/reason。'
         'ys_clearance_data/yf_clearance_data 按原顺序逐行返回叶子,adjust_hscode_dat'
         'a 是一个数组值叶子;属性平铺,不使用 goods_attr。无建议为 null;0、false、空字符串和空数组按实际值保留。'
-        'claim_ref/source_ref 原样带回。'
+        'claim_ref/source_ref 原样带回;认证文件变化后须重新读取当前资料并预审。'
+        'context.certification_files 及四组附件键仅供读取,不得加入保存入参或 fields。'
         '禁止使用:省略可见字段、伪造原值、保存过期领取或旧资料、提交正式人工审核、改写业务状态或身份。机器键和值不得翻译或省略。'
     )