From 31591e663e98c23b5ba506c4f6a0b713e283c53b Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 23 Sep 2026 00:44:56 +0800 Subject: [PATCH] =?UTF-8?q?feat(integration-connector):=20=E7=BB=91?= =?UTF-8?q?=E5=AE=9A=E5=8F=82=E6=95=B0=E6=98=A0=E5=B0=84=E4=B8=8E=E5=87=AD?= =?UTF-8?q?=E6=8D=AE=20DB=20=E5=8A=A0=E5=AF=86=E8=90=BD=E5=BA=93=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 绑定新增 param_mapping_json:域参数→接口参数声明式映射(map_response 规范),空对象同名直通 - 凭据引用新增 db 维护模式:secret_ciphertext Fernet 加密落库,主密钥 INTEGRATION_CREDENTIAL_KEY 仅环境注入,与 env 引用模式并存 - 新增 credential_types 凭据形态注册表:代码注册各类型字段清单,UI 动态渲染与 API 组装校验的唯一事实来源 - 移除绑定 context_source_code 独立列,路由条件统一 context_selector_json - 管理端表单 Modal 重构为 Drawer,新增 JSON 编辑字段组件与页面级测试 - 迁移 rd1/re1 重挂当前唯一 head dd22ee33ff44,维持单 head 链 - settings 移除 IN_TRANSIT_TRANSFER_ERP_* 配置,外部端点/凭据移交连接器客户端实例管理 --- backend/app/api/integration_connector.py | 436 +++++++++++--- backend/app/core/config/settings.py | 17 +- backend/app/models/integration_connector.py | 13 +- .../services/integration_connector/binding.py | 46 +- .../integration_connector/capability.py | 74 +-- .../integration_connector/credential_types.py | 79 +++ .../services/integration_connector/engine.py | 47 +- .../services/integration_connector/mapping.py | 177 +++++- .../integration_connector/security.py | 50 +- .../integration_connector/transports/base.py | 41 +- .../integration_connector/transports/rest.py | 28 +- .../integration_connector/transports/soap.py | 210 ++++++- ...nector_param_mapping_and_db_credentials.py | 45 ++ ...integration_binding_context_source_code.py | 31 + .../api/test_integration_connector_api.py | 381 +++++++++++- .../integration_connector/test_binding.py | 41 ++ .../integration_connector/test_capability.py | 12 - .../test_credential_types.py | 51 ++ .../integration_connector/test_engine.py | 130 +++- .../integration_connector/test_mapping.py | 244 ++++++++ .../integration_connector/test_migration.py | 28 + .../integration_connector/test_security.py | 56 ++ .../integration_connector/test_transports.py | 289 ++++++++- .../integration-connector-framework-design.md | 20 +- .../IntegrationConnectorPage.spec.ts | 136 +++++ .../IntegrationConnectorPage.vue | 383 ++++++++++-- .../api/integration-connector.api.ts | 18 + .../IntegrationConnectorFormDrawer.spec.ts | 410 +++++++++++++ .../IntegrationConnectorFormDrawer.vue | 565 ++++++++++++++++++ .../IntegrationConnectorFormModal.spec.ts | 96 --- .../IntegrationConnectorFormModal.vue | 277 --------- .../components/JsonTextareaField.vue | 82 +++ .../useIntegrationConnectorAdmin.spec.ts | 252 +++++++- .../useIntegrationConnectorAdmin.ts | 193 +++++- .../types/integration-connector.types.ts | 137 ++++- 35 files changed, 4345 insertions(+), 750 deletions(-) create mode 100644 backend/app/services/integration_connector/credential_types.py create mode 100644 backend/migrations/versions/rd1e2f3a4b5c_integration_connector_param_mapping_and_db_credentials.py create mode 100644 backend/migrations/versions/re1f3a4b5c6d_drop_integration_binding_context_source_code.py create mode 100644 backend/tests/services/integration_connector/test_credential_types.py create mode 100644 frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts create mode 100644 frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts create mode 100644 frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue delete mode 100644 frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.spec.ts delete mode 100644 frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.vue create mode 100644 frontend/src/features/admin/modules/integration-connector/components/JsonTextareaField.vue diff --git a/backend/app/api/integration_connector.py b/backend/app/api/integration_connector.py index c41b7773..7597db6c 100644 --- a/backend/app/api/integration_connector.py +++ b/backend/app/api/integration_connector.py @@ -1,21 +1,30 @@ """api/integration_connector.py 用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。 -依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。 +依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。 逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key}, 拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。 + 接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的 + 状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS + 转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端 + 与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。 + 凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回 + active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。 + 凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。 注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有 /api/integration Dify 文件代理)。 """ from __future__ import annotations +import json import uuid from flask import Blueprint, request +from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret from app.core.decorators import require_admin -from app.core.errors import NotFoundError, ValidationError +from app.core.errors import AppError, NotFoundError, ValidationError from app.core.response import ok from app.models import ( IntegrationBinding, @@ -23,14 +32,36 @@ from app.models import ( IntegrationCredentialReference, IntegrationInterfaceDefinition, ) -from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities +from app.services.integration_connector.capability import list_capabilities +from app.services.integration_connector.credential_types import ( + build_secret_dict, + get_credential_type, + list_credential_types, + visible_fields, +) from app.services.integration_connector.gateway import get_capability_gateway -from app.services.integration_connector.transports.base import IntegrationCallResult +from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES +from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config integration_connector_bp = Blueprint('integration_connector', __name__) VALID_CONNECTOR_TYPES = ('rest', 'soap') VALID_STATUSES = ('draft', 'published', 'retired') +VALID_SECRET_PROVIDERS = ('db', 'env') +# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」 +# 现语义等于断供且真实版本化轮换未实现(属 P2),故 PUT 只允许在 active/retired 间切换, +# rotating 不再可进入;存量 rotating 数据保留只读展示,经 PUT 置 active 即恢复。 +VALID_CREDENTIAL_UI_STATUSES = ('active', 'retired') + +# 配置实体生命周期转移表(接口定义与绑定共用):动作 → (源状态, 目标状态)。状态不再 +# 由 PUT 直接改写,只能经动作端点按此表转移(draft→published 发布;published→draft 撤回; +# published→retired 退役;retired→draft 恢复为草稿,作为无版本化阶段的保险阀)。 +CONFIG_STATUS_TRANSITIONS = { + 'publish': ('draft', 'published'), + 'unpublish': ('published', 'draft'), + 'retire': ('published', 'retired'), + 'reopen': ('retired', 'draft'), +} def _require(value, field: str) -> None: @@ -39,6 +70,70 @@ def _require(value, field: str) -> None: raise ValidationError(f'{field} is required', details={'field': field}) +def _require_client(code: str) -> IntegrationClientInstance: + """按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。""" + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise ValidationError( + 'client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND', + details={'client_instance_code': code}, + ) + return client + + +def _apply_status_transition(entity, action: str, *, kind: str) -> None: + """按转移表校验并落库状态;非法动作或源状态不符即 400。""" + transition = CONFIG_STATUS_TRANSITIONS.get(action) + if transition is None: + raise ValidationError( + 'unknown lifecycle action', details={'allowed': sorted(CONFIG_STATUS_TRANSITIONS)}) + src, dst = transition + if entity.status != src: + raise ValidationError( + f'{kind} status is {entity.status}, cannot {action}', + code='INTEGRATION.ILLEGAL_STATUS_TRANSITION', + details={'action': action, 'from': entity.status, 'to': dst}, + ) + entity.status = dst + + +def _require_interface(code: str) -> IntegrationInterfaceDefinition: + """按编码取接口定义;不存在即 400(绑定成对校验以其所属客户端为准,而非依赖外键报 500)。""" + iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first() + if iface is None: + raise ValidationError( + 'interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND', + details={'interface_definition_code': code}, + ) + return iface + + +def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClientInstance, IntegrationInterfaceDefinition]: + """绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。 + + 错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接 + 400(fail-fast),不留给调用期 fail-closed。 + """ + client = _require_client(str(client_code).strip()) + iface = _require_interface(str(interface_code).strip()) + if iface.client_instance_code != client.code: + raise ValidationError( + 'interface definition does not belong to the selected client instance', + code='INTEGRATION.BINDING_PAIR_MISMATCH', + details={ + 'client_instance_code': client.code, + 'interface_definition_code': iface.code, + 'interface_client_instance_code': iface.client_instance_code, + }, + ) + return client, iface + + +def _interface_transition(iface, action: str) -> None: + """按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。""" + _apply_status_transition(iface, action, kind='interface') + + def _serialize_client(client) -> dict: return { 'id': client.id, 'code': client.code, 'name': client.name, @@ -64,7 +159,7 @@ def _serialize_binding(binding) -> dict: return { 'id': binding.id, 'capability': binding.capability, 'context_selector_json': binding.context_selector_json or {}, - 'context_source_code': binding.context_source_code, + 'param_mapping_json': binding.param_mapping_json or {}, 'client_instance_code': binding.client_instance_code, 'interface_definition_code': binding.interface_definition_code, 'mapping_version': binding.mapping_version, 'priority': binding.priority, @@ -73,15 +168,59 @@ def _serialize_binding(binding) -> dict: } +def _decrypted_secret(cred) -> dict: + """db 模式下解密凭据字典;密文缺失或主密钥异常时返回空 dict(fail-closed 不炸列表)。""" + if cred.secret_provider != 'db' or not cred.secret_ciphertext: + return {} + try: + raw = decrypt_secret( + cred.secret_ciphertext, + key_config_name=CREDENTIAL_KEY_CONFIG_NAME, + codes=_DB_SECRET_CODES, + ) + parsed = json.loads(raw) + return parsed if isinstance(parsed, dict) else {} + except AppError: + return {} + + def _serialize_credential(cred) -> dict: + secret_dict = _decrypted_secret(cred) return { 'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref, 'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type, + # 非密字段按类型定义回显(如 username);密文字段与密文本身永不回显。 + 'secret_fields': visible_fields(cred.credential_type, secret_dict), + 'has_secret': bool(cred.secret_ciphertext), 'version': cred.version, 'status': cred.status, + 'updated_at': cred.updated_at.isoformat() if cred.updated_at else None, 'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None, } +def _apply_db_secret(cred, body) -> None: + """db 模式:按凭据类型定义组装字段并加密落库;只改部分字段可沿用解密出的旧值。 + + 类型必须在凭据类型注册表内(fail-closed);合并旧值后必填字段仍缺失即拒绝。 + """ + ctype = str(body.get('credential_type') or cred.credential_type or 'password').strip() + if get_credential_type(ctype) is None: + raise ValidationError('unknown credential_type', details={'credential_type': ctype}) + cred.credential_type = ctype + current = _decrypted_secret(cred) if cred.secret_ciphertext else {} + values: dict = dict(current) + for key in (field['key'] for field in get_credential_type(ctype)['fields']): + incoming = body.get(key) + if incoming is not None and str(incoming) != '': + values[key] = str(incoming) + merged = build_secret_dict(ctype, values) + cred.secret_ciphertext = encrypt_secret( + json.dumps(merged, ensure_ascii=False), + key_config_name=CREDENTIAL_KEY_CONFIG_NAME, + codes=_DB_SECRET_CODES, + ) + + def _result_to_dict(result: IntegrationCallResult) -> dict: return { 'status': result.status, @@ -98,7 +237,6 @@ def _result_to_dict(result: IntegrationCallResult) -> dict: @integration_connector_bp.route('/capabilities', methods=['GET']) @require_admin def list_capabilities_endpoint(): - ensure_capabilities_loaded() data = [{ 'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency, 'input_schema': spec.input_schema, 'output_schema': spec.output_schema, @@ -231,15 +369,15 @@ def create_interface_definition(): code = str(body.get('code') or '').strip() _require(code, 'code') _require(body.get('client_instance_code'), 'client_instance_code') - connector_type = str(body.get('connector_type') or '') - if connector_type not in VALID_CONNECTOR_TYPES: - raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) + # 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值, + # 杜绝接口与客户端类型不一致);客户端不存在即 400,而非依赖外键报 500。 + client = _require_client(str(body['client_instance_code']).strip()) status = str(body.get('status') or 'draft') if status not in VALID_STATUSES: raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) iface = IntegrationInterfaceDefinition( code=code, name=str(body.get('name') or code).strip(), - client_instance_code=body['client_instance_code'], connector_type=connector_type, + client_instance_code=client.code, connector_type=client.connector_type, http_method=(str(body.get('http_method') or '').strip().upper() or None), request_path=(str(body.get('request_path') or '').strip() or None), request_spec_json=body.get('request_spec_json') or {}, @@ -247,7 +385,9 @@ def create_interface_definition(): response_mapping_json=body.get('response_mapping_json') or {}, output_schema_json=body.get('output_schema_json') or {}, version=int(body.get('version') or 1), status=status, - enabled=bool(body.get('enabled', True)), + # enabled 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略; + # 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。 + enabled=True, ) from app import db db.session.add(iface) @@ -258,7 +398,11 @@ def create_interface_definition(): @integration_connector_bp.route('/interface-definitions/', methods=['PUT']) @require_admin def update_interface_definition(code): - """更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。""" + """更新接口定义(code 不变;可改模板/入参/回传/出参 Schema 与所属客户端)。 + + 状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转); + 连接器类型由所属客户端实例服务端推导,请求体传值被忽略。 + """ iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first() if iface is None: raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND') @@ -268,12 +412,9 @@ def update_interface_definition(code): iface.name = str(body['name']).strip() if body.get('client_instance_code') is not None: _require(body.get('client_instance_code'), 'client_instance_code') - iface.client_instance_code = body['client_instance_code'] - if body.get('connector_type') is not None: - connector_type = str(body['connector_type']) - if connector_type not in VALID_CONNECTOR_TYPES: - raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) - iface.connector_type = connector_type + client = _require_client(str(body['client_instance_code']).strip()) + iface.client_instance_code = client.code + iface.connector_type = client.connector_type if 'http_method' in body: iface.http_method = str(body.get('http_method') or '').strip().upper() or None if 'request_path' in body: @@ -283,18 +424,52 @@ def update_interface_definition(code): setattr(iface, json_field, body.get(json_field) or {}) if body.get('version') is not None: iface.version = int(body.get('version') or 1) - if body.get('status') is not None: - status = str(body['status']) - if status not in VALID_STATUSES: - raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) - iface.status = status - if 'enabled' in body: - iface.enabled = bool(body.get('enabled', True)) from app import db db.session.commit() return ok(_serialize_interface(iface)) +# ---- 接口定义生命周期(状态只经动作端点按转移表流转) ---- + +def _do_interface_lifecycle(code: str, action: str): + """动作端点共用体:取接口 → 按转移表转移 → 落库并回显。""" + iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first() + if iface is None: + raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND') + _interface_transition(iface, action) + from app import db + db.session.commit() + return ok(_serialize_interface(iface)) + + +@integration_connector_bp.route('/interface-definitions//publish', methods=['POST']) +@require_admin +def publish_interface_definition(code): + """发布接口定义(draft → published):发布后才会被绑定解析选中。""" + return _do_interface_lifecycle(code, 'publish') + + +@integration_connector_bp.route('/interface-definitions//unpublish', methods=['POST']) +@require_admin +def unpublish_interface_definition(code): + """撤回发布(published → draft):临时下线,修正后可重新发布。""" + return _do_interface_lifecycle(code, 'unpublish') + + +@integration_connector_bp.route('/interface-definitions//retire', methods=['POST']) +@require_admin +def retire_interface_definition(code): + """退役(published → retired):该接口引用的所有绑定同时失效。""" + return _do_interface_lifecycle(code, 'retire') + + +@integration_connector_bp.route('/interface-definitions//reopen', methods=['POST']) +@require_admin +def reopen_interface_definition(code): + """恢复为草稿(retired → draft):版本化发布上线前的保险阀,重新走发布流程。""" + return _do_interface_lifecycle(code, 'reopen') + + # ---- Binding ---- @integration_connector_bp.route('/bindings', methods=['GET']) @@ -307,23 +482,22 @@ def list_bindings(): @integration_connector_bp.route('/bindings', methods=['POST']) @require_admin def create_binding(): + """创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。""" body = request.get_json(silent=True) or {} _require(body.get('capability'), 'capability') _require(body.get('client_instance_code'), 'client_instance_code') _require(body.get('interface_definition_code'), 'interface_definition_code') - status = str(body.get('status') or 'draft') - if status not in VALID_STATUSES: - raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) + client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code']) binding = IntegrationBinding( capability=body['capability'], context_selector_json=body.get('context_selector_json') or {}, - context_source_code=(str(body.get('context_source_code') or '').strip() or None), - client_instance_code=body['client_instance_code'], - interface_definition_code=body['interface_definition_code'], + param_mapping_json=body.get('param_mapping_json') or {}, + client_instance_code=client.code, + interface_definition_code=iface.code, mapping_version=int(body.get('mapping_version') or 1), priority=int(body.get('priority') or 0), environment=str(body.get('environment') or 'prod').strip(), - status=status, + status='draft', ) from app import db db.session.add(binding) @@ -334,7 +508,11 @@ def create_binding(): @integration_connector_bp.route('/bindings/', methods=['PUT']) @require_admin def update_binding(binding_id): - """更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。""" + """更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。 + + 状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转); + 客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。 + """ from app import db binding = db.session.get(IntegrationBinding, binding_id) if binding is None: @@ -345,14 +523,23 @@ def update_binding(binding_id): binding.capability = body['capability'] if 'context_selector_json' in body: binding.context_selector_json = body.get('context_selector_json') or {} - if 'context_source_code' in body: - binding.context_source_code = str(body.get('context_source_code') or '').strip() or None - if body.get('client_instance_code') is not None: - _require(body.get('client_instance_code'), 'client_instance_code') - binding.client_instance_code = body['client_instance_code'] - if body.get('interface_definition_code') is not None: - _require(body.get('interface_definition_code'), 'interface_definition_code') - binding.interface_definition_code = body['interface_definition_code'] + if 'param_mapping_json' in body: + binding.param_mapping_json = body.get('param_mapping_json') or {} + new_client_code = body.get('client_instance_code') + new_iface_code = body.get('interface_definition_code') + if new_client_code is not None: + _require(new_client_code, 'client_instance_code') + if new_iface_code is not None: + _require(new_iface_code, 'interface_definition_code') + if new_client_code is not None or new_iface_code is not None: + _validate_binding_pair( + new_client_code if new_client_code is not None else binding.client_instance_code, + new_iface_code if new_iface_code is not None else binding.interface_definition_code, + ) + if new_client_code is not None: + binding.client_instance_code = str(new_client_code).strip() + if new_iface_code is not None: + binding.interface_definition_code = str(new_iface_code).strip() if body.get('mapping_version') is not None: binding.mapping_version = int(body.get('mapping_version') or 1) if body.get('priority') is not None: @@ -363,16 +550,69 @@ def update_binding(binding_id): binding.effective_from = body['effective_from'] or None if body.get('effective_to') is not None: binding.effective_to = body['effective_to'] or None - if body.get('status') is not None: - status = str(body['status']) - if status not in VALID_STATUSES: - raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) - binding.status = status from app import db db.session.commit() return ok(_serialize_binding(binding)) +# ---- 绑定生命周期(状态只经动作端点按转移表流转) ---- + +def _do_binding_lifecycle(binding_id: int, action: str): + """动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。 + + 发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用, + 否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定 + (与 binding.resolve_binding 的调用期门禁同一语义)。 + """ + from app import db + binding = db.session.get(IntegrationBinding, binding_id) + if binding is None: + raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND') + if action == 'publish': + client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first() + iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first() + if client is None or iface is None or iface.status != 'published' or not client.enabled: + raise ValidationError( + 'binding target not ready: interface must be published and client instance enabled', + code='INTEGRATION.BINDING_TARGET_NOT_READY', + details={ + 'client_instance_code': binding.client_instance_code, + 'interface_definition_code': binding.interface_definition_code, + }, + ) + _apply_status_transition(binding, action, kind='binding') + db.session.commit() + return ok(_serialize_binding(binding)) + + +@integration_connector_bp.route('/bindings//publish', methods=['POST']) +@require_admin +def publish_binding(binding_id): + """发布绑定(draft → published):发布后才会被绑定解析选中。""" + return _do_binding_lifecycle(binding_id, 'publish') + + +@integration_connector_bp.route('/bindings//unpublish', methods=['POST']) +@require_admin +def unpublish_binding(binding_id): + """撤回发布(published → draft):临时下线,修正后可重新发布。""" + return _do_binding_lifecycle(binding_id, 'unpublish') + + +@integration_connector_bp.route('/bindings//retire', methods=['POST']) +@require_admin +def retire_binding(binding_id): + """退役(published → retired):绑定退出自动调用。""" + return _do_binding_lifecycle(binding_id, 'retire') + + +@integration_connector_bp.route('/bindings//reopen', methods=['POST']) +@require_admin +def reopen_binding(binding_id): + """恢复为草稿(retired → draft):重新走发布流程。""" + return _do_binding_lifecycle(binding_id, 'reopen') + + # ---- 凭据引用 ---- @integration_connector_bp.route('/credential-references', methods=['GET']) @@ -385,41 +625,87 @@ def list_credential_references(): @integration_connector_bp.route('/credential-references', methods=['POST']) @require_admin def create_credential_reference(): + """创建凭据引用:db 模式(默认)按凭据类型加密字段落库;env 模式只存配置键名。""" body = request.get_json(silent=True) or {} _require(body.get('code'), 'code') - _require(body.get('secret_ref'), 'secret_ref') - from app import db + # 缺省保持 env(兼容既有直连 API 调用);管理端 db 模式显式传 secret_provider='db'。 + provider = str(body.get('secret_provider') or 'env').strip() + if provider not in VALID_SECRET_PROVIDERS: + raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)}) + code = str(body['code']).strip() + if IntegrationCredentialReference.query.filter_by(code=code).first(): + raise ValidationError('credential reference code already exists', code='RESOURCE.CONFLICT') + status = str(body.get('status') or 'active') + if status not in ('active', 'rotating', 'retired'): + raise ValidationError('invalid credential status', details={'allowed': ['active', 'rotating', 'retired']}) cred = IntegrationCredentialReference( - code=str(body['code']).strip(), - secret_ref=str(body['secret_ref']).strip(), - secret_provider=str(body.get('secret_provider') or 'env').strip(), + code=code, + secret_ref=str(body.get('secret_ref') or '').strip(), + secret_provider=provider, credential_type=str(body.get('credential_type') or 'password').strip(), version=int(body.get('version') or 1), - status=str(body.get('status') or 'active'), + status=status, ) + if provider == 'db': + _apply_db_secret(cred, body) + cred.secret_ref = f'db:{code}' + else: + _require(cred.secret_ref, 'secret_ref') + from app import db db.session.add(cred) db.session.commit() - # 永不回显真实凭据值;只回元数据。 + # 永不回显真实凭据值;只回元数据与非密字段。 return ok(_serialize_credential(cred), status=201) +@integration_connector_bp.route('/credential-references/types', methods=['GET']) +@require_admin +def list_credential_type_specs(): + """凭据类型注册表清单(类型 + 字段定义),供管理端动态渲染表单与占位符提示。""" + return ok(list_credential_types()) + + @integration_connector_bp.route('/credential-references/', methods=['PUT']) @require_admin def update_credential_reference(code): - """更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。""" + """更新凭据引用(code 不变);db 模式可只改部分字段(其余沿用旧值),永不回显明文。""" cred = IntegrationCredentialReference.query.filter_by(code=code).first() if cred is None: raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND') body = request.get_json(silent=True) or {} - if body.get('secret_ref') is not None: - _require(body.get('secret_ref'), 'secret_ref') - cred.secret_ref = str(body['secret_ref']).strip() if body.get('secret_provider') is not None: - cred.secret_provider = str(body['secret_provider']).strip() - if body.get('credential_type') is not None: - cred.credential_type = str(body['credential_type']).strip() + provider = str(body['secret_provider']).strip() + if provider not in VALID_SECRET_PROVIDERS: + raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)}) + cred.secret_provider = provider + if provider == 'env': + # 切回 env 模式时清掉遗留密文,避免失效凭据残留库中。 + cred.secret_ciphertext = None + field_keys = tuple( + field['key'] for field in (get_credential_type( + str(body.get('credential_type') or cred.credential_type or 'password')) or {'fields': []} + )['fields'] + ) + has_secret_input = any(body.get(key) is not None for key in field_keys) + if cred.secret_provider == 'db': + if has_secret_input or body.get('credential_type') is not None or not cred.secret_ciphertext: + _apply_db_secret(cred, body) + cred.secret_ref = f'db:{cred.code}' + else: + if body.get('secret_ref') is not None: + _require(body.get('secret_ref'), 'secret_ref') + cred.secret_ref = str(body['secret_ref']).strip() + if has_secret_input: + raise ValidationError('credential fields only apply to db credentials') if body.get('status') is not None: - cred.status = str(body['status']).strip() + # 状态改写冻结为两态开关:仅允许 active/retired(管理端行内开关即走此通道); + # rotating 不可进入——其现语义等于断供(resolve_credential 只解析 active), + # 真实版本化轮换属 P2;存量 rotating 数据经置 active 即恢复。 + status = str(body['status']).strip() + if status not in VALID_CREDENTIAL_UI_STATUSES: + raise ValidationError( + 'invalid credential status', details={'allowed': list(VALID_CREDENTIAL_UI_STATUSES)}) + cred.status = status from app import db db.session.commit() return ok(_serialize_credential(cred)) @@ -430,6 +716,11 @@ def update_credential_reference(code): @integration_connector_bp.route('/client-instances//test', methods=['POST']) @require_admin def test_connection(code): + """连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。 + + 配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列 + 拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。 + """ client = IntegrationClientInstance.query.filter_by(code=code).first() if client is None: raise NotFoundError('client instance not found') @@ -439,9 +730,20 @@ def test_connection(code): raise ValidationError( 'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN', ) - raw = transport.call( - client={'config_json': client.config_json or {}, 'credential': {}}, - interface={'request_spec_json': {}}, - request={}, - ) - return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw}) + client_payload = { + 'config_json': merge_client_config({ + 'config_json': client.config_json or {}, + 'endpoint': client.endpoint, + 'timeout_seconds': client.timeout_seconds, + }), + 'credential': {}, + } + probe = getattr(transport, 'probe', None) + if probe is not None: + raw = probe(client=client_payload) + ok_flag = bool(raw.get('ok')) + else: + # 测试替身等未实现 probe 的传输:回退 call(空 interface 规格)。 + raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={}) + ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown') + return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw}) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index b34875cc..1f0e835c 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -255,6 +255,8 @@ class Config: INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower() INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE') INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY') + # 集成连接器凭据密文的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。 + INTEGRATION_CREDENTIAL_KEY = os.getenv('INTEGRATION_CREDENTIAL_KEY') # HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP) HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE') @@ -282,27 +284,14 @@ class Config: SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower() SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2')) SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2')) - # 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。 + # 在途仓自动调拨(独立业务模块)参数;外部系统端点/凭据由集成连接器客户端实例管理。 IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2')) - IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2')) - IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1')) - IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int( - os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60' - ) - IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int( - os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60' - ) IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int( os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600' ) IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3') IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5') IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7') - # ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。 - IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip() - IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip() - IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip() - IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip() IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip() SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420') diff --git a/backend/app/models/integration_connector.py b/backend/app/models/integration_connector.py index 9f49fefc..843c675f 100644 --- a/backend/app/models/integration_connector.py +++ b/backend/app/models/integration_connector.py @@ -22,6 +22,7 @@ from sqlalchemy import ( Integer, JSON, String, + Text, UniqueConstraint, text, ) @@ -41,7 +42,7 @@ CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql') class IntegrationCredentialReference(Base): - """凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。""" + """凭据引用:真实凭据加密落库(db 模式)或引用环境注入键(env 模式),绝不落库明文。""" __tablename__ = 'integration_credential_references' __table_args__ = ( @@ -55,6 +56,9 @@ class IntegrationCredentialReference(Base): id: Mapped[int] = mapped_column(primary_key=True) code: Mapped[str] = mapped_column(String(64), nullable=False) secret_ref: Mapped[str] = mapped_column(String(128), nullable=False) + # db 模式:凭据 JSON(如 {"username","password"})的 Fernet 密文;主密钥由 + # INTEGRATION_CREDENTIAL_KEY 环境注入。env 模式为空。绝不回显、绝不写日志。 + secret_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True) secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env') credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password') version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) @@ -159,9 +163,12 @@ class IntegrationBinding(Base): id: Mapped[int] = mapped_column(primary_key=True) capability: Mapped[str] = mapped_column(String(128), nullable=False) + # 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。 context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict) - # 最常用的 context 匹配键独立列(JSON 保留作兜底)。 - context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + # 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}}); + # 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。 + # 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。 + param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict) client_instance_code: Mapped[str] = mapped_column( ForeignKey('integration_client_instances.code'), nullable=False, ) diff --git a/backend/app/services/integration_connector/binding.py b/backend/app/services/integration_connector/binding.py index 6bf2c80a..68f22a21 100644 --- a/backend/app/services/integration_connector/binding.py +++ b/backend/app/services/integration_connector/binding.py @@ -4,16 +4,21 @@ (客户端 + 接口 + 映射版本),并冻结调用期配置快照。 依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。 逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集; + 且接口定义须为 published、客户端实例须 enabled(管理端「发布/退役」「启停」的总开关); 同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。 """ from __future__ import annotations +import logging from dataclasses import dataclass from datetime import datetime, timezone from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition from app.services.integration_connector.errors import BindingNotFoundError +from app.services.integration_connector.transports.base import merge_client_config + +logger = logging.getLogger(__name__) @dataclass(frozen=True) @@ -32,6 +37,9 @@ class BindingSnapshot: request_spec: dict response_mapping: dict output_schema: dict + # 域参数→接口参数映射(空 = 同名直通)与接口入参 Schema(映射结果校验)。 + param_mapping: dict + input_schema: dict def _to_naive(dt: datetime | None) -> datetime | None: @@ -68,7 +76,8 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da Returns: BindingSnapshot。 Raises: - BindingNotFoundError: 无可用绑定(fail-closed)。 + BindingNotFoundError: 无可用绑定(fail-closed);接口未发布或客户端已停用同样按 + 无可用绑定处理(与列表「发布/退役」「启停」按钮语义闭环,且不向调用方泄露配置细节)。 """ base_now = now or datetime.utcnow() rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all() @@ -81,6 +90,12 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da continue candidates.append((row, selector)) if not candidates: + # fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」, + # 否则调用方只看到 no binding for capability(2026-09 排障实测痛点)。 + logger.warning( + "connector binding miss: capability=%s env=%s published_rows=%s context_keys=%s", + capability, environment, len(rows), sorted((context or {}).keys()), + ) raise BindingNotFoundError(capability=capability) candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True) row, selector = candidates[0] @@ -88,15 +103,28 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first() iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first() if client is None or iface is None: + logger.warning( + "connector binding target missing: capability=%s binding_id=%s client=%s iface=%s", + capability, row.id, row.client_instance_code, row.interface_definition_code, + ) + raise BindingNotFoundError(capability=capability) + # fail-closed 门禁:接口未发布(draft/retired)或客户端已停用视同无可用绑定—— + # 管理端「发布/退役」「启停」按钮因此具备真实的调用期语义;错误类型与无命中一致。 + if iface.status != 'published' or not client.enabled: + logger.warning( + "connector binding gated: capability=%s binding_id=%s iface_status=%s client_enabled=%s", + capability, row.id, iface.status, client.enabled, + ) raise BindingNotFoundError(capability=capability) - # 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。 + # 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费 + # (与 transports.base.merge_client_config 同一实现)。 # 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。 - config = dict(client.config_json or {}) - if client.endpoint is not None: - config['endpoint'] = client.endpoint - if client.timeout_seconds is not None: - config['timeout_seconds'] = client.timeout_seconds + config = merge_client_config({ + 'config_json': client.config_json, + 'endpoint': client.endpoint, + 'timeout_seconds': client.timeout_seconds, + }) request_spec = dict(iface.request_spec_json or {}) if iface.http_method is not None: @@ -105,8 +133,6 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da request_spec['path'] = iface.request_path selector = dict(row.context_selector_json or {}) - if row.context_source_code is not None and 'source_code' not in selector: - selector['source_code'] = row.context_source_code return BindingSnapshot( capability=row.capability, @@ -121,4 +147,6 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da request_spec=request_spec, response_mapping=iface.response_mapping_json or {}, output_schema=iface.output_schema_json or {}, + param_mapping=row.param_mapping_json or {}, + input_schema=iface.input_schema_json or {}, ) diff --git a/backend/app/services/integration_connector/capability.py b/backend/app/services/integration_connector/capability.py index 560ce700..62cac91c 100644 --- a/backend/app/services/integration_connector/capability.py +++ b/backend/app/services/integration_connector/capability.py @@ -2,7 +2,9 @@ 用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。 依赖:app.core.errors、errors.py;纯代码,不依赖 DB。 -逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。 +逻辑:能力必须由代码注册,不能由管理端动态定义;各域契约声明在各域包的 + capabilities 模块(如 in_transit_transfer/capabilities.py),由应用组合根 + import 完成注册;领域只调用已注册能力,未注册 fail-closed。 """ from __future__ import annotations @@ -12,37 +14,6 @@ from dataclasses import dataclass from app.core.errors import ValidationError from app.services.integration_connector.errors import CapabilityNotFoundError -# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。 -_QUERY_INPUT_SCHEMA: dict = { - "type": "object", - "required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"], - "properties": { - "invoice_no": {"type": "string"}, - "from_warehouse": {"type": "string"}, - "to_warehouse": {"type": "string"}, - "quantity": {"type": "number"}, - }, -} -_QUERY_OUTPUT_SCHEMA: dict = { - "type": "object", - "properties": { - "found": {"type": "boolean"}, - "quantity": {"type": ["number", "null"]}, - }, -} -_WRITE_OUTPUT_SCHEMA: dict = { - "type": "object", - "required": ["status"], - "properties": { - "status": { - "type": "string", - "enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"], - }, - "document_no": {"type": ["string", "null"]}, - "verified_posted": {"type": ["boolean", "null"]}, - }, -} - @dataclass(frozen=True) class CapabilitySpec: @@ -56,7 +27,6 @@ class CapabilitySpec: _CAPABILITIES: dict[str, CapabilitySpec] = {} -_LOADED = False def register_capability(spec: CapabilitySpec) -> CapabilitySpec: @@ -84,42 +54,6 @@ def list_capabilities() -> list[CapabilitySpec]: return sorted(_CAPABILITIES.values(), key=lambda s: s.name) -def ensure_capabilities_loaded() -> None: - """惰性注册内置能力(幂等);由网关/API 在解析前调用。""" - global _LOADED # noqa: PLW0603 - if _LOADED: - return - _LOADED = True - _register_transfer_capabilities() - - -def _register_transfer_capabilities() -> None: - """注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。""" - register_capability(CapabilitySpec( - name="in_transit_transfer.query_inventory", - input_schema=_QUERY_INPUT_SCHEMA, - output_schema=_QUERY_OUTPUT_SCHEMA, - idempotency="none", - write=False, - )) - register_capability(CapabilitySpec( - name="in_transit_transfer.create_transfer", - input_schema=_QUERY_INPUT_SCHEMA, - output_schema=_WRITE_OUTPUT_SCHEMA, - idempotency="invoice", - write=True, - )) - register_capability(CapabilitySpec( - name="in_transit_transfer.verify_duplicate", - input_schema=_QUERY_INPUT_SCHEMA, - output_schema=_WRITE_OUTPUT_SCHEMA, - idempotency="invoice", - write=False, - )) - - def reset_capability_registry_for_tests() -> None: - """单测隔离:清空注册表并重置加载标记。""" - global _LOADED # noqa: PLW0603 + """单测隔离:清空注册表(领域 capabilities 模块可重调其注册函数重建)。""" _CAPABILITIES.clear() - _LOADED = False diff --git a/backend/app/services/integration_connector/credential_types.py b/backend/app/services/integration_connector/credential_types.py new file mode 100644 index 00000000..e3f0483a --- /dev/null +++ b/backend/app/services/integration_connector/credential_types.py @@ -0,0 +1,79 @@ +"""services/integration_connector/credential_types.py + +用途:凭据形态注册表——每种凭据类型定义自己的字段清单(键名/是否密文/是否必填), + 是 UI 动态渲染与 API 组装/校验的唯一事实来源。 +依赖:app.core.errors;纯代码注册表,无 DB/IO。 +逻辑:类型由代码注册(与能力注册同哲学),管理端不可动态定义;字段键名即模板 + 占位符 credential_ 的 ;新增形态 = 加一个注册条目 + 前端标签,零迁移。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import ValidationError + +# 凭据形态注册表:key 为稳定类型编码(credential_type 列值),fields 为字段清单。 +# secret=True 的字段加密落库且永不回显;required 在「合并旧值后」仍缺失即拒绝。 +CREDENTIAL_TYPE_SPECS: dict[str, dict[str, Any]] = { + "password": { + "fields": [ + {"key": "username", "secret": False, "required": True}, + {"key": "password", "secret": True, "required": True}, + ], + }, + "token": { + "fields": [ + {"key": "token", "secret": True, "required": True}, + ], + }, + "api_key": { + "fields": [ + {"key": "api_key", "secret": True, "required": True}, + ], + }, +} + + +def get_credential_type(credential_type: str) -> dict[str, Any] | None: + """按类型编码查字段定义;未知类型返回 None(调用方 fail-closed)。""" + return CREDENTIAL_TYPE_SPECS.get(str(credential_type or "").strip()) + + +def list_credential_types() -> list[dict[str, Any]]: + """返回全部已注册类型及其字段定义(供 GET /credential-references/types)。""" + return [ + {"type": type_code, "fields": [dict(field) for field in spec["fields"]]} + for type_code, spec in sorted(CREDENTIAL_TYPE_SPECS.items()) + ] + + +def build_secret_dict(credential_type: str, values: dict) -> dict[str, str]: + """按类型定义从「合并旧值后的提交值」组装凭据字典。 + + 只保留类型定义内的键(未知键丢弃);必填字段缺失抛 ValidationError(fail-closed)。 + """ + spec = get_credential_type(credential_type) + if spec is None: + raise ValidationError("unknown credential_type", details={"credential_type": credential_type}) + result: dict[str, str] = {} + for field in spec["fields"]: + value = values.get(field["key"]) + if value is not None and str(value) != "": + result[field["key"]] = str(value) + missing = [field["key"] for field in spec["fields"] if field["required"] and not result.get(field["key"])] + if missing: + raise ValidationError("required credential fields missing", details={"fields": missing}) + return result + + +def visible_fields(credential_type: str, secret_dict: dict) -> dict[str, str]: + """按类型定义回显非密字段(secret=True 的字段永不回显)。""" + spec = get_credential_type(credential_type) + if spec is None: + return {} + return { + field["key"]: str(secret_dict[field["key"]]) + for field in spec["fields"] + if not field["secret"] and secret_dict.get(field["key"]) + } diff --git a/backend/app/services/integration_connector/engine.py b/backend/app/services/integration_connector/engine.py index 0701f370..a0efaca2 100644 --- a/backend/app/services/integration_connector/engine.py +++ b/backend/app/services/integration_connector/engine.py @@ -1,26 +1,36 @@ """services/integration_connector/engine.py -用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。 +用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→map-params→call→classify→audit。 依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 -逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout; +逻辑:域入参先经能力 Schema 校验,再按绑定 param_mapping 翻译为接口参数(对照接口 + 入参 Schema 校验);凭据按引用解析后以 credential_* 注入传输层;读能力返回 + 带 status 的失败 dict 时原样分类,其余映射校验通过即 success; 入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。 """ from __future__ import annotations +import logging import time import uuid from dataclasses import replace from app import db from app.services.integration_connector.binding import BindingSnapshot, resolve_binding -from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability +from app.services.integration_connector.capability import CapabilitySpec, get_capability from app.services.integration_connector.errors import CallFailedError, InputInvalidError from app.services.integration_connector.mapping import map_response, schema_errors -from app.services.integration_connector.security import sanitize -from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response +from app.services.integration_connector.security import resolve_credential, sanitize +from app.services.integration_connector.transports.base import ( + RESULT_FAILURE_STATUSES, + IntegrationCallResult, + Transport, + classify_transport_response, +) from app.models import IntegrationCall +logger = logging.getLogger(__name__) + def build_request(request_spec: dict, config: dict, params: dict) -> dict: """按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。""" @@ -85,34 +95,51 @@ class CapabilityGateway: environment: str | None = None, transports: dict[str, Transport] | None = None, ) -> IntegrationCallResult: - ensure_capabilities_loaded() spec = get_capability(capability) input_errors = schema_errors(params, spec.input_schema) if input_errors: + # InputInvalidError 只带 message 不带明细,降级进 result_message 后只剩 + # "input invalid";不落日志则字段级原因(required missing/类型不符)永久丢失。 + logger.warning( + "connector input invalid: capability=%s errors=%s", + capability, input_errors, + ) raise InputInvalidError(details={'errors': input_errors}) env = environment or _environment() snapshot = resolve_binding(capability, context, env) + # 域参数 → 接口参数翻译:绑定配置了 param_mapping 时按映射引擎执行, + # 结果对照接口入参 Schema 校验;未配置时同名直通(能力入参原样下传)。 + params = map_response(snapshot.param_mapping, params, snapshot.input_schema) \ + if snapshot.param_mapping else params transport = (transports or self.transports).get(snapshot.connector_type) if transport is None: raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'}) + # 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。 + credential = resolve_credential(snapshot.credential_ref_code) if snapshot.credential_ref_code else {} request = build_request(snapshot.request_spec, snapshot.config, params) trace_id = f'ic-{uuid.uuid4().hex}' start_ms = int(time.time() * 1000) try: raw = transport.call( - client={'config_json': snapshot.config, 'credential': {}}, + client={'config_json': snapshot.config, 'credential': credential}, interface={'request_spec_json': snapshot.request_spec}, request=request, ) except TimeoutError: - result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id) + result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id) _record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id) return result - result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success') - if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'): + if spec.write: + result = classify_transport_response(raw) + elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES: + # 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML)→ 原样分类,不做输出映射。 + result = classify_transport_response(raw) + else: + result = IntegrationCallResult(status='success') + if result.status in ('success', 'duplicate_success', 'duplicate_unverified'): data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema) result = replace(result, data=data) result = replace(result, trace_id=trace_id) diff --git a/backend/app/services/integration_connector/mapping.py b/backend/app/services/integration_connector/mapping.py index 51973652..2736a28a 100644 --- a/backend/app/services/integration_connector/mapping.py +++ b/backend/app/services/integration_connector/mapping.py @@ -2,12 +2,14 @@ 用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。 依赖:decimal、errors.py;纯函数,无 IO/网络/DB。 -逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL; - 缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。 +逻辑:只允许点路径/数组下标提取与白名单转换函数(含 pick 键值取值、template 参数模板、 + each 列表逐元素子映射),禁止任意 Python/JS/SQL;缺字段且不可满足→MappingInvalidError; + 输出不合 Schema→MappingInvalidError(fail-closed)。 """ from __future__ import annotations +import string from decimal import Decimal from typing import Any @@ -50,25 +52,37 @@ def _tokenize(path: str) -> list[str]: def extract_path(obj: Any, path: str) -> Any: - """按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。""" + """按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。 + + 路径途经重复节点列表(名称段撞上列表)时逐元素收集剩余路径的命中: + 全部未命中视为 MISSING,部分命中收集为列表——同一配置在单/多记录 + (如多条件查询返回多个 RecordSet)之间不再随机失效。 + """ path = str(path or "") if len(path) > MAX_PATH_LENGTH: raise MappingInvalidError(details={"reason": "path_too_long"}) tokens = _tokenize(path) if len(tokens) > MAX_DEPTH: raise MappingInvalidError(details={"reason": "path_too_deep"}) - cur = obj - for tok in tokens: - if isinstance(cur, list) and tok.isdigit(): - idx = int(tok) - if idx >= len(cur): - return MISSING - cur = cur[idx] - elif isinstance(cur, dict) and tok in cur: - cur = cur[tok] - else: + return _walk(obj, tokens) + + +def _walk(cur: Any, tokens: list[str]) -> Any: + """按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。""" + if not tokens: + return cur + tok, rest = tokens[0], tokens[1:] + if isinstance(cur, list) and tok.isdigit(): + idx = int(tok) + if idx >= len(cur): return MISSING - return cur + return _walk(cur[idx], rest) + if isinstance(cur, dict) and tok in cur: + return _walk(cur[tok], rest) + if isinstance(cur, list): + collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING] + return collected if collected else MISSING + return MISSING # ---- 白名单转换函数(纯函数,无 IO/网络/eval) ---- @@ -119,6 +133,81 @@ def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any: return then if condition == "truthy" and bool(value) else else_ +def _pick(value: Any, key_field: str | None = None, key_value: Any = None, + value_field: str | None = None, exists: bool = False, cast: str | None = None) -> Any: + """从「键值对记录列表」按 key_field==key_value 取值(行转列通用需求)。 + + Args: + value: 目标列表(每项为 dict,如 XML 归一化后的 Field 列表)。 + key_field / key_value: 匹配键字段名与期望值(按字符串比较)。 + value_field: 命中后取的字段名;缺省返回整条记录。 + exists: True 时返回布尔(是否命中),不取值。 + cast: 可选 "decimal" 或 _cast 支持的标量类型。 + """ + if value is MISSING: + return MISSING + if key_field is None or key_value is None: + raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"}) + if not isinstance(value, list): + raise MappingInvalidError(details={"reason": "pick_target_not_list"}) + for item in value: + if isinstance(item, dict) and str(item.get(key_field)) == str(key_value): + if exists: + return True + found = item.get(value_field) if value_field is not None else item + if cast == "decimal": + return _decimal(found) + return _cast(found, cast) if cast else found + if exists: + return False + return MISSING + + +def _each(value: Any, fields: dict | None = None) -> Any: + """对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。 + + Args: + value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。 + fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致: + 元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。 + """ + if value is MISSING: + # 目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 归一为空列表: + # 空结果是合法答案(如库存查无此批号),交领域层归类为"未找到", + # 不得因输出 Schema 校验 fail-closed 成映射错误。 + return [] + # XML 重复节点归一化后单条记录是 dict、多条是 list:单记录归一为单元素列表, + # 否则同一配置在单/多记录间会随机 fail-closed。 + if isinstance(value, dict): + value = [value] + if not isinstance(value, list): + raise MappingInvalidError(details={"reason": "each_target_not_list"}) + out: list[Any] = [] + for item in value: + row: dict[str, Any] = {} + for field, spec in (fields or {}).items(): + if not isinstance(spec, dict): + raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"}) + if "default" in spec: + v: Any = spec["default"] + else: + expr = spec.get("expr") + v = extract_path(item, expr) if expr is not None else MISSING + transform = spec.get("transform") + if transform: + fn = TRANSFORMS.get(transform) + if fn is None: + raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"}) + v = fn(v, **(spec.get("args") or {})) + if v is not MISSING: + row[field] = v + if row: + # 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过, + # 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。 + out.append(row) + return out + + TRANSFORMS: dict[str, Any] = { "default": _default, "fallback": _fallback, @@ -127,9 +216,64 @@ TRANSFORMS: dict[str, Any] = { "enum-map": _enum_map, "list-map": _list_map, "if-else": _if_else, + "pick": _pick, + "each": _each, } +# ---- 参数模板填充(spec 级 "template",对整个参数表渲染,多用于域参数→接口参数翻译)---- + +def _render_template_value(value: Any, args: dict) -> str: + """渲染单个占位符值:列表按 list_item_template 逐项渲染后用 separator 连接。 + + 列表项为 dict 时,item_template 的占位符对 item 的键校验(缺失即 + template_item_field_missing,fail-closed)并按字段转义渲染, + 如 list_item_template = "(img01 = '{material_no}' AND img04 = '{lot_no}')"。 + """ + item_template = str(args.get("list_item_template") or "{item}") + separator = str(args.get("separator") if args.get("separator") is not None else ",") + escape = args.get("escape") + + def _escape(text: Any) -> str: + text = str(text) + if escape == "quote": + text = text.replace("'", "''") + return text + + if isinstance(value, (list, tuple)): + rendered: list[str] = [] + for item in value: + if isinstance(item, dict): + placeholders = {f for _, f, _, _ in string.Formatter().parse(item_template) if f} + missing = sorted(p for p in placeholders if p not in item) + if missing: + raise MappingInvalidError(details={"reason": "template_item_field_missing", "field": missing[0]}) + rendered.append(item_template.format(**{k: _escape(v) for k, v in item.items()})) + else: + rendered.append(item_template.format(item=_escape(item))) + return separator.join(rendered) + return _escape(value) + + +def fill_param_template(template: str, params: dict, args: dict | None = None) -> str: + """按 {param} 占位符对参数表渲染模板(str.format 语义,{{}} 转义字面大括号)。 + + 缺占位符即抛 MappingInvalidError(fail-closed),绝不静默输出空串。 + """ + template = str(template or "") + args = args or {} + placeholders = {fname for _, fname, _, _ in string.Formatter().parse(template) if fname} + rendered: dict[str, str] = {} + for name in placeholders: + if name not in (params or {}): + raise MappingInvalidError(details={"reason": "template_param_missing", "param": name}) + rendered[name] = _render_template_value(params[name], args) + try: + return template.format(**rendered) + except (KeyError, IndexError, ValueError) as exc: + raise MappingInvalidError(details={"reason": "template_invalid"}) from exc + + # ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)---- def _matches_type(value: Any, type_spec: Any) -> bool: @@ -190,7 +334,10 @@ def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict: for field, spec in mapping.items(): if not isinstance(spec, dict): raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"}) - if "default" in spec: + if "template" in spec: + # 参数模板:对整个 raw(参数表)渲染,与单字段 expr 提取互补。 + value = fill_param_template(spec["template"], raw, spec.get("args") or {}) + elif "default" in spec: value = spec["default"] else: expr = spec.get("expr") diff --git a/backend/app/services/integration_connector/security.py b/backend/app/services/integration_connector/security.py index 865bc948..7763cece 100644 --- a/backend/app/services/integration_connector/security.py +++ b/backend/app/services/integration_connector/security.py @@ -1,18 +1,32 @@ """services/integration_connector/security.py 用途:凭据引用解析(fail-closed)与敏感字段脱敏。 -依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。 -逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError; - sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。 +依赖:IntegrationCredentialReference 模型、core.credential_crypto、current_app.config、errors.py。 +逻辑:db 模式解密 secret_ciphertext(主密钥 INTEGRATION_CREDENTIAL_KEY 环境注入); + env 模式按 secret_ref 读当前环境配置,缺失即抛 CredentialUnresolvedError; + sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文/密文。 """ from __future__ import annotations +import json from typing import Any +from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret +from app.core.errors import AppError from app.models import IntegrationCredentialReference from app.services.integration_connector.errors import CredentialUnresolvedError +# 连接器凭据密文的 Fernet 主密钥配置键与错误码。 +CREDENTIAL_KEY_CONFIG_NAME = 'INTEGRATION_CREDENTIAL_KEY' +_DB_SECRET_CODES = CredentialCryptoErrorCodes( + key_missing='INTEGRATION.CREDENTIAL_KEY_MISSING', + key_invalid='INTEGRATION.CREDENTIAL_KEY_INVALID', + secret_empty='INTEGRATION.CREDENTIAL_SECRET_EMPTY', + secret_missing='INTEGRATION.CREDENTIAL_SECRET_MISSING', + secret_invalid='INTEGRATION.CREDENTIAL_SECRET_INVALID', +) + DEFAULT_SENSITIVE_KEYS = frozenset({ 'password', 'token', 'secret', 'authorization', 'cookie', 'access_key', 'secret_key', 'credential', 'api_key', 'apikey', 'credentials', @@ -20,10 +34,10 @@ DEFAULT_SENSITIVE_KEYS = frozenset({ def resolve_credential(credential_ref_code: str) -> dict[str, Any]: - """按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。 + """按凭据引用解析真实凭据(db 解密 / env 配置键),fail-closed。 Raises: - CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。 + CredentialUnresolvedError: 引用不存在、密文缺失、主密钥缺失/无效或 env 键缺失。 """ from flask import current_app @@ -32,13 +46,29 @@ def resolve_credential(credential_ref_code: str) -> dict[str, Any]: ).first() if cred is None: raise CredentialUnresolvedError(ref=credential_ref_code) + if cred.secret_provider == 'db': + if not cred.secret_ciphertext: + raise CredentialUnresolvedError(ref=credential_ref_code) + try: + value = decrypt_secret( + cred.secret_ciphertext, + key_config_name=CREDENTIAL_KEY_CONFIG_NAME, + codes=_DB_SECRET_CODES, + ) + except AppError as exc: + raise CredentialUnresolvedError(message=str(exc.message)) from exc + try: + parsed = json.loads(value) + except (ValueError, TypeError): + parsed = None + return dict(parsed) if isinstance(parsed, dict) else {'value': value} secret_ref = cred.secret_ref - value = current_app.config.get(secret_ref) if has_app_ctx() else None - if value is None or value == '': + config_value = current_app.config.get(secret_ref) if has_app_ctx() else None + if config_value is None or config_value == '': raise CredentialUnresolvedError(ref=secret_ref) - if isinstance(value, dict): - return dict(value) - return {'value': value} + if isinstance(config_value, dict): + return dict(config_value) + return {'value': config_value} def has_app_ctx() -> bool: diff --git a/backend/app/services/integration_connector/transports/base.py b/backend/app/services/integration_connector/transports/base.py index 17f6a680..6a552b4a 100644 --- a/backend/app/services/integration_connector/transports/base.py +++ b/backend/app/services/integration_connector/transports/base.py @@ -4,6 +4,7 @@ 依赖:typing.Protocol、dataclass;无 Flask/DB。 逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为 IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。 + probe 为可选实现的连接测试探针(只证明网络可达,不做业务调用)。 """ from __future__ import annotations @@ -18,6 +19,9 @@ RESULT_STATUSES = ( 'technical_failed', 'timeout', 'result_unknown', ) +# 传输层直接判失败的子集(读能力返回带这些 status 的原始 dict 时不再做输出映射)。 +RESULT_FAILURE_STATUSES = ('business_failed', 'technical_failed') + @dataclass(frozen=True) class IntegrationCallResult: @@ -32,13 +36,44 @@ class IntegrationCallResult: class Transport(Protocol): - """传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。""" + """传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。 + + probe 为可选实现的连接测试探针:只证明网络/服务可达,不要求接口契约; + Admin API 测试端点优先调 probe,未实现时回退 call(空 interface 规格)。 + """ connector_type: str def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: ... + def probe(self, *, client: dict) -> dict[str, Any]: + ... + + +def merge_client_config(client: dict) -> dict: + """把客户端实例独立列(endpoint/timeout_seconds)拼回 config_json 的兼容层。 + + 与 binding.resolve_binding 的列拼回逻辑同源(单一实现),供连接测试等 + 不经绑定解析、直接消费客户端实例的调用方复用;返回副本,不改入参。 + """ + config = dict(client.get('config_json') or {}) + if client.get('endpoint') is not None: + config['endpoint'] = client['endpoint'] + if client.get('timeout_seconds') is not None: + config['timeout_seconds'] = client['timeout_seconds'] + return config + + +def mask_secrets(text: str, credential: dict | None) -> str: + """把凭据值从自由文本(错误回显/响应摘要)中替换为 ***,防外泄进审计与日志。""" + result = str(text or '') + for value in (credential or {}).values(): + secret = str(value or '') + if secret: + result = result.replace(secret, '***') + return result + def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult: """按原始响应文本归一化结果分类(复用调拨六态分类语义)。 @@ -67,7 +102,7 @@ def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult: error_message=str(raw.get('message') or ''), ) if status == 'timeout': - return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN') + return IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN') if status == 'result_unknown': - return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no) + return IntegrationCallResult(status='result_unknown', error_code='EXTERNAL_RESULT_UNKNOWN', document_no=document_no) return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE') diff --git a/backend/app/services/integration_connector/transports/rest.py b/backend/app/services/integration_connector/transports/rest.py index 081ad309..a6ae2f9b 100644 --- a/backend/app/services/integration_connector/transports/rest.py +++ b/backend/app/services/integration_connector/transports/rest.py @@ -4,6 +4,7 @@ 依赖:requests(默认注入),可注入 http_request 供测试替身。 逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为 business_failed dict;非 JSON 响应映射为 technical_failed。 + probe 连接测试探针:GET endpoint,任意 HTTP 响应即算可达(连接异常才算不通)。 """ from __future__ import annotations @@ -13,6 +14,7 @@ from typing import Any, Callable import requests from app.services.integration_connector.errors import TransportNotFrozenError +from app.services.integration_connector.transports.base import mask_secrets HttpRequest = Callable[..., Any] @@ -50,7 +52,8 @@ class RestTransport: return { 'status': 'business_failed', 'code': f"HTTP_{int(response.status_code)}", - 'message': str(getattr(response, 'text', ''))[:500], + # 错误回显可能包含请求内容(含凭据),先脱敏再截断。 + 'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500], } try: return response.json() @@ -58,5 +61,26 @@ class RestTransport: return { 'status': 'technical_failed', 'code': 'NON_JSON', - 'message': str(getattr(response, 'text', ''))[:500], + 'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500], } + + def probe(self, *, client: dict) -> dict[str, Any]: + """连接测试探针:GET endpoint,任意 HTTP 响应(含 4xx/5xx)都证明网络可达。 + + 与 call 的区别:不要求接口契约(method/path),不做业务语义解析; + 连接建立失败(DNS/超时/拒绝)才算不通。异常回显先脱敏再截断。 + """ + config = client.get('config_json') or {} + endpoint = str(config.get('endpoint') or '').strip() + if not endpoint: + raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)') + timeout = int(config.get('timeout_seconds') or 60) + try: + response = self._http_request('GET', endpoint, timeout=timeout) + except Exception as exc: + return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))} + return { + 'ok': True, + 'code': f"HTTP_{int(getattr(response, 'status_code', 0))}", + 'message': mask_secrets(str(getattr(response, 'text', ''))[:200], client.get('credential'))[:200], + } diff --git a/backend/app/services/integration_connector/transports/soap.py b/backend/app/services/integration_connector/transports/soap.py index f945ff7f..12e3bb00 100644 --- a/backend/app/services/integration_connector/transports/soap.py +++ b/backend/app/services/integration_connector/transports/soap.py @@ -1,29 +1,215 @@ """services/integration_connector/transports/soap.py -用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。 -依赖:zeep(延时导入);errors.py。 -逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。 +用途:SOAP Transport——按接口消息配置(soap.body_template)生成报文并解析 XML 响应。 +依赖:requests(默认注入)、xml.etree.ElementTree、errors.py。 +逻辑:endpoint 或 body_template 缺失 → fail-closed(TransportNotFrozenError); + 模板占位符从请求参数 + 凭据(credential_* 保留前缀)填充,缺参即失败; + 响应按 localname 解析(不绑命名空间前缀),Body 首子节点为业务根, + 叶节点文本本身是合法 XML 时递归展开(内嵌转义报文的通用规则); + 标准 SOAP 1.1 Fault(faultcode/faultstring)→ business_failed(SOAP 1.2 的 + Code/Reason 结构暂只归 business_failed 不提取消息);HTTP ≥400 → business_failed; + 非 XML → technical_failed。 + probe 连接测试探针:GET WSDL 地址并校验返回 XML(definitions/Envelope 任一即通); + 裸服务端点自动补 ?wsdl(SOAP 端点对裸 GET 常返回 404/405/501)。 """ from __future__ import annotations -from typing import Any +import string +import xml.etree.ElementTree as ET +from typing import Any, Callable -from app.services.integration_connector.errors import TransportNotFrozenError +import requests + +from app.services.integration_connector.errors import ( + InputInvalidError, + TransportNotFrozenError, +) +from app.services.integration_connector.transports.base import mask_secrets + +HttpRequest = Callable[..., Any] + +# 内嵌转义 XML 的最大递归展开深度(防深嵌套/构造报文拖垮解析)。 +MAX_EMBED_DEPTH = 3 + + +def _localname(tag: Any) -> str: + """去掉命名空间 URI,只取元素/属性的本地名(厂商前缀差异不影响映射路径)。""" + return tag.rsplit('}', 1)[-1] if isinstance(tag, str) else '' + + +def fill_soap_template(template: str, params: dict, credential: dict) -> str: + """填充 SOAP 报文模板:{param} 来自请求参数,{credential_*} 来自凭据注入。 + + Args: + template: 接口配置里的完整报文模板(str.format 语义,{{}} 为字面大括号)。 + params: 引擎映射后的接口参数。 + credential: resolve_credential 解析出的凭据字典,按 credential_ 前缀注入。 + Raises: + InputInvalidError: 占位符无对应值(fail-closed,绝不静默出空串)。 + """ + merged: dict[str, Any] = dict(params or {}) + # 凭据后注入并覆盖同名占位符:请求参数不得冒充/覆盖 credential_* 值。 + for key, value in (credential or {}).items(): + merged[f'credential_{key}'] = value + missing = sorted({ + field for _, field, _, _ in string.Formatter().parse(template) + if field and field not in merged + }) + if missing: + raise InputInvalidError(details={'reason': 'soap_template_param_missing', 'params': missing}) + for key, value in merged.items(): + # CDATA 内出现 ]]> 会截断报文;模板骨架自身的 CDATA 结束符不受影响,仅查替换值。 + if ']]>' in str(value): + raise InputInvalidError(details={'reason': 'soap_cdata_terminator_in_params', 'param': key}) + try: + return template.format(**merged) + except (KeyError, IndexError, ValueError) as exc: + # 覆盖裸 {} / 格式规格非法等 str.format 原生异常,统一 fail-closed 语义。 + raise InputInvalidError(details={'reason': 'soap_template_invalid'}) from exc + + +def _element_to_value(elem: ET.Element, embed_depth: int) -> Any: + """把元素转为通用 dict:属性 → @key;重复同名子元素 → list;叶子文本为值。 + + 叶子文本本身是合法 XML(网关型系统常见的转义内嵌报文)时递归解析并保留内层根标签。 + """ + attrs = {f'@{_localname(key)}': value for key, value in elem.attrib.items()} + children = list(elem) + text = (elem.text or '').strip() + if children: + node: dict[str, Any] = dict(attrs) + grouped: dict[str, list[Any]] = {} + for child in children: + name = _localname(child.tag) + grouped.setdefault(name, []).append(_element_to_value(child, embed_depth)) + for name, items in grouped.items(): + node[name] = items[0] if len(items) == 1 else items + if text: + node['#text'] = text + return node + if text.startswith('<') and embed_depth > 0: + try: + inner = ET.fromstring(text) + except ET.ParseError: + inner = None + if inner is not None: + return {_localname(inner.tag): _element_to_value(inner, embed_depth - 1)} + if not attrs: + return text or None + if text: + return {**attrs, '#text': text} + return attrs + + +def _parse_soap_payload(text: str) -> dict[str, Any]: + """解析 SOAP 信封:取 Body 首子元素为业务根并转 dict;检测标准 Fault。""" + root = ET.fromstring(text) + body = None + for node in root.iter(): + if _localname(node.tag) == 'Body': + body = node + break + payload = list(body)[0] if body is not None and len(body) else root + for node in payload.iter(): + if _localname(node.tag) == 'Fault': + code = message = '' + for child in node.iter(): + name = _localname(child.tag) + if name == 'faultcode' and not code: + code = (child.text or '').strip() + if name == 'faultstring' and not message: + message = (child.text or '').strip() + return { + 'status': 'business_failed', + 'code': code or 'SOAP_FAULT', + 'message': message, + } + return {_localname(payload.tag): _element_to_value(payload, MAX_EMBED_DEPTH)} class SoapTransport: - """SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。""" + """SOAP 传输;http_request 可注入以便单元测试(默认 requests.request)。""" connector_type = 'soap' + def __init__(self, http_request: HttpRequest | None = None): + self._http_request = http_request or requests.request + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: config = client.get('config_json') or {} - # SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。 - # 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。 - wsdl = str(config.get('endpoint') or '').strip() - if not wsdl: + endpoint = str(config.get('endpoint') or '').strip() + if not endpoint: raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)') - # 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。 - raise NotImplementedError('SOAP implementation pending frozen WSDL') + spec = interface.get('request_spec_json') or {} + soap_spec = spec.get('soap') or {} + template = str(soap_spec.get('body_template') or '').strip() + if not template: + raise TransportNotFrozenError('SOAP contract not frozen (missing soap.body_template)') + + body = fill_soap_template(template, request.get('params') or {}, client.get('credential') or {}) + headers = {'Content-Type': 'text/xml; charset=utf-8'} + action = str(soap_spec.get('action') or '').strip() + # SOAPAction 头必须存在且按规范带引号(空契约即 '""'):不带引号或缺失 + # 会被鼎捷网关以 415 拒绝(2026-09-22 实测)。 + headers['SOAPAction'] = f'"{action}"' + method = str(spec.get('method') or 'POST').upper() + path = str(spec.get('path') or '').strip() + url = endpoint.rstrip('/') + '/' + path.lstrip('/') if path else endpoint + + response = self._http_request( + method, + url, + data=body.encode('utf-8'), + headers=headers, + timeout=int(config.get('timeout_seconds') or 60), + ) + if int(getattr(response, 'status_code', 0)) >= 400: + return { + 'status': 'business_failed', + 'code': f"HTTP_{int(response.status_code)}", + # 错误回显可能包含请求体(含凭据),先脱敏再截断。 + 'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500], + } + response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential')) + try: + return _parse_soap_payload(response_text) + except ET.ParseError: + return { + 'status': 'technical_failed', + 'code': 'NON_XML', + 'message': response_text[:500], + } + + def probe(self, *, client: dict) -> dict[str, Any]: + """连接测试探针:GET WSDL 地址并校验返回 XML,只证明网络与服务可达。 + + 与 call 的区别:不要求 soap.body_template 契约;根元素为 definitions + (WSDL 地址约定)或 Envelope(直连服务端点约定)任一即算通过。 + 裸服务端点对 GET 常返回 404/405/501(SOAP 只实现 POST),故未带 query + 时自动补 ?wsdl 取服务描述;已带 query(如 ?wsdl)则按原地址探测。 + 连接失败 / HTTP ≥400 / 非 XML / 根元素不符 → ok=False;错误回显先脱敏。 + """ + config = client.get('config_json') or {} + endpoint = str(config.get('endpoint') or '').strip() + if not endpoint: + raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)') + timeout = int(config.get('timeout_seconds') or 60) + probe_url = endpoint if '?' in endpoint else f'{endpoint}?wsdl' + try: + response = self._http_request('GET', probe_url, timeout=timeout) + except Exception as exc: + return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))} + status = int(getattr(response, 'status_code', 0)) + text = mask_secrets(str(getattr(response, 'text', '') or '')[:500], client.get('credential')) + if status >= 400: + return {'ok': False, 'code': f'HTTP_{status}', 'message': text} + try: + root = ET.fromstring(str(getattr(response, 'text', '') or '')) + except ET.ParseError: + return {'ok': False, 'code': 'NON_XML', 'message': text} + root_name = _localname(root.tag) + if root_name not in ('definitions', 'Envelope'): + return {'ok': False, 'code': 'NOT_WSDL', 'message': f'unexpected root <{root_name}>'} + return {'ok': True, 'code': f'HTTP_{status}', 'message': f'wsdl root <{root_name}>'} diff --git a/backend/migrations/versions/rd1e2f3a4b5c_integration_connector_param_mapping_and_db_credentials.py b/backend/migrations/versions/rd1e2f3a4b5c_integration_connector_param_mapping_and_db_credentials.py new file mode 100644 index 00000000..8df9c5c3 --- /dev/null +++ b/backend/migrations/versions/rd1e2f3a4b5c_integration_connector_param_mapping_and_db_credentials.py @@ -0,0 +1,45 @@ +""" +backend/migrations/versions/rd1e2f3a4b5c_integration_connector_param_mapping_and_db_credentials.py + +用途:集成连接器两项增强——绑定增加参数映射列、凭据引用增加密文列(db 维护模式)。 +依赖:Alembic revision dd22ee33ff44(当前唯一 head);integration_bindings / integration_credential_references 已存在。 +逻辑:param_mapping_json 承载域参数→接口参数的声明式映射(空对象=同名直通); + secret_ciphertext 承载凭据 JSON 的 Fernet 密文(主密钥 INTEGRATION_CREDENTIAL_KEY + 环境注入),与既有 env 引用模式并存(secret_provider 区分)。 + +Revision ID: rd1e2f3a4b5c +Revises: dd22ee33ff44 +Create Date: 2026-09-21 19:00:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision = "rd1e2f3a4b5c" +down_revision = "dd22ee33ff44" +branch_labels = None +depends_on = None + +# 与 context_selector_json 同类型约定:PostgreSQL 用 JSONB,SQLite/测试用 JSON。 +PARAM_MAPPING_JSON = sa.JSON().with_variant(postgresql.JSONB(), 'postgresql') + + +def upgrade() -> None: + """绑定加参数映射列;凭据引用加密文列(可空,兼容既有 env 模式行)。""" + op.add_column( + 'integration_bindings', + sa.Column('param_mapping_json', PARAM_MAPPING_JSON, nullable=False, server_default=sa.text("'{}'")), + ) + op.add_column( + 'integration_credential_references', + sa.Column('secret_ciphertext', sa.Text(), nullable=True), + ) + + +def downgrade() -> None: + """删除两列(param_mapping/密文均可由配置与凭据重新维护,无衍生数据)。""" + op.drop_column('integration_credential_references', 'secret_ciphertext') + op.drop_column('integration_bindings', 'param_mapping_json') diff --git a/backend/migrations/versions/re1f3a4b5c6d_drop_integration_binding_context_source_code.py b/backend/migrations/versions/re1f3a4b5c6d_drop_integration_binding_context_source_code.py new file mode 100644 index 00000000..1dcfd624 --- /dev/null +++ b/backend/migrations/versions/re1f3a4b5c6d_drop_integration_binding_context_source_code.py @@ -0,0 +1,31 @@ +"""drop integration binding context_source_code + +Revision ID: re1f3a4b5c6d +Revises: rd1e2f3a4b5c +Create Date: 2026-09-22 10:00:00.000000 + +用途:删除 IntegrationBinding.context_source_code 独立列(过度设计一刀切)。 +依赖:ix1a2b3c4d5e 加列;rd1e2f3a4b5c 为当前 head。 +逻辑:context_source_code 只是 context_selector_json 中 source_code 键的快捷列, + 与高级配置(context_selector_json)机制重复;按路由条件统一走 + context_selector_json 的约定删列,不设兼容层(框架未上线,无存量数据顾虑)。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 're1f3a4b5c6d' +down_revision = 'rd1e2f3a4b5c' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """删除绑定表的 context_source_code 快捷列(路由条件统一由 context_selector_json 表达)。""" + op.drop_column('integration_bindings', 'context_source_code') + + +def downgrade() -> None: + """回滚:恢复 context_source_code 列(nullable,与拆列迁移 ix1a2b3c4d5e 时的定义一致)。""" + op.add_column('integration_bindings', sa.Column('context_source_code', sa.String(length=64), nullable=True)) diff --git a/backend/tests/api/test_integration_connector_api.py b/backend/tests/api/test_integration_connector_api.py index 8b0ea8a2..76417fb9 100644 --- a/backend/tests/api/test_integration_connector_api.py +++ b/backend/tests/api/test_integration_connector_api.py @@ -146,6 +146,69 @@ def test_client_instance_test_connection(app, client, admin_headers, fake_gatewa assert response.get_json()["data"]["ok"] is True +class ProbeSpyTransport: + """记录 probe 收到的 client 配置,验证独立列(endpoint/timeout)已拼回 config_json。""" + + connector_type = "soap" + + def __init__(self): + self.seen = None + + def probe(self, *, client): + self.seen = client + return {"ok": True, "code": "HTTP_200", "message": "wsdl root "} + + def call(self, *, client, interface, request): # pragma: no cover — 走到即失败 + self.seen = {"unexpected_call": True} + + +def test_client_instance_test_connection_merges_endpoint_column(app, client, admin_headers, fake_gateway): + """连接测试回归:endpoint 存独立列(config_json 为空)时必须拼回配置再探测。 + + 曾因测试端点只透传 config_json,SOAP 客户端误报 + 'SOAP contract not frozen (missing wsdl/endpoint)'。 + """ + created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-SOAP", "name": "soap client", "connector_type": "soap", "environment": "prod", + "endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 45, + "config_json": {}, + }) + assert created.status_code == 201 + + spy = ProbeSpyTransport() + fake_gateway.transports["soap"] = spy + response = client.post(f"{API_PREFIX}/client-instances/CLI-SOAP/test", headers=admin_headers) + + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["ok"] is True + # 独立列值必须出现在传给 transport 的 config_json 里(关键断言)。 + assert spy.seen["config_json"]["endpoint"] == "https://erp.invalid/wsdl" + assert spy.seen["config_json"]["timeout_seconds"] == 45 + + +def test_client_instance_test_connection_reports_unreachable(app, client, admin_headers, fake_gateway): + """probe 探测不通 → 仍 200 但 ok=False(探测结果是业务结果,不是请求错误)。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-DOWN", "name": "down", "connector_type": "rest", "environment": "prod", + "endpoint": "https://down.invalid", + }) + + class DownTransport: + connector_type = "rest" + + def probe(self, *, client): + return {"ok": False, "code": "CONNECTION_FAILED", "message": "connection refused"} + + fake_gateway.transports["rest"] = DownTransport() + response = client.post(f"{API_PREFIX}/client-instances/CLI-DOWN/test", headers=admin_headers) + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["ok"] is False + assert data["status"] == "failed" + assert data["result"]["code"] == "CONNECTION_FAILED" + + def test_update_client_instance(app, client, admin_headers): """PUT /client-instances/ → 200,更新 name/config/enabled。""" client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ @@ -162,13 +225,13 @@ def test_update_client_instance(app, client, admin_headers): def test_update_interface_definition(app, client, admin_headers): - """PUT /interface-definitions/ → 200,更新模板/回传映射/状态。""" + """PUT /interface-definitions/ → 200,更新模板/回传映射;body 里的 status 被忽略。""" client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ "code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod", "config_json": {}, }) client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ - "code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest", + "code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "request_spec_json": {"path": "/v1/old"}, "status": "draft", }) response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={ @@ -177,12 +240,86 @@ def test_update_interface_definition(app, client, admin_headers): }) assert response.status_code == 200 data = response.get_json()["data"] - assert data["status"] == "published" + # 状态只能经生命周期动作端点流转:PUT 携带 status 不生效,仍为创建时的 draft + assert data["status"] == "draft" assert data["request_spec_json"] == {"path": "/v1/new"} + assert data["response_mapping_json"] == {"qty": "data.quantity"} + + +def test_interface_connector_type_derived_from_client(app, client, admin_headers): + """连接器类型由所属客户端实例服务端推导:创建/换绑客户端均以客户端为准,body 传值被忽略。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-D1", "name": "soap cli", "connector_type": "soap", "environment": "prod", + "config_json": {}, + }) + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-D2", "name": "rest cli", "connector_type": "rest", "environment": "prod", + "config_json": {}, + }) + # 创建:body 误传 rest(与客户端 soap 不一致)→ 落库以客户端为准 + created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-DERIVE", "name": "iface", "client_instance_code": "CLI-D1", + "connector_type": "rest", + }) + assert created.status_code == 201 + assert created.get_json()["data"]["connector_type"] == "soap" + # 换绑客户端 → 类型跟随新客户端 + updated = client.put(f"{API_PREFIX}/interface-definitions/IF-DERIVE", headers=admin_headers, json={ + "client_instance_code": "CLI-D2", + }) + assert updated.status_code == 200 + assert updated.get_json()["data"]["connector_type"] == "rest" + # 客户端不存在 → 400(而非依赖外键报 500) + missing = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-NOCLI", "name": "iface", "client_instance_code": "CLI-NOT-EXIST", + }) + assert missing.status_code == 400 + + +def test_interface_create_freezes_enabled(app, client, admin_headers): + """接口定义 enabled 冻结:请求体传值被忽略,可用性只由 status 生命周期表达。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-FE", "name": "cli", "connector_type": "rest", "environment": "prod", + }) + created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-FE", "name": "iface", "client_instance_code": "CLI-FE", "enabled": False, + }) + assert created.status_code == 201 + assert created.get_json()["data"]["enabled"] is True + + +def test_interface_lifecycle_transitions(app, client, admin_headers): + """发布/撤回/退役/恢复按转移表流转;非法转移与未知动作被拒绝。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-LC", "name": "cli", "connector_type": "rest", "environment": "prod", + "config_json": {}, + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-LC", "name": "iface", "client_instance_code": "CLI-LC", + }) + + def lifecycle(action, code="IF-LC"): + return client.post(f"{API_PREFIX}/interface-definitions/{code}/{action}", headers=admin_headers) + + # draft 上直接撤回/退役 → 400(源状态不符) + assert lifecycle("unpublish").status_code == 400 + assert lifecycle("retire").status_code == 400 + # draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复) + assert lifecycle("publish").get_json()["data"]["status"] == "published" + assert lifecycle("unpublish").get_json()["data"]["status"] == "draft" + assert lifecycle("publish").get_json()["data"]["status"] == "published" + assert lifecycle("retire").get_json()["data"]["status"] == "retired" + # retired 不能直接发布,须经恢复为草稿 + illegal = lifecycle("publish") + assert illegal.status_code == 400 + assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION" + assert lifecycle("reopen").get_json()["data"]["status"] == "draft" + # 接口不存在 → 404 + assert lifecycle("publish", code="IF-NOPE").status_code == 404 def test_update_binding(app, client, admin_headers): - """PUT /bindings/ → 200,更新映射版本/优先级/状态。""" + """PUT /bindings/ → 200,更新映射版本/优先级;状态不经 PUT 改写(走生命周期端点)。""" client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ "code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod", "config_json": {}, @@ -192,7 +329,7 @@ def test_update_binding(app, client, admin_headers): }) created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ "capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B", - "interface_definition_code": "IF-B", "status": "draft", + "interface_definition_code": "IF-B", }) binding_id = created.get_json()["data"]["id"] response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ @@ -202,24 +339,153 @@ def test_update_binding(app, client, admin_headers): data = response.get_json()["data"] assert data["priority"] == 5 assert data["mapping_version"] == 2 - assert data["status"] == "published" + # 请求体携带 status 被忽略:状态只能经 /publish 动作端点流转 + assert data["status"] == "draft" + + # 发布绑定有就绪门禁:接口定义须先发布 + client.post(f"{API_PREFIX}/interface-definitions/IF-B/publish", headers=admin_headers) + published = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers) + assert published.get_json()["data"]["status"] == "published" + + +def test_binding_create_forces_draft_and_pair_validation(app, client, admin_headers): + """新建绑定固定落 draft;客户端与接口成对校验(错配/缺失均 400)。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod", + "endpoint": "https://erp.invalid", + }) + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-OTHER", "name": "other", "connector_type": "rest", "environment": "prod", + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest", + }) + # 请求体携带 status / context_source_code 均被忽略:状态走生命周期端点, + # 来源路由条件统一由 context_selector_json 表达(无独立快捷列) + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC", + "status": "published", "context_source_code": "DBS-AWSBI", + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert data["status"] == "draft" + assert "context_source_code" not in data + + # 接口定义不属于所选客户端 → 400(fail-fast,不留给调用期) + mismatch = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "client_instance_code": "CLI-OTHER", "interface_definition_code": "IF-BC", + }) + assert mismatch.status_code == 400 + assert mismatch.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH" + # 客户端/接口不存在 → 400(而非依赖外键报 500) + assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "client_instance_code": "CLI-NOT-EXIST", "interface_definition_code": "IF-BC", + }).status_code == 400 + assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "client_instance_code": "CLI-BC", "interface_definition_code": "IF-NOT-EXIST", + }).status_code == 400 + + # 更新换绑接口时同样成对校验:以变更后的最终组合为准 + binding_id = data["id"] + updated = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ + "client_instance_code": "CLI-OTHER", + }) + assert updated.status_code == 400 + assert updated.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH" + + +def test_binding_lifecycle_transitions(app, client, admin_headers): + """发布/撤回/退役/恢复按转移表流转;发布有就绪门禁(接口须已发布且客户端启用)。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-BLC", "name": "cli", "connector_type": "rest", "environment": "prod", + "config_json": {}, + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-BLC", "name": "iface", "client_instance_code": "CLI-BLC", + }) + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "client_instance_code": "CLI-BLC", "interface_definition_code": "IF-BLC", + }) + binding_id = created.get_json()["data"]["id"] + + def lifecycle(action): + return client.post(f"{API_PREFIX}/bindings/{binding_id}/{action}", headers=admin_headers) + + # 接口定义还是草稿 → 发布绑定被就绪门禁拦截(避免发布永不生效的死绑定) + not_ready = lifecycle("publish") + assert not_ready.status_code == 400 + assert not_ready.get_json()["error"]["code"] == "INTEGRATION.BINDING_TARGET_NOT_READY" + + # 接口发布后:draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复) + client.post(f"{API_PREFIX}/interface-definitions/IF-BLC/publish", headers=admin_headers) + assert lifecycle("publish").get_json()["data"]["status"] == "published" + assert lifecycle("unpublish").get_json()["data"]["status"] == "draft" + assert lifecycle("publish").get_json()["data"]["status"] == "published" + assert lifecycle("retire").get_json()["data"]["status"] == "retired" + # retired 不能直接发布,须经恢复为草稿 + illegal = lifecycle("publish") + assert illegal.status_code == 400 + assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION" + assert lifecycle("reopen").get_json()["data"]["status"] == "draft" + # 绑定不存在 → 404 + assert client.post(f"{API_PREFIX}/bindings/999999/publish", headers=admin_headers).status_code == 404 def test_update_credential_reference(app, client, admin_headers): - """PUT /credential-references/ → 200,更新 secret_ref/status,且不回显明文。""" + """PUT /credential-references/ → 200,更新 secret_ref,且不回显明文。""" client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ "code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD", }) response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={ - "secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating", + "secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", }) assert response.status_code == 200 data = response.get_json()["data"] assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED" - assert data["status"] == "rotating" assert "secret" not in str(data).lower() or data.get("secret") is None +def test_credential_status_two_state_toggle(app, client, admin_headers): + """凭据状态两态开关:active/retired 可经 PUT 互切;rotating 不可进入;存量 rotating 可恢复。""" + client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-TS", "secret_ref": "IN_TRANSIT_ERP_PASSWORD", + }) + # active → retired(停用;解析层只认 active,停用即断流) + retired = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={ + "status": "retired", + }) + assert retired.status_code == 200 + assert retired.get_json()["data"]["status"] == "retired" + # rotating 不可进入(其现语义等于断供,真实版本化轮换属 P2) + rotating = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={ + "status": "rotating", + }) + assert rotating.status_code == 400 + # retired → active(恢复启用) + reactivated = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={ + "status": "active", + }) + assert reactivated.get_json()["data"]["status"] == "active" + # 存量 rotating 数据(经 create 兼容通道落库)可经 PUT 置回 active 恢复 + client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-LEGACY", "secret_ref": "LEGACY_KEY", "status": "rotating", + }) + recovered = client.put(f"{API_PREFIX}/credential-references/CRED-LEGACY", headers=admin_headers, json={ + "status": "active", + }) + assert recovered.status_code == 200 + assert recovered.get_json()["data"]["status"] == "active" + # 非法状态值 → 400 + assert client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={ + "status": "bogus", + }).status_code == 400 + + def test_client_instance_split_columns(app, client, admin_headers): """POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。""" created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ @@ -265,26 +531,101 @@ def test_interface_definition_split_columns(app, client, admin_headers): assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}" -def test_binding_split_columns(app, client, admin_headers): - """POST/PUT /bindings 写 context_source_code 独立列并回显。""" +# ---- 绑定参数映射 / 凭据 db 模式 ---- + +def test_binding_param_mapping_round_trip(app, client, admin_headers): + """POST/PUT /bindings 透传 param_mapping_json,序列化原样返回。""" client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ - "code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod", + "code": "CLI-PM", "name": "cli", "connector_type": "rest", "environment": "prod", "endpoint": "https://erp.invalid", }) client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ - "code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest", + "code": "IFACE-PM", "name": "iface", "client_instance_code": "CLI-PM", "connector_type": "rest", }) created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ "capability": "in_transit_transfer.query_inventory", - "client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC", - "context_source_code": "DBS-AWSBI", "status": "published", + "client_instance_code": "CLI-PM", "interface_definition_code": "IFACE-PM", + "param_mapping_json": {"organization": {"expr": "external_org"}, + "condition": {"template": "img04 = '{invoice_no}'"}}, }) assert created.status_code == 201 data = created.get_json()["data"] - assert data["context_source_code"] == "DBS-AWSBI" + assert data["param_mapping_json"]["organization"] == {"expr": "external_org"} - updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={ - "context_source_code": "CRANE-SZ", - }) + updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, + json={"param_mapping_json": {"condition": {"template": "img02 = '{warehouse}'"}}}) assert updated.status_code == 200 - assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ" + assert updated.get_json()["data"]["param_mapping_json"] == { + "condition": {"template": "img02 = '{warehouse}'"}, + } + + +def test_credential_db_mode_round_trip(app, client, admin_headers): + """db 模式:按凭据类型加密字段落库;回显非密字段、绝不回显密文;只改密码保留用户名。""" + from cryptography.fernet import Fernet + + app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii") + created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-DB", "secret_provider": "db", + "username": "erp_user", "password": "erp_pass", + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert data["secret_fields"] == {"username": "erp_user"} + assert data["has_secret"] is True + assert "erp_pass" not in created.get_data(as_text=True) + assert "secret_ciphertext" not in data + + updated = client.put(f"{API_PREFIX}/credential-references/CRED-DB", headers=admin_headers, + json={"password": "new_pass"}) + assert updated.status_code == 200 + data = updated.get_json()["data"] + assert data["secret_fields"] == {"username": "erp_user"} # 只改密码时用户名保留 + assert "new_pass" not in updated.get_data(as_text=True) + + +def test_credential_db_mode_token_type_and_types_endpoint(app, client, admin_headers): + """token 类型按其字段清单组装;类型清单端点返回注册表。""" + from cryptography.fernet import Fernet + + app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii") + types = client.get(f"{API_PREFIX}/credential-references/types", headers=admin_headers) + assert types.status_code == 200 + type_names = {item["type"] for item in types.get_json()["data"]} + assert type_names == {"password", "token", "api_key"} + + created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-TOKEN", "secret_provider": "db", "credential_type": "token", + "token": "tk-123", + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert data["credential_type"] == "token" + assert data["secret_fields"] == {} # token 是密文字段,不回显 + assert "tk-123" not in created.get_data(as_text=True) + + # token 必填缺失 → 400 + missing = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-TOKEN2", "secret_provider": "db", "credential_type": "token", + }) + assert missing.status_code == 400 + + +def test_credential_db_mode_unknown_type_rejected(app, client, admin_headers): + """未知凭据类型 → 400(fail-closed)。""" + from cryptography.fernet import Fernet + + app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii") + response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-BAD", "secret_provider": "db", "credential_type": "nope", + "username": "u", "password": "p", + }) + assert response.status_code == 400 + + +def test_credential_db_mode_requires_username_and_password(app, client, admin_headers): + """db 模式创建缺用户名或密码 → 400。""" + response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-DB2", "secret_provider": "db", "username": "only-user", + }) + assert response.status_code == 400 diff --git a/backend/tests/services/integration_connector/test_binding.py b/backend/tests/services/integration_connector/test_binding.py index 245b1ff8..f8159a72 100644 --- a/backend/tests/services/integration_connector/test_binding.py +++ b/backend/tests/services/integration_connector/test_binding.py @@ -3,6 +3,7 @@ 用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。 依赖:IntegrationBinding 等模型、binding.py、errors.py。 逻辑:只匹配 published + environment + 生效区间 + context_selector 子集; + 接口定义须 published、客户端须 enabled,否则同样 fail-closed; 无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。 """ @@ -120,3 +121,43 @@ def test_freeze_versions_in_snapshot(app): assert snap.credential_ref_code is None assert snap.request_spec.get("path") == "/stock" assert snap.config.get("endpoint") == "https://erp.invalid" + + +def test_snapshot_carries_param_mapping_and_input_schema(app): + """快照冻结绑定参数映射与接口入参 Schema(引擎翻译契约)。""" + db.session.add_all([ + _client(), + _interface(input_schema_json={"type": "object", "required": ["condition"]}), + _binding(param_mapping_json={"condition": {"template": "img04 = '{invoice_no}'"}}), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert snap.param_mapping == {"condition": {"template": "img04 = '{invoice_no}'"}} + assert snap.input_schema == {"type": "object", "required": ["condition"]} + + +def test_draft_interface_not_matched(app): + """接口定义为 draft 时不命中(fail-closed):绑定已发布但接口未发布视同无可用绑定。""" + db.session.add_all([_client(), _interface(status="draft"), _binding()]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_retired_interface_not_matched(app): + """接口定义为 retired 时不命中:退役是引用它的所有绑定的总开关。""" + db.session.add_all([_client(), _interface(status="retired"), _binding()]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_disabled_client_not_matched(app): + """客户端实例停用(enabled=False)时不命中:列表行内启停开关具备调用期语义。""" + db.session.add_all([_client(enabled=False), _interface(), _binding()]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" diff --git a/backend/tests/services/integration_connector/test_capability.py b/backend/tests/services/integration_connector/test_capability.py index 8b0c3c8b..d112507c 100644 --- a/backend/tests/services/integration_connector/test_capability.py +++ b/backend/tests/services/integration_connector/test_capability.py @@ -11,9 +11,7 @@ import pytest from app.services.integration_connector.capability import ( CapabilitySpec, - ensure_capabilities_loaded, get_capability, - list_capabilities, register_capability, reset_capability_registry_for_tests, ) @@ -47,13 +45,3 @@ def test_get_unregistered_raises_not_found(): get_capability("in_transit_transfer.none") assert exc.value.code == "INTEGRATION.CAPABILITY_NOT_FOUND" assert exc.value.http_status == 404 - - -def test_ensure_loaded_registers_three_transfer_capabilities(): - """ensure_capabilities_loaded 后注册 3 个在途调拨能力,write 标志正确。""" - ensure_capabilities_loaded() - names = {spec.name for spec in list_capabilities()} - assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names) - assert get_capability("in_transit_transfer.create_transfer").write is True - assert get_capability("in_transit_transfer.query_inventory").write is False - assert get_capability("in_transit_transfer.verify_duplicate").write is False diff --git a/backend/tests/services/integration_connector/test_credential_types.py b/backend/tests/services/integration_connector/test_credential_types.py new file mode 100644 index 00000000..df74a73c --- /dev/null +++ b/backend/tests/services/integration_connector/test_credential_types.py @@ -0,0 +1,51 @@ +"""tests/services/integration_connector/test_credential_types.py + +用途:验证凭据类型注册表——字段组装/必填校验/非密回显/未知类型 fail-closed。 +依赖:credential_types(纯函数)。 +逻辑:build_secret_dict 只保留类型定义内字段且必填齐全;visible_fields 只回显非密字段。 +""" + +from __future__ import annotations + +import pytest + +from app.core.errors import AppError +from app.services.integration_connector.credential_types import ( + build_secret_dict, + get_credential_type, + list_credential_types, + visible_fields, +) + + +def test_registry_contains_builtin_types(): + """内置 password/token/api_key 三种类型,字段定义齐全。""" + types = {item["type"] for item in list_credential_types()} + assert types == {"password", "token", "api_key"} + password_fields = {f["key"]: f for f in get_credential_type("password")["fields"]} + assert set(password_fields) == {"username", "password"} + assert password_fields["password"]["secret"] is True + assert password_fields["username"]["secret"] is False + + +def test_build_secret_dict_keeps_defined_keys_only(): + """只保留类型定义内的键(未知键丢弃),必填齐全。""" + values = {"username": "u", "password": "p", "evil": "x"} + assert build_secret_dict("password", values) == {"username": "u", "password": "p"} + + +def test_build_secret_dict_missing_required_fail_closed(): + """必填字段缺失 → ValidationError。""" + with pytest.raises(AppError): + build_secret_dict("password", {"username": "u"}) + + +def test_build_secret_dict_unknown_type_fail_closed(): + with pytest.raises(AppError): + build_secret_dict("nope", {}) + + +def test_visible_fields_returns_non_secret_only(): + assert visible_fields("password", {"username": "u", "password": "p"}) == {"username": "u"} + assert visible_fields("token", {"token": "t"}) == {} + assert visible_fields("nope", {"x": "y"}) == {} diff --git a/backend/tests/services/integration_connector/test_engine.py b/backend/tests/services/integration_connector/test_engine.py index 8cb22785..ae6c8a7c 100644 --- a/backend/tests/services/integration_connector/test_engine.py +++ b/backend/tests/services/integration_connector/test_engine.py @@ -16,10 +16,20 @@ import pytest from app import db from app.core.errors import AppError from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition -from app.services.integration_connector.capability import ensure_capabilities_loaded +from app.services.in_transit_transfer.capabilities import register_transfer_capabilities +from app.services.integration_connector.capability import reset_capability_registry_for_tests from app.services.integration_connector.engine import CapabilityGateway +@pytest.fixture(autouse=True) +def _transfer_capabilities(): + """每用例前重建在途调拨能力注册:能力声明已移至领域包,注册表可能被其他用例 reset。""" + reset_capability_registry_for_tests() + register_transfer_capabilities() + yield + reset_capability_registry_for_tests() + + class FakeTransport: """可注入响应或异常的传输替身。""" @@ -60,14 +70,16 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc def _params(**overrides): - values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100} + values = { + "external_org": "HX-CN01", + "targets": [{"material_no": "M-1", "from_warehouse": "W1", "lot_no": "L-1"}], + } values.update(overrides) return values def test_call_success_records_integration_call(app): """读能力成功:status=success、data 含映射结果、落 IntegrationCall。""" - ensure_capabilities_loaded() _seed("in_transit_transfer.query_inventory") fake = FakeTransport({"found": True, "quantity": "100"}) result = CapabilityGateway(transports={"rest": fake}).call( @@ -83,7 +95,6 @@ def test_call_success_records_integration_call(app): def test_call_input_invalid_raises(app): """入参不合输入 Schema → INTEGRATION.INPUT_INVALID。""" - ensure_capabilities_loaded() _seed("in_transit_transfer.query_inventory") with pytest.raises(AppError) as exc: CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( @@ -95,7 +106,6 @@ def test_call_input_invalid_raises(app): def test_call_no_binding_raises(app): """无可用绑定 → INTEGRATION.BINDING_NOT_FOUND(fail-closed)。""" - ensure_capabilities_loaded() with pytest.raises(AppError) as exc: CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( capability="in_transit_transfer.query_inventory", context={}, @@ -106,7 +116,6 @@ def test_call_no_binding_raises(app): def test_call_write_business_failed(app): """写能力按原始 status 分类 → business_failed。""" - ensure_capabilities_loaded() _seed("in_transit_transfer.create_transfer") fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"}) result = CapabilityGateway(transports={"rest": fake}).call( @@ -119,7 +128,6 @@ def test_call_write_business_failed(app): def test_call_transport_timeout_returns_timeout(app): """传输超时 → status=timeout。""" - ensure_capabilities_loaded() _seed("in_transit_transfer.query_inventory") result = CapabilityGateway(transports={"rest": FakeTransport(TimeoutError())}).call( capability="in_transit_transfer.query_inventory", context={}, @@ -130,7 +138,6 @@ def test_call_transport_timeout_returns_timeout(app): def test_call_mapping_invalid_raises(app): """输出不合输出 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。""" - ensure_capabilities_loaded() _seed("in_transit_transfer.query_inventory", output_schema={"type": "object", "required": ["found", "quantity"], "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}}) @@ -145,7 +152,6 @@ def test_call_mapping_invalid_raises(app): def test_call_result_unknown_no_auto_retry(app): """result_unknown 不自动重试:transport 仅被调用一次。""" - ensure_capabilities_loaded() _seed("in_transit_transfer.create_transfer") calls = [] @@ -160,3 +166,109 @@ def test_call_result_unknown_no_auto_retry(app): ) assert result.status == "result_unknown" assert len(calls) == 1 + + +# ---- 参数映射与凭据注入(P1 绑定翻译契约)---- + +def _seed_full_params(*, param_mapping=None, input_schema=None, credential_ref=None): + client = IntegrationClientInstance( + code="CLI-P", name="client", connector_type="rest", environment="prod", + config_json={"endpoint": "https://erp.invalid"}, credential_ref_code=credential_ref, + ) + iface = IntegrationInterfaceDefinition( + code="IFACE-P", name="iface", client_instance_code="CLI-P", connector_type="rest", + request_spec_json={"method": "GET", "path": "/stock"}, + input_schema_json=input_schema or {}, + response_mapping_json={"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}}, + output_schema_json={"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}}, + version=1, status="published", + ) + db.session.add_all([client, iface]) + db.session.flush() + binding = IntegrationBinding( + capability="in_transit_transfer.query_inventory", context_selector_json={}, + param_mapping_json=param_mapping or {}, + client_instance_code="CLI-P", interface_definition_code="IFACE-P", + mapping_version=1, priority=0, environment="prod", status="published", + ) + db.session.add(binding) + db.session.commit() + + +def test_call_applies_binding_param_mapping(app): + """绑定配置 param_mapping 时域参数先翻译为接口参数再下传传输层。""" + _seed_full_params( + param_mapping={"organization": {"expr": "external_org"}, + "condition": {"template": "{targets}", + "args": {"list_item_template": "img04 = '{lot_no}'", "separator": " OR "}}}, + input_schema={"type": "object", "required": ["organization", "condition"], + "properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}}, + ) + captured = {} + + class _Capture(FakeTransport): + def call(self, *, client, interface, request): + captured.update(params=request["params"], interface=interface) + return {"found": True, "quantity": "5"} + + result = CapabilityGateway(transports={"rest": _Capture(None)}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(external_org="TGHX", targets=[{"material_no": "M-9", "from_warehouse": "W1", "lot_no": "L-9"}]), + operation_id="OP-PM", environment="prod", + ) + assert captured["params"] == {"organization": "TGHX", "condition": "img04 = 'L-9'"} + assert result.status == "success" + + +def test_call_mapped_params_fail_interface_schema(app): + """映射结果不合接口入参 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。""" + _seed_full_params( + param_mapping={"organization": {"expr": "external_org"}}, + input_schema={"type": "object", "required": ["organization", "condition"], + "properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}}, + ) + with pytest.raises(AppError) as exc: + CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(external_org="TGHX"), + operation_id="OP-PM2", environment="prod", + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_call_injects_resolved_credential(app): + """客户端实例引用凭据时,引擎解析凭据并经 client['credential'] 注入传输层。""" + _seed_full_params(credential_ref="CRED-1") + app.config["CRED1_CFG"] = {"username": "u", "password": "p"} + from app import db as _db + from app.models import IntegrationCredentialReference + _db.session.add(IntegrationCredentialReference( + code="CRED-1", secret_ref="CRED1_CFG", secret_provider="env", + credential_type="password", version=1, status="active", + )) + _db.session.commit() + captured = {} + + class _Capture(FakeTransport): + def call(self, *, client, interface, request): + captured.update(credential=client["credential"]) + return {"found": True, "quantity": "5"} + + CapabilityGateway(transports={"rest": _Capture(None)}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-CRED", environment="prod", + ) + assert captured["credential"] == {"username": "u", "password": "p"} + + +def test_call_read_capability_failure_passthrough(app): + """读能力返回带失败 status 的原始 dict 时原样分类,不做输出映射。""" + _seed_full_params() + result = CapabilityGateway(transports={"rest": FakeTransport( + {"status": "business_failed", "code": "HTTP_500", "message": "boom"} + )}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-RF", environment="prod", + ) + assert result.status == "business_failed" + assert result.error_code == "HTTP_500" diff --git a/backend/tests/services/integration_connector/test_mapping.py b/backend/tests/services/integration_connector/test_mapping.py index e6548a2a..8efd5a5d 100644 --- a/backend/tests/services/integration_connector/test_mapping.py +++ b/backend/tests/services/integration_connector/test_mapping.py @@ -8,6 +8,7 @@ from __future__ import annotations +import json from decimal import Decimal import pytest @@ -94,3 +95,246 @@ def test_map_response_enum_violation_raises(): }, ) assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +# ---- pick:键值对记录列表取值(XML Field[@name,@value] 归一化的通用消费方式)---- + +def _field_rows(): + return [ + {"@name": "img04", "@value": "HOW25071402"}, + {"@name": "img11", "@value": "30.000"}, + ] + + +def test_pick_returns_value_with_decimal_cast(): + mapped = map_response( + {"quantity": {"expr": "rows", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img11", "value_field": "@value", "cast": "decimal"}}}, + {"rows": _field_rows()}, + {"type": "object", "properties": {"quantity": {"type": "number"}}}, + ) + assert mapped["quantity"] == Decimal("30.000") + + +def test_pick_exists_boolean(): + mapped = map_response( + {"found": {"expr": "rows", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img04", "exists": True}}}, + {"rows": _field_rows()}, + {"type": "object", "properties": {"found": {"type": "boolean"}}}, + ) + assert mapped["found"] is True + mapped_absent = map_response( + {"found": {"expr": "rows", "transform": "pick", + "args": {"key_field": "@name", "key_value": "nope", "exists": True}}}, + {"rows": _field_rows()}, + {"type": "object", "properties": {"found": {"type": "boolean"}}}, + ) + assert mapped_absent["found"] is False + + +def test_pick_requires_list_and_key_args(): + with pytest.raises(AppError): + map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name", "key_value": "x"}}}, + {"rows": {"not": "a list"}}, {}) + with pytest.raises(AppError): + map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name"}}}, + {"rows": _field_rows()}, {}) + + +def test_pick_miss_returns_missing_so_field_absent(): + mapped = map_response( + {"quantity": {"expr": "rows", "transform": "pick", + "args": {"key_field": "@name", "key_value": "nope", "value_field": "@value"}}}, + {"rows": _field_rows()}, + {"type": "object", "properties": {"quantity": {"type": "number"}}}, + ) + assert "quantity" not in mapped + + +# ---- template:参数模板填充(域参数→接口参数翻译的列表渲染)---- + +def test_template_renders_list_into_in_clause(): + mapped = map_response( + {"condition": {"template": "img02 = '{warehouse}' AND img04 IN ({lots})", + "args": {"list_item_template": "'{item}'", "separator": ",", "escape": "quote"}}}, + {"warehouse": "HTP-D43", "lots": ["HOW25071402", "HOW25081302"]}, + {"type": "object", "properties": {"condition": {"type": "string"}}}, + ) + assert mapped["condition"] == "img02 = 'HTP-D43' AND img04 IN ('HOW25071402','HOW25081302')" + + +def test_template_escapes_single_quotes_in_values(): + mapped = map_response( + {"condition": {"template": "img02 = '{warehouse}'", "args": {"escape": "quote"}}}, + {"warehouse": "HT'D43"}, + {"type": "object", "properties": {"condition": {"type": "string"}}}, + ) + assert mapped["condition"] == "img02 = 'HT''D43'" + + +def test_template_missing_param_fail_closed(): + with pytest.raises(AppError) as exc: + map_response( + {"condition": {"template": "img04 = '{invoice_no}'"}}, + {}, + {"type": "object", "properties": {"condition": {"type": "string"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +# ---- dict 项列表模板:域元组列表 → OR 拼接条件(料号+库位+批号批量查询)---- + +def test_template_renders_dict_items_with_field_refs(): + mapped = map_response( + {"condition": {"template": "{targets}", + "args": {"list_item_template": "(img01 = '{material_no}' AND img02 = '{from_warehouse}' AND img04 = '{lot_no}')", + "separator": " OR ", "escape": "quote"}}}, + {"targets": [ + {"material_no": "M-1", "from_warehouse": "HTP-D43", "lot_no": "LOT-1"}, + {"material_no": "M'2", "from_warehouse": "HTP-D49", "lot_no": "LOT-2"}, + ]}, + {"type": "object", "properties": {"condition": {"type": "string"}}}, + ) + assert mapped["condition"] == ( + "(img01 = 'M-1' AND img02 = 'HTP-D43' AND img04 = 'LOT-1') OR " + "(img01 = 'M''2' AND img02 = 'HTP-D49' AND img04 = 'LOT-2')" + ) + + +def test_template_dict_item_missing_field_fail_closed(): + with pytest.raises(AppError) as exc: + map_response( + {"condition": {"template": "{targets}", + "args": {"list_item_template": "(img01 = '{material_no}' AND img04 = '{lot_no}')", + "separator": " OR "}}}, + {"targets": [{"material_no": "M-1"}]}, + {"type": "object", "properties": {"condition": {"type": "string"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +# ---- each:列表逐元素子映射(多条外部记录 → 多行结果)---- + +def test_each_maps_record_list_via_pick_and_cast(): + raw = {"Master": [ + {"Record": {"Field": [ + {"name": "img01", "value": "M-1"}, {"name": "img02", "value": "W1"}, + {"name": "img04", "value": "L-1"}, {"name": "img11", "value": "36"}]}}, + {"Record": {"Field": [ + {"name": "img01", "value": "M-2"}, {"name": "img02", "value": "W2"}, + {"name": "img04", "value": "L-2"}, {"name": "img11", "value": "0"}]}}, + ]} + mapped = map_response( + {"rows": {"expr": "Master", "transform": "each", "args": {"fields": { + "material_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "name", "key_value": "img01", "value_field": "value"}}, + "lot_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "name", "key_value": "img04", "value_field": "value"}}, + "quantity": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "name", "key_value": "img11", "value_field": "value", "cast": "decimal"}}, + }}}}, + raw, + {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}}, + ) + assert mapped["rows"] == [ + {"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("36")}, + {"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("0")}, + ] + + +def test_each_single_record_dict_wrapped_to_one_row(): + """XML 归一化单条记录为 dict → 自动包装为单元素列表,不 fail-closed。""" + mapped = map_response( + {"rows": {"expr": "Master", "transform": "each", "args": {"fields": { + "lot_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}}, + {"Master": {"Record": {"Field": [{"@name": "img04", "@value": "L-1"}]}}}, + {"type": "object", "properties": {"rows": {"type": "array"}}}, + ) + assert mapped["rows"] == [{"lot_no": "L-1"}] + + +def test_each_missing_target_yields_empty_rows(): + """目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 空列表而非 fail-closed。 + + 空结果是合法答案:交领域层归类为"未找到",不因输出 Schema 校验抛映射错误。 + """ + mapped = map_response( + {"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master", + "transform": "each", "args": {"fields": { + "lot_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}}, + {"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {}}}}}}, + {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}}, + ) + assert mapped["rows"] == [] + + +def test_each_skips_items_with_all_fields_missing(): + """Master 存在但无 Record 子节点 → 逐字段全缺失的空行被跳过,不产出违反行 Schema 的 {}。""" + mapped = map_response( + {"rows": {"expr": "Master", "transform": "each", "args": {"fields": { + "lot_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}}, + {"Master": {"@name": "img_file"}}, + {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}}, + ) + assert mapped["rows"] == [] + + +def test_each_flattens_repeated_recordset_from_multi_target_query(): + """多条件批量查询返回多个 RecordSet(重复节点列表)→ 路径扇出收集,行全部拉平。 + + [回归防线 2026-09-22] TIPTOP 对 OR 多目标查询按条件拆多个 RecordSet 返回: + 路径遇列表做逐元素收集后 each 正常产出全部行,不得误判为"查无记录"。 + """ + raw = json.loads(r""" + {"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {"RecordSet": [ + {"@id": "1", "Master": {"@name": "img_file", "Record": {"Field": [ + {"@name": "img01", "@value": "M-1"}, {"@name": "img04", "@value": "L-1"}, + {"@name": "img10", "@value": "0.000"}]}}}, + {"@id": "2", "Master": {"@name": "img_file", "Record": {"Field": [ + {"@name": "img01", "@value": "M-2"}, {"@name": "img04", "@value": "L-2"}, + {"@name": "img10", "@value": "5.000"}]}}} + ]}}}}} + }""") + mapped = map_response( + {"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master", + "transform": "each", "args": {"fields": { + "material_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img01", "value_field": "@value"}}, + "lot_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}, + "quantity": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img10", "value_field": "@value", + "cast": "decimal"}}}}}}, + raw, + {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}}, + ) + # [断言意图] 两个条件的记录都进入 rows,数量不足/未找到的判定输入完整。 + assert mapped["rows"] == [ + {"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("0.000")}, + {"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("5.000")}, + ] + + +def test_each_target_not_list_fail_closed(): + with pytest.raises(AppError) as exc: + map_response( + {"rows": {"expr": "Master", "transform": "each", "args": {"fields": {}}}}, + {"Master": "not a dict or list"}, + {"type": "object", "properties": {"rows": {"type": "array"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_each_unknown_nested_transform_fail_closed(): + with pytest.raises(AppError) as exc: + map_response( + {"rows": {"expr": "Master", "transform": "each", "args": {"fields": { + "x": {"expr": "a", "transform": "no_such_fn"}}}}}, + {"Master": [{"a": 1}]}, + {"type": "object", "properties": {"rows": {"type": "array"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" diff --git a/backend/tests/services/integration_connector/test_migration.py b/backend/tests/services/integration_connector/test_migration.py index 4d00b979..1f7367bc 100644 --- a/backend/tests/services/integration_connector/test_migration.py +++ b/backend/tests/services/integration_connector/test_migration.py @@ -84,3 +84,31 @@ def test_split_migration_chains_after_create(): split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py') assert split.revision == 'ix1a2b3c4d5e' assert split.down_revision == 'iy1a2b3c4d5e' + + +def test_drop_context_source_code_migration_round_trip(): + """删列迁移承接 head rd1e2f3a4b5c:升级后 context_source_code 消失,回滚后恢复。""" + engine = sa.create_engine('sqlite:///:memory:') + base = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py') + split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py') + drop = _load_migration( + 'integration_binding_drop_source_code_migration', + 're1f3a4b5c6d_drop_integration_binding_context_source_code.py', + ) + assert drop.revision == 're1f3a4b5c6d' + assert drop.down_revision == 'rd1e2f3a4b5c' + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + for module in (base, split, drop): + module.op = operations + + base.upgrade() + split.upgrade() + drop.upgrade() + cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')} + assert 'context_source_code' not in cols + + drop.downgrade() + cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')} + assert 'context_source_code' in cols diff --git a/backend/tests/services/integration_connector/test_security.py b/backend/tests/services/integration_connector/test_security.py index 7f53ab69..8f7bf74b 100644 --- a/backend/tests/services/integration_connector/test_security.py +++ b/backend/tests/services/integration_connector/test_security.py @@ -71,3 +71,59 @@ def test_credential_summary_has_no_plaintext(app): assert "s3cretLY" not in json.dumps(summary) assert "svc_user_erp" not in json.dumps(summary) assert summary["version"] == 1 + + +# ---- db 模式:密文落库 + 主密钥解密 ---- + +def _add_db_credential(code="DB-CRED", ciphertext=None): + cred = IntegrationCredentialReference( + code=code, secret_ref=f"db:{code}", secret_provider="db", + credential_type="password", version=1, status="active", + secret_ciphertext=ciphertext, + ) + db.session.add(cred) + db.session.commit() + return cred + + +def _crypto_codes(): + from app.core.credential_crypto import CredentialCryptoErrorCodes + return CredentialCryptoErrorCodes( + key_missing="K1", key_invalid="K2", secret_empty="S0", secret_missing="S1", secret_invalid="S2", + ) + + +def test_resolve_credential_db_mode_decrypts(app): + """db 模式:用 INTEGRATION_CREDENTIAL_KEY 解密密文还原凭据字典。""" + from cryptography.fernet import Fernet + + from app.core.credential_crypto import encrypt_secret + app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii") + ciphertext = encrypt_secret( + json.dumps({"username": "u", "password": "p"}), + key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes(), + ) + _add_db_credential(ciphertext=ciphertext) + assert resolve_credential("DB-CRED") == {"username": "u", "password": "p"} + + +def test_resolve_credential_db_mode_missing_ciphertext_fail_closed(app): + """db 模式缺密文 → CredentialUnresolvedError。""" + _add_db_credential(ciphertext=None) + with pytest.raises(AppError) as exc: + resolve_credential("DB-CRED") + assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED" + + +def test_resolve_credential_db_mode_missing_master_key_fail_closed(app): + """主密钥无效 → 统一折算为 CredentialUnresolvedError(fail-closed)。""" + from cryptography.fernet import Fernet + + from app.core.credential_crypto import encrypt_secret + app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii") + ciphertext = encrypt_secret("x", key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes()) + _add_db_credential(ciphertext=ciphertext) + app.config["INTEGRATION_CREDENTIAL_KEY"] = "not-a-valid-key" + with pytest.raises(AppError) as exc: + resolve_credential("DB-CRED") + assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED" diff --git a/backend/tests/services/integration_connector/test_transports.py b/backend/tests/services/integration_connector/test_transports.py index bd3cfc80..a191a39a 100644 --- a/backend/tests/services/integration_connector/test_transports.py +++ b/backend/tests/services/integration_connector/test_transports.py @@ -1,9 +1,10 @@ """tests/services/integration_connector/test_transports.py 用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed; - 以及结果分类(classify_transport_response)的六态语义。 + 连接测试探针(probe)的可达判定;以及结果分类(classify_transport_response)的六态语义。 依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。 逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。 + probe 只做网络可达性探测(REST 任意响应即通;SOAP 校验 WSDL/Envelope 根元素)。 """ from __future__ import annotations @@ -102,3 +103,289 @@ def test_classify_transport_response_states(): assert dup.status == "duplicate_success" unknown = classify_transport_response({}) assert unknown.status == "technical_failed" + + +# ---- SOAP Transport 实装 ---- + +_SOAP_TEMPLATE = ( + '' + '' + '' + '' + '' + '' + ']]>' +) + +# 带命名空间前缀 + 转义内嵌 XML 的典型网关响应。 +_SOAP_RESPONSE = ( + '' + '' + '' + '' + '<Response>' + '<Execution><Status code="0" sqlcode="0" description=""/></Execution>' + '<ResponseContent><Parameter/>' + '<Document><RecordSet id="1"><Master name="img_file"><Record>' + '<Field name="img04" value="HOW25071402"/>' + '<Field name="img11" value="30.000"/>' + '</Record></Master></RecordSet></Document>' + '</ResponseContent></Response>' + '' + '' +) + + +def _soap_client(**overrides): + cfg = {"endpoint": "https://erp.invalid/ws", "timeout_seconds": 30} + cfg.update(overrides) + return {"config_json": cfg, "credential": {"username": "u1", "password": "p1"}} + + +def test_soap_fills_template_with_params_and_credential(): + """模板占位符从请求参数与凭据(credential_* 前缀)填充,按 text/xml POST。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(method=method, url=url, data=kw.get("data"), headers=kw.get("headers")) + return _resp(200, text=_SOAP_RESPONSE) + + result = SoapTransport(http_request=fake_http).call( + client=_soap_client(), + interface={"request_spec_json": {"method": "POST", "soap": {"action": "", "body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "TGHX", "condition": "img04 IN ('HOW25071402')"}}, + ) + body = captured["data"].decode("utf-8") + assert captured["method"] == "POST" + assert captured["url"] == "https://erp.invalid/ws" + assert captured["headers"]["Content-Type"].startswith("text/xml") + assert captured["headers"]["SOAPAction"] == '""' # SOAPAction 头恒存在(空契约即带引号空串) + assert 'name="TGHX"' in body + assert "img04 IN ('HOW25071402')" in body + assert 'user="u1"' in body and 'password="p1"' in body + # 内嵌转义 XML 被递归展开,且按 localname 归一化(前缀 fjs1 不出现)。 + assert result["GetItemStockListResponse"]["response"]["Response"]["Execution"]["Status"]["@code"] == "0" + fields = result["GetItemStockListResponse"]["response"]["Response"]["ResponseContent"]["Document"]["RecordSet"]["Master"]["Record"]["Field"] + by_name = {f["@name"]: f["@value"] for f in fields} + assert by_name["img11"] == "30.000" + + +def test_soap_missing_template_param_fail_closed(): + """占位符缺值 → INTEGRATION.INPUT_INVALID(fail-closed,不静默出空串)。""" + from app.core.errors import AppError + transport = SoapTransport(http_request=lambda *a, **k: None) + with pytest.raises(AppError) as exc: + transport.call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}}, + request={"params": {"condition": "x"}}, # 缺 organization + ) + assert exc.value.code == "INTEGRATION.INPUT_INVALID" + + +def test_soap_cdata_terminator_rejected(): + """参数值含 CDATA 终止符 ]]> 时拒绝,防报文被截断。""" + from app.core.errors import AppError + transport = SoapTransport(http_request=lambda *a, **k: None) + with pytest.raises(AppError) as exc: + transport.call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "TGHX", "condition": "a]]>b"}}, + ) + assert exc.value.details.get("reason") == "soap_cdata_terminator_in_params" + + +def test_soap_fail_closed_without_body_template(): + """endpoint 存在但缺 soap.body_template → 仍 fail-closed。""" + transport = SoapTransport(http_request=lambda *a, **k: None) + with pytest.raises(TransportNotFrozenError): + transport.call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {}}}, + request={"params": {}}, + ) + + +def test_soap_fault_maps_to_business_failed(): + """标准 SOAP Fault → business_failed dict(faultcode/faultstring 透传)。""" + fault = ( + '' + 'soap:Client' + 'bad request' + ) + transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text=fault)) + result = transport.call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "TGHX", "condition": "c"}}, + ) + assert result["status"] == "business_failed" + assert result["message"] == "bad request" + + +def test_soap_http_error_and_non_xml(): + """HTTP 5xx → business_failed;200 非 XML → technical_failed(与 REST 同语义)。""" + transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom")) + result = transport.call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "T", "condition": "c"}}, + ) + assert result["status"] == "business_failed" and result["code"] == "HTTP_500" + + transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text="not soap")) + result = transport.call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "T", "condition": "c"}}, + ) + assert result["status"] == "technical_failed" and result["code"] == "NON_XML" + + +def test_soap_error_message_masks_credentials(): + """错误回显(可能含请求体)中的凭据值必须替换为 ***,不得进审计/响应。""" + transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text='echo: password="p1" failed')) + result = transport.call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "T", "condition": "c"}}, + ) + assert result["message"] == 'echo: password="***" failed' + assert "p1" not in result["message"] + + +def test_soap_params_cannot_shadow_credentials(): + """请求参数不得冒充 credential_* 占位符值(凭据注入永远后写覆盖)。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(data=kw.get("data")) + return _resp(200, text=_SOAP_RESPONSE) + + SoapTransport(http_request=fake_http).call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "T", "condition": "c", "credential_password": "evil"}}, + ) + assert 'password="p1"' in captured["data"].decode("utf-8") + assert "evil" not in captured["data"].decode("utf-8") + + +def test_soap_action_header_sent_when_configured(): + """soap.action 非空时写入 SOAPAction 头。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(headers=kw.get("headers")) + return _resp(200, text=_SOAP_RESPONSE) + + SoapTransport(http_request=fake_http).call( + client=_soap_client(), + interface={"request_spec_json": {"soap": {"action": "urn:GetItemStockList", "body_template": _SOAP_TEMPLATE}}}, + request={"params": {"organization": "T", "condition": "c"}}, + ) + assert captured["headers"]["SOAPAction"] == '"urn:GetItemStockList"' # 按规范带引号 + + +# ---- 连接测试探针(probe):只证明网络/服务可达,不做业务调用 ---- + +_WSDL = ( + '' + '' + '' +) + + +def test_rest_probe_reachable_on_any_http_response(): + """REST probe:任意 HTTP 响应(含 404)都证明 endpoint 网络可达。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(method=method, url=url) + return _resp(404, text="not found") + + result = RestTransport(http_request=fake_http).probe(client=_client()) + assert captured["method"] == "GET" + assert captured["url"] == "https://erp.invalid" + assert result["ok"] is True + assert result["code"] == "HTTP_404" + + +def test_rest_probe_connection_failure_not_ok_and_masked(): + """REST probe:连接异常 → ok=False,异常回显中凭据值脱敏。""" + + def fake_http(method, url, **kw): + raise ConnectionError('connect failed with password="p1"') + + probe_client = _client() + probe_client["credential"] = {"password": "p1"} + result = RestTransport(http_request=fake_http).probe(client=probe_client) + assert result["ok"] is False + assert result["code"] == "CONNECTION_FAILED" + assert "p1" not in result["message"] + + +def test_rest_probe_fail_closed_without_endpoint(): + """REST probe:endpoint 未冻结时同样 fail-closed。""" + transport = RestTransport(http_request=lambda *a, **k: None) + with pytest.raises(TransportNotFrozenError): + transport.probe(client={"config_json": {}}) + + +def test_soap_probe_wsdl_and_envelope_reachable(): + """SOAP probe:WSDL(definitions)与直连服务端点(Envelope)根元素均算可达。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(method=method, url=url) + return _resp(200, text=_WSDL) + + result = SoapTransport(http_request=fake_http).probe(client=_soap_client()) + assert captured["method"] == "GET" + # 裸服务端点自动补 ?wsdl:SOAP 端点对裸 GET 常返回 404/405/501 + assert captured["url"] == "https://erp.invalid/ws?wsdl" + assert result["ok"] is True + + envelope = ( + '' + '' + ) + ok_envelope = SoapTransport(http_request=lambda *a, **k: _resp(200, text=envelope)) + assert ok_envelope.probe(client=_soap_client())["ok"] is True + + +def test_soap_probe_keeps_existing_query(): + """SOAP probe:endpoint 已带 query(如 ?wsdl)时按原地址探测,不重复追加。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(url=url) + return _resp(200, text=_WSDL) + + result = SoapTransport(http_request=fake_http).probe( + client=_soap_client(endpoint="https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl"), + ) + assert captured["url"] == "https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl" + assert result["ok"] is True + + +def test_soap_probe_failure_paths(): + """SOAP probe:HTTP 错误/非 XML/根元素不符/连接异常 → ok=False;缺 wsdl fail-closed。""" + http_error = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom")) + result = http_error.probe(client=_soap_client()) + assert result["ok"] is False and result["code"] == "HTTP_500" + + not_xml = SoapTransport(http_request=lambda *a, **k: _resp(200, text="broken")) + assert not_xml.probe(client=_soap_client())["code"] == "NON_XML" + + wrong_root = SoapTransport(http_request=lambda *a, **k: _resp(200, text="")) + assert wrong_root.probe(client=_soap_client())["code"] == "NOT_WSDL" + + def unreachable(method, url, **kw): + raise ConnectionError("connection refused") + + assert SoapTransport(http_request=unreachable).probe(client=_soap_client())["ok"] is False + + with pytest.raises(TransportNotFrozenError): + SoapTransport().probe(client={"config_json": {}}) diff --git a/docs/platform/integration-connector-framework-design.md b/docs/platform/integration-connector-framework-design.md index f8c73153..40da4bd2 100644 --- a/docs/platform/integration-connector-framework-design.md +++ b/docs/platform/integration-connector-framework-design.md @@ -2,9 +2,9 @@ | 项目 | 说明 | | --- | --- | -| 文档版本 | v1.0(首期最小可行设计) | -| 日期 | 2026-08-27 | -| 状态 | 设计评审中(未实现) | +| 文档版本 | v1.1(P0 内核已实现:REST/SOAP 传输、参数映射、凭据 db/env 双模;版本行冻结/分片/WSDL 导入/发布门禁待后续) | +| 日期 | 2026-09-21(v1.0:2026-08-27) | +| 状态 | P0 已实现并交付首个消费者(在途调拨 query_inventory);§7C/§7E/§7F/§9.4 与版本行冻结为后续阶段 | | 读者 | 平台研发、后端、前端、Agent/集成负责人、ERP/RPA 管理员 | | 关联文档 | [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) | | 首个消费者 | 在途仓自动调拨(`in_transit_transfer`) | @@ -23,13 +23,13 @@ ## 1. 背景与问题 -### 1.1 现状 +### 1.1 现状(2026-09-22 更新:调拨域已完成切换) -在途仓自动调拨当前把 ERP 访问**写死**在代码里: +在途仓自动调拨早期把外部系统访问**写死**在代码里(旧 `erp_adapter.py` / `gateway_adapter.py` 已删除): -- `app/services/in_transit_transfer/erp_adapter.py` 的 `SoapErpTransport` 是唯一传输层,`query_inventory` / `create_transfer` / `verify_duplicate` 三个操作硬编码; -- `app/services/in_transit_transfer/deps.py::_build_erp_adapter()` 固定读取 `IN_TRANSIT_TRANSFER_ERP_*` 配置键并固定构造 SOAP 传输; -- 没有"按来源/按操作选择哪个外部系统、哪个接口、哪种映射"的注册与路由机制。 +- ~~`app/services/in_transit_transfer/erp_adapter.py` 的 `SoapErpTransport` 是唯一传输层~~ 现查询统一走 `capability_client.py::CapabilityClient.query_stock`(组织分组 + 料号/库位/批号元组批量,`external_org` 取自仓库映射),写路径待 Phase 2 接线(fail-closed); +- ~~`deps.py::_build_erp_adapter()` 固定读取 `IN_TRANSIT_TRANSFER_ERP_*` 配置键~~ 现由 `_build_capability_client()` 装配;`query_inventory` 是首个配置绑定消费者(鼎捷 TOPGP GetItemStockList,SOAP 实测联调通过); +- 历史动机:没有"按来源/按操作选择哪个外部系统、哪个接口、哪种映射"的注册与路由机制。 ### 1.2 目标 @@ -85,6 +85,8 @@ > 当前不单独建立 `Connector`、`MessageProfile`、`MappingVersion`、`Fixture` 表,也不把每个 Header、XML 节点或映射字段拆成关系表。接口版本是配置冻结边界:稳定身份、版本、状态、路由、安全和审计字段使用关系列;协议细节、模板、映射和测试引用使用 JSONB。未来只有在出现跨接口复用、独立权限/查询或统计需求时再拆表。 +> **当前实现(2026-09,P1 范围)**:接口定义与客户端实例均带状态/启停字段,且已接入运行时门禁——`resolve_binding` 仅在绑定 `published`、接口定义 `published`、客户端实例 `enabled` 三者同时满足时命中,否则一律 `BindingNotFoundError`(fail-closed)。接口定义与绑定状态只经 `/publish|unpublish|retire|reopen` 动作端点按转移表(draft→published→retired,含撤回与恢复)流转,PUT 不再直接改写状态;绑定发布附加就绪门禁(接口须已发布、客户端须启用,`INTEGRATION.BINDING_TARGET_NOT_READY`),避免发布调用期永不生效的死绑定。接口的连接器类型由所属客户端实例在服务端推导(单一事实源);绑定的客户端与接口在创建/更新时成对校验(接口定义必须属于所选客户端实例,`INTEGRATION.BINDING_PAIR_MISMATCH`)。绑定路由条件统一由 `context_selector_json` 表达(键值对须全部包含于调用上下文才命中;空对象=默认绑定;P1 调用方不传上下文),原 `context_source_code` 快捷列已按过度设计删除(迁移 re1f3a4b5c6d),不设兼容层。凭据引用状态两态化:管理端经行内开关在 active/retired 间切换(`resolve_credential` 只解析 active,停用即断流),`rotating` 不可进入——其现语义等于断供,真实版本化轮换(新旧并存)属 P2;接口定义 `enabled` 冻结忽略传值,可用性只由 status 生命周期表达。版本行冻结、发布后不可变与完整发布门禁(§7F)仍属 P2。 + ### 3.2 运行时实体(2) | 实体 | 职责 | @@ -379,6 +381,7 @@ last_verified_at ``` - ClientInstance 引用 `secret_ref`; +- **已实现的凭据维护双模**:`secret_provider='db'`(管理端默认)——用户名/密码在凭据引用页维护,服务端以 Fernet 主密钥 `INTEGRATION_CREDENTIAL_KEY`(环境注入)加密落库 `secret_ciphertext`,改密免重启,响应只回用户名不回密码/密文;`secret_provider='env'`——兼容模式,只存环境配置键名,真实值由环境注入; - 切换凭据通过版本更新,**不能覆盖运行中的调用**; - 凭据不回显、不写日志、不进配置快照(复用调拨 `sanitize_snapshot` 思路)。 @@ -464,6 +467,7 @@ verify_duplicate # 确认重复 Invoice 对应原单 - 模型:`app/models/integration_connector.py`(ClientInstance / 按版本存储的 InterfaceDefinition / Binding / CredentialReference / IntegrationCall;异步能力启用后再增加 IntegrationAsyncTask) - 服务:`app/services/integration_connector/`(`capability.py` / `binding.py` / `engine.py` / `mapping.py` / `transports/rest.py` / `transports/soap.py` / `descriptors.py` / `security.py`) +- 域能力声明:`app/services//capabilities.py`(如 `in_transit_transfer/capabilities.py`;框架只留注册/校验机制,域契约随域代码版本化,应用组合根每次 `create_app` 幂等注册,2026-09-22 起) - API:`app/api/integration_connector.py`(Admin CRUD + 能力调用端点 + 工具清单) - Admin UI:`frontend/src/features/admin/modules/integration-connector/`(客户端配置作业) - 迁移:Alembic 新迁移,挂在当前 head 后 diff --git a/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts new file mode 100644 index 00000000..a2db1a8e --- /dev/null +++ b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts @@ -0,0 +1,136 @@ +/** + * features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts + * 用途:锁定凭据引用列表的重设计列——类型/账号/来源/启停开关,以及能力清单 tab 的激活与注册表渲染; + * 不再出现内部实现列(secret_ref 原文)与无行动价值的「更新时间」列。 + * 依赖:vi.mock(useIntegrationConnectorAdmin)、@vue/test-utils、i18n。 + * 逻辑:mock composable 返回固定 fixture(password 账密 + token 两条),断言 + * 列表按类型标签/非密账号/来源本地化与布尔启停开关渲染。 + */ +import { describe, expect, it, vi } from 'vitest'; +import { defineComponent, h, ref } from 'vue'; +import { mount } from '@vue/test-utils'; +import { createMemoryHistory, createRouter } from 'vue-router'; +import i18n from '@/i18n'; +import IntegrationConnectorPage from './IntegrationConnectorPage.vue'; +import { createEmptyBindingForm, createEmptyClientInstanceForm, createEmptyCredentialReferenceForm, createEmptyInterfaceDefinitionForm } from './types/integration-connector.types'; + +const mockState = vi.hoisted(() => { + const capabilities = [ + { name: 'in_transit_transfer.create_transfer', write: true, idempotency: 'invoice' }, + { name: 'in_transit_transfer.query_inventory', write: false, idempotency: 'none' }, + { name: 'in_transit_transfer.verify_duplicate', write: false, idempotency: 'invoice' }, + ]; + const bindings = [ + { + id: 1, capability: 'in_transit_transfer.query_inventory', context_selector_json: {}, + client_instance_code: '1001', interface_definition_code: 'IF-A', + mapping_version: 1, priority: 0, environment: 'prod', + effective_from: null, effective_to: null, status: 'published', + }, + ]; + const credentials = [ + { + id: 1, code: 'tiptop-erp', secret_ref: 'db:tiptop-erp', secret_provider: 'db', + credential_type: 'password', secret_fields: { username: 'tiptop' }, has_secret: true, + version: 1, status: 'active', updated_at: '2026-09-21T18:30:00', last_verified_at: null, + }, + { + id: 2, code: 'wms-token', secret_ref: 'db:wms-token', secret_provider: 'env', + credential_type: 'token', secret_fields: {}, has_secret: true, + version: 1, status: 'rotating', updated_at: null, last_verified_at: null, + }, + ]; + const noop = () => vi.fn(); + return { credentials, capabilities, bindings }; +}); + +vi.mock('./composables/useIntegrationConnectorAdmin', () => ({ + useIntegrationConnectorAdmin: () => ({ + clients: ref([]), interfaces: ref([]), bindings: ref(mockState.bindings), + credentials: ref(mockState.credentials), capabilities: ref(mockState.capabilities), credentialTypes: ref([]), + isLoading: ref(false), activeEntity: ref('credential'), showFormModal: ref(false), isSaving: ref(false), + clientForm: ref(createEmptyClientInstanceForm()), + interfaceForm: ref(createEmptyInterfaceDefinitionForm()), + bindingForm: ref(createEmptyBindingForm()), + credentialForm: ref(createEmptyCredentialReferenceForm()), + showCallModal: ref(false), callCapability: ref(''), callParamsText: ref(''), callContextText: ref(''), + callResult: ref(null), callBusy: ref(false), + testingClientCode: ref(''), testResultText: ref(''), + lifecycleBusy: ref(false), + loadAll: vi.fn(), openCreateModal: vi.fn(), openEditModal: vi.fn(), closeFormModal: vi.fn(), + saveActive: vi.fn(), testConnection: vi.fn(), openCallModal: vi.fn(), closeCallModal: vi.fn(), + runCall: vi.fn(), deleteClient: vi.fn(), toggleClient: vi.fn(), toggleCredential: vi.fn(), + changeInterfaceLifecycle: vi.fn(), changeBindingLifecycle: vi.fn(), + }), +})); + +function mountPage() { + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/:pathMatch(.*)*', component: { template: '
' } }] }); + const Harness = defineComponent({ + setup() { + return () => h('div', { style: 'width: 1400px' }, [h(IntegrationConnectorPage)]); + }, + }); + return mount(Harness, { global: { plugins: [i18n, router] } }); +} + +describe('IntegrationConnectorPage credential list', () => { + it('按重设计列渲染:类型徽标 + 非密账号 + 来源徽标 + 启停开关,不再显示 secret_ref 原文', () => { + const wrapper = mountPage(); + const text = wrapper.text(); + // password 类型:类型标签 + 非密账号(username 值)+ 来源本地化;状态不走文字(开关 + 悬停提示) + expect(text).toContain('tiptop-erp'); + expect(text).toContain('账密'); + expect(text).toContain('tiptop'); + expect(text).toContain('界面维护(加密保存)'); + // token 类型:非密字段为空显示占位;env 来源显示 Secret 键名 + expect(text).toContain('wms-token'); + expect(text).toContain('令牌'); + // 内部实现列不再出现:db: 前缀的 secret_ref 原文不渲染 + expect(wrapper.findAll('td').some((td) => td.text() === 'db:tiptop-erp')).toBe(false); + // 「更新时间」列已移除:updated_at 只是行保存时间,非最后轮换/验证时间,无行动价值 + expect(text).not.toContain('2026-09-21 18:30'); + expect(text).not.toContain('更新时间'); + // 布尔启停走行内开关(与客户端实例一致),开关后不带状态文字,精确状态走悬停提示 + expect(wrapper.findAll('[data-testid="credential-status-toggle"]').length).toBe(2); + expect(wrapper.find('[data-testid="credential-status"]').exists()).toBe(false); + expect(text).not.toContain('启用中'); + expect(text).not.toContain('轮换中'); + // 表头与客户端实例一致为「启用」(布尔开关列);「状态」留给接口/绑定的多状态徽章列 + expect(wrapper.findAll('th').some((th) => th.text() === '启用')).toBe(true); + }); + + it('能力清单 tab 可激活:渲染注册能力(写/幂等)与调用入口,新增按钮隐藏', async () => { + const wrapper = mountPage(); + const capTab = wrapper.findAll('[role="tab"]').find((b) => b.text() === '能力清单')!; + await capTab.trigger('click'); + // tab 进入选中态(此前 selectTab 对 capability 直接 return,点击无效) + expect(capTab.attributes('aria-selected')).toBe('true'); + const text = wrapper.text(); + // 中文名称为主行,注册名保留为次行(绑定引用用精确标识) + expect(text).toContain('创建调拨单'); + expect(text).toContain('在途库存查询'); + expect(text).toContain('防重校验'); + expect(text).toContain('in_transit_transfer.query_inventory'); + expect(text).toContain('in_transit_transfer.create_transfer'); + // 写入/幂等本地化:不再出现原始 yes/no 与 invoice/none + expect(wrapper.findAll('td').some((td) => td.text() === '是')).toBe(true); + expect(wrapper.findAll('td').some((td) => td.text() === '否')).toBe(true); + expect(text).toContain('按单据号幂等'); + expect(text).not.toContain('yes'); + expect(text).not.toContain('invoice'); + // 只读清单:无「新增」入口;每行提供「调用」按钮(打开手动调用弹窗) + expect(wrapper.findAll('button').some((b) => b.text().includes('新增'))).toBe(false); + expect(wrapper.findAll('button').some((b) => b.text().includes('调用'))).toBe(true); + }); + + it('绑定列表能力列渲染「中文名 + 注册名」两行', async () => { + const wrapper = mountPage(); + const bindTab = wrapper.findAll('[role="tab"]').find((b) => b.text() === '绑定')!; + await bindTab.trigger('click'); + const text = wrapper.text(); + // 能力引用列与客户端/接口引用列同款:中文名主行 + 注册名次行 + expect(text).toContain('在途库存查询'); + expect(text).toContain('in_transit_transfer.query_inventory'); + }); +}); diff --git a/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue index 8062602e..4ef2504f 100644 --- a/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue +++ b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue @@ -1,28 +1,39 @@ @@ -91,40 +196,92 @@ function selectTab(key: TabKey) { - - + + + + - - - - - - - +
{{ t('admin.integrationConnector.headers.code') }} {{ t('admin.integrationConnector.headers.name') }} {{ t('admin.integrationConnector.headers.connectorType') }} {{ t('admin.integrationConnector.headers.environment') }}{{ t('admin.integrationConnector.headers.actions') }}{{ t('admin.integrationConnector.headers.endpoint') }}{{ t('admin.integrationConnector.fields.enabled') }}{{ t('admin.integrationConnector.headers.testStatus') }}{{ t('admin.integrationConnector.headers.actions') }}
{{ t('admin.integrationConnector.empty') }}
{{ row.code }}{{ row.name }}{{ row.connector_type }}{{ row.environment }} -
-
{{ t('admin.integrationConnector.empty') }}
-

{{ testResultText }}

- +
@@ -132,8 +289,8 @@ function selectTab(key: TabKey) { - - + + @@ -141,10 +298,48 @@ function selectTab(key: TabKey) { - - + +
{{ t('admin.integrationConnector.headers.code') }} {{ t('admin.integrationConnector.headers.name') }} {{ t('admin.integrationConnector.headers.clientInstance') }}{{ t('admin.integrationConnector.headers.status') }}{{ t('admin.integrationConnector.headers.actions') }}{{ t('admin.integrationConnector.headers.status') }}{{ t('admin.integrationConnector.headers.actions') }}
{{ row.code }} {{ row.name }}{{ row.client_instance_code }}{{ row.status }} +

{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}

+

{{ row.client_instance_code }}

+
+ {{ statusLabel(row.status) }} +
+ + + + @@ -155,7 +350,7 @@ function selectTab(key: TabKey) {
- +
@@ -163,19 +358,64 @@ function selectTab(key: TabKey) { - - + + - - - - + + + + + - + + - - + + - + - - - + + + + - - - + + + +
{{ t('admin.integrationConnector.headers.capability') }} {{ t('admin.integrationConnector.headers.clientInstance') }} {{ t('admin.integrationConnector.headers.interfaceDef') }}{{ t('admin.integrationConnector.headers.status') }}{{ t('admin.integrationConnector.headers.actions') }}{{ t('admin.integrationConnector.headers.status') }}{{ t('admin.integrationConnector.headers.actions') }}
{{ t('admin.integrationConnector.empty') }}
{{ row.capability }}{{ row.client_instance_code }}{{ row.interface_definition_code }}{{ row.status }} +

{{ capabilityLabelOf(row.capability) }}

+

{{ row.capability }}

+
+

{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}

+

{{ row.client_instance_code }}

+
+

{{ interfaceNameOf(row.interface_definition_code) || row.interface_definition_code }}

+

{{ row.interface_definition_code }}

+
+ {{ statusLabel(row.status) }} +
+ + + + @@ -192,19 +432,40 @@ function selectTab(key: TabKey) {
{{ t('admin.integrationConnector.headers.code') }}{{ t('admin.integrationConnector.headers.secretRef') }}{{ t('admin.integrationConnector.headers.connectorType') }}{{ t('admin.integrationConnector.headers.account') }} {{ t('admin.integrationConnector.headers.secretProvider') }}{{ t('admin.integrationConnector.headers.status') }}{{ t('admin.integrationConnector.headers.actions') }}{{ t('admin.integrationConnector.fields.enabled') }}{{ t('admin.integrationConnector.headers.actions') }}
{{ t('admin.integrationConnector.empty') }}
{{ t('admin.integrationConnector.empty') }}
{{ row.code }}{{ row.secret_ref }}{{ row.secret_provider }}{{ row.status }} + {{ credentialTypeLabel(row.credential_type) }} + {{ credentialAccountText(row) }} + {{ secretProviderLabel(row.secret_provider) }} + + + +
{{ t('admin.integrationConnector.empty') }}
{{ row.name }}{{ row.write ? 'yes' : 'no' }}{{ row.idempotency }} +

{{ capabilityLabelOf(row.name) }}

+

{{ row.name }}

+
{{ row.write ? t('admin.integrationConnector.writeLabels.yes') : t('admin.integrationConnector.writeLabels.no') }}{{ idempotencyLabel(row.idempotency) }}