- 绑定新增 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_* 配置,外部端点/凭据移交连接器客户端实例管理
750 lines
34 KiB
Python
750 lines
34 KiB
Python
"""api/integration_connector.py
|
||
|
||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
|
||
依赖: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 AppError, NotFoundError, ValidationError
|
||
from app.core.response import ok
|
||
from app.models import (
|
||
IntegrationBinding,
|
||
IntegrationClientInstance,
|
||
IntegrationCredentialReference,
|
||
IntegrationInterfaceDefinition,
|
||
)
|
||
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.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:
|
||
"""字段必填校验。"""
|
||
if value is None or (isinstance(value, str) and not value.strip()):
|
||
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,
|
||
'connector_type': client.connector_type, 'environment': client.environment,
|
||
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
|
||
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
|
||
'enabled': client.enabled,
|
||
}
|
||
|
||
|
||
def _serialize_interface(iface) -> dict:
|
||
return {
|
||
'id': iface.id, 'code': iface.code, 'name': iface.name,
|
||
'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type,
|
||
'http_method': iface.http_method, 'request_path': iface.request_path,
|
||
'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {},
|
||
'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {},
|
||
'version': iface.version, 'status': iface.status, 'enabled': iface.enabled,
|
||
}
|
||
|
||
|
||
def _serialize_binding(binding) -> dict:
|
||
return {
|
||
'id': binding.id, 'capability': binding.capability,
|
||
'context_selector_json': binding.context_selector_json or {},
|
||
'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,
|
||
'environment': binding.environment, 'effective_from': binding.effective_from,
|
||
'effective_to': binding.effective_to, 'status': binding.status,
|
||
}
|
||
|
||
|
||
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,
|
||
'data': result.data,
|
||
'error_code': result.error_code,
|
||
'error_message': result.error_message,
|
||
'document_no': result.document_no,
|
||
'trace_id': result.trace_id,
|
||
}
|
||
|
||
|
||
# ---- 能力清单与调用 ----
|
||
|
||
@integration_connector_bp.route('/capabilities', methods=['GET'])
|
||
@require_admin
|
||
def list_capabilities_endpoint():
|
||
data = [{
|
||
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
|
||
'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
|
||
} for spec in list_capabilities()]
|
||
return ok(data)
|
||
|
||
|
||
@integration_connector_bp.route('/capabilities/<capability>', methods=['POST'])
|
||
@require_admin
|
||
def call_capability(capability):
|
||
body = request.get_json(silent=True) or {}
|
||
if body.get('interface_id') is not None:
|
||
raise ValidationError(
|
||
'interface_id is not allowed for capability calls',
|
||
code='INTEGRATION.INTERFACE_ID_NOT_ALLOWED',
|
||
)
|
||
params = body.get('params') or {}
|
||
context = body.get('context') or {}
|
||
operation_id = str(body.get('operation_id') or f'api-{uuid.uuid4().hex}')
|
||
idempotency_key = body.get('idempotency_key')
|
||
result = get_capability_gateway().call(
|
||
capability=capability, context=context, params=params,
|
||
operation_id=operation_id, idempotency_key=idempotency_key,
|
||
)
|
||
return ok(_result_to_dict(result))
|
||
|
||
|
||
# ---- 客户端实例 ----
|
||
|
||
@integration_connector_bp.route('/client-instances', methods=['GET'])
|
||
@require_admin
|
||
def list_client_instances():
|
||
rows = IntegrationClientInstance.query.order_by(IntegrationClientInstance.code).all()
|
||
return ok([_serialize_client(row) for row in rows])
|
||
|
||
|
||
@integration_connector_bp.route('/client-instances', methods=['POST'])
|
||
@require_admin
|
||
def create_client_instance():
|
||
body = request.get_json(silent=True) or {}
|
||
connector_type = str(body.get('connector_type') or '').strip()
|
||
_require(body.get('code'), 'code')
|
||
_require(body.get('name'), 'name')
|
||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
|
||
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
|
||
client = IntegrationClientInstance(
|
||
code=str(body['code']).strip(), name=str(body['name']).strip(),
|
||
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
|
||
endpoint=(str(body.get('endpoint') or '').strip() or None),
|
||
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
|
||
config_json=body.get('config_json') or {},
|
||
credential_ref_code=body.get('credential_ref_code'),
|
||
enabled=bool(body.get('enabled', True)),
|
||
)
|
||
from app import db
|
||
db.session.add(client)
|
||
db.session.commit()
|
||
return ok(_serialize_client(client), status=201)
|
||
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>', methods=['GET'])
|
||
@require_admin
|
||
def get_client_instance(code):
|
||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||
if client is None:
|
||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||
return ok(_serialize_client(client))
|
||
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>', methods=['DELETE'])
|
||
@require_admin
|
||
def delete_client_instance(code):
|
||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||
if client is None:
|
||
raise NotFoundError('client instance not found')
|
||
from app import db
|
||
db.session.delete(client)
|
||
db.session.commit()
|
||
return ok({'deleted': True})
|
||
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
||
@require_admin
|
||
def update_client_instance(code):
|
||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
|
||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||
if client is None:
|
||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||
body = request.get_json(silent=True) or {}
|
||
connector_type = str(body.get('connector_type') or client.connector_type)
|
||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||
if body.get('name') is not None:
|
||
_require(body.get('name'), 'name')
|
||
client.name = str(body['name']).strip()
|
||
if body.get('connector_type') is not None:
|
||
client.connector_type = connector_type
|
||
if body.get('environment') is not None:
|
||
client.environment = str(body['environment']).strip()
|
||
if 'endpoint' in body:
|
||
client.endpoint = str(body.get('endpoint') or '').strip() or None
|
||
if 'timeout_seconds' in body:
|
||
client.timeout_seconds = int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None
|
||
if 'config_json' in body:
|
||
client.config_json = body.get('config_json') or {}
|
||
if 'credential_ref_code' in body:
|
||
client.credential_ref_code = body.get('credential_ref_code')
|
||
if 'enabled' in body:
|
||
client.enabled = bool(body.get('enabled', True))
|
||
from app import db
|
||
db.session.commit()
|
||
return ok(_serialize_client(client))
|
||
|
||
|
||
# ---- 接口定义 ----
|
||
|
||
@integration_connector_bp.route('/interface-definitions', methods=['GET'])
|
||
@require_admin
|
||
def list_interface_definitions():
|
||
rows = IntegrationInterfaceDefinition.query.order_by(IntegrationInterfaceDefinition.code).all()
|
||
return ok([_serialize_interface(row) for row in rows])
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions', methods=['POST'])
|
||
@require_admin
|
||
def create_interface_definition():
|
||
body = request.get_json(silent=True) or {}
|
||
code = str(body.get('code') or '').strip()
|
||
_require(code, 'code')
|
||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||
# 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值,
|
||
# 杜绝接口与客户端类型不一致);客户端不存在即 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=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 {},
|
||
input_schema_json=body.get('input_schema_json') or {},
|
||
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 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略;
|
||
# 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。
|
||
enabled=True,
|
||
)
|
||
from app import db
|
||
db.session.add(iface)
|
||
db.session.commit()
|
||
return ok(_serialize_interface(iface), status=201)
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
|
||
@require_admin
|
||
def update_interface_definition(code):
|
||
"""更新接口定义(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')
|
||
body = request.get_json(silent=True) or {}
|
||
if body.get('name') is not None:
|
||
_require(body.get('name'), 'name')
|
||
iface.name = str(body['name']).strip()
|
||
if body.get('client_instance_code') is not None:
|
||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||
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:
|
||
iface.request_path = str(body.get('request_path') or '').strip() or None
|
||
for json_field in ('request_spec_json', 'input_schema_json', 'response_mapping_json', 'output_schema_json'):
|
||
if json_field in body:
|
||
setattr(iface, json_field, body.get(json_field) or {})
|
||
if body.get('version') is not None:
|
||
iface.version = int(body.get('version') or 1)
|
||
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/<code>/publish', methods=['POST'])
|
||
@require_admin
|
||
def publish_interface_definition(code):
|
||
"""发布接口定义(draft → published):发布后才会被绑定解析选中。"""
|
||
return _do_interface_lifecycle(code, 'publish')
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>/unpublish', methods=['POST'])
|
||
@require_admin
|
||
def unpublish_interface_definition(code):
|
||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||
return _do_interface_lifecycle(code, 'unpublish')
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>/retire', methods=['POST'])
|
||
@require_admin
|
||
def retire_interface_definition(code):
|
||
"""退役(published → retired):该接口引用的所有绑定同时失效。"""
|
||
return _do_interface_lifecycle(code, 'retire')
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>/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'])
|
||
@require_admin
|
||
def list_bindings():
|
||
rows = IntegrationBinding.query.order_by(IntegrationBinding.capability, IntegrationBinding.priority.desc()).all()
|
||
return ok([_serialize_binding(row) for row in rows])
|
||
|
||
|
||
@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')
|
||
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 {},
|
||
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='draft',
|
||
)
|
||
from app import db
|
||
db.session.add(binding)
|
||
db.session.commit()
|
||
return ok(_serialize_binding(binding), status=201)
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||
@require_admin
|
||
def update_binding(binding_id):
|
||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
|
||
|
||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
|
||
"""
|
||
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')
|
||
body = request.get_json(silent=True) or {}
|
||
if body.get('capability') is not None:
|
||
_require(body.get('capability'), 'capability')
|
||
binding.capability = body['capability']
|
||
if 'context_selector_json' in body:
|
||
binding.context_selector_json = body.get('context_selector_json') or {}
|
||
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:
|
||
binding.priority = int(body.get('priority') or 0)
|
||
if body.get('environment') is not None:
|
||
binding.environment = str(body['environment']).strip()
|
||
if body.get('effective_from') is not None:
|
||
binding.effective_from = body['effective_from'] or None
|
||
if body.get('effective_to') is not None:
|
||
binding.effective_to = body['effective_to'] or None
|
||
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/<int:binding_id>/publish', methods=['POST'])
|
||
@require_admin
|
||
def publish_binding(binding_id):
|
||
"""发布绑定(draft → published):发布后才会被绑定解析选中。"""
|
||
return _do_binding_lifecycle(binding_id, 'publish')
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>/unpublish', methods=['POST'])
|
||
@require_admin
|
||
def unpublish_binding(binding_id):
|
||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||
return _do_binding_lifecycle(binding_id, 'unpublish')
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>/retire', methods=['POST'])
|
||
@require_admin
|
||
def retire_binding(binding_id):
|
||
"""退役(published → retired):绑定退出自动调用。"""
|
||
return _do_binding_lifecycle(binding_id, 'retire')
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>/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'])
|
||
@require_admin
|
||
def list_credential_references():
|
||
rows = IntegrationCredentialReference.query.order_by(IntegrationCredentialReference.code).all()
|
||
return ok([_serialize_credential(row) for row in rows])
|
||
|
||
|
||
@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')
|
||
# 缺省保持 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=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=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/<code>', methods=['PUT'])
|
||
@require_admin
|
||
def update_credential_reference(code):
|
||
"""更新凭据引用(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_provider') is not None:
|
||
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:
|
||
# 状态改写冻结为两态开关:仅允许 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))
|
||
|
||
|
||
# ---- 连接测试 ----
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>/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')
|
||
gateway = get_capability_gateway()
|
||
transport = gateway.transports.get(client.connector_type)
|
||
if transport is None:
|
||
raise ValidationError(
|
||
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
|
||
)
|
||
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})
|