84 lines
3.0 KiB
Python
84 lines
3.0 KiB
Python
"""services/integration_connector/security.py
|
||
|
||
用途:凭据引用解析(fail-closed)与敏感字段脱敏。
|
||
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
|
||
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError;
|
||
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from app.models import IntegrationCredentialReference
|
||
from app.services.integration_connector.errors import CredentialUnresolvedError
|
||
|
||
DEFAULT_SENSITIVE_KEYS = frozenset({
|
||
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
|
||
'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
|
||
})
|
||
|
||
|
||
def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
|
||
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。
|
||
|
||
Raises:
|
||
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。
|
||
"""
|
||
from flask import current_app
|
||
|
||
cred = IntegrationCredentialReference.query.filter_by(
|
||
code=credential_ref_code, status='active',
|
||
).first()
|
||
if cred is None:
|
||
raise CredentialUnresolvedError(ref=credential_ref_code)
|
||
secret_ref = cred.secret_ref
|
||
value = current_app.config.get(secret_ref) if has_app_ctx() else None
|
||
if value is None or value == '':
|
||
raise CredentialUnresolvedError(ref=secret_ref)
|
||
if isinstance(value, dict):
|
||
return dict(value)
|
||
return {'value': value}
|
||
|
||
|
||
def has_app_ctx() -> bool:
|
||
"""当前是否处于 Flask app 上下文(无则返回 False)。"""
|
||
try:
|
||
from flask import has_app_context
|
||
return has_app_context()
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def sanitize(obj: Any, sensitive_keys: set[str] | None = None) -> Any:
|
||
"""递归脱敏:把敏感键对应的值替换为 ***;保留原始结构。
|
||
|
||
Args:
|
||
obj: 待脱敏对象(dict/list/标量)。
|
||
sensitive_keys: 附加敏感键集合;缺省用 DEFAULT_SENSITIVE_KEYS。
|
||
Returns:
|
||
脱敏后的新对象(不修改入参)。
|
||
"""
|
||
keys = DEFAULT_SENSITIVE_KEYS | (sensitive_keys or set())
|
||
if isinstance(obj, dict):
|
||
return {
|
||
key: ('***' if str(key).lower() in keys else sanitize(value, sensitive_keys))
|
||
for key, value in obj.items()
|
||
}
|
||
if isinstance(obj, (list, tuple)):
|
||
return [sanitize(item, sensitive_keys) for item in obj]
|
||
return obj
|
||
|
||
|
||
def credential_summary(cred: IntegrationCredentialReference) -> dict[str, Any]:
|
||
"""只回凭据元数据,绝不含解析出的明文。"""
|
||
return {
|
||
'code': cred.code,
|
||
'secret_ref': cred.secret_ref,
|
||
'secret_provider': cred.secret_provider,
|
||
'credential_type': cred.credential_type,
|
||
'version': cred.version,
|
||
'status': cred.status,
|
||
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
|
||
}
|