83 lines
2.7 KiB
Python
83 lines
2.7 KiB
Python
"""
|
||
services/shipping_notice/credential_crypto.py
|
||
|
||
用途:加密和解密库存 RPA Profile 的登录凭据。
|
||
依赖:Flask current_app、cryptography.fernet;调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用 decrypt_credential。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from cryptography.fernet import Fernet, InvalidToken
|
||
from flask import current_app
|
||
|
||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||
|
||
|
||
def _fernet() -> Fernet:
|
||
"""
|
||
构造当前环境的凭据加密器。
|
||
|
||
核心逻辑:主密钥只从运行环境读取,缺失或格式无效时拒绝继续,避免写入无法恢复的密文。
|
||
|
||
Returns:
|
||
Fernet: 可执行对称加密的实例。
|
||
|
||
Raises:
|
||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||
"""
|
||
key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip()
|
||
if not key:
|
||
raise ServiceUnavailableError(
|
||
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured',
|
||
code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
|
||
)
|
||
try:
|
||
return Fernet(key.encode('ascii'))
|
||
except (ValueError, UnicodeEncodeError) as exc:
|
||
raise ServiceUnavailableError(
|
||
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid',
|
||
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
|
||
) from exc
|
||
|
||
|
||
def encrypt_credential(value: str) -> str:
|
||
"""
|
||
加密单个 RPA 凭据字段以便持久化。
|
||
|
||
Args:
|
||
value: 非空明文凭据;调用方不得记录此值。
|
||
|
||
Returns:
|
||
str: 可安全保存到数据库的 Fernet 密文。
|
||
|
||
Raises:
|
||
ValidationError: 传入空凭据。
|
||
"""
|
||
plaintext = str(value or '')
|
||
if not plaintext:
|
||
raise ValidationError('RPA credential must not be empty', code='SHIPPING.RPA_CREDENTIAL_EMPTY')
|
||
return _fernet().encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||
|
||
|
||
def decrypt_credential(ciphertext: str) -> str:
|
||
"""
|
||
在受控运行时解密 RPA 凭据。
|
||
|
||
Args:
|
||
ciphertext: 数据库中保存的 Fernet 密文。
|
||
|
||
Returns:
|
||
str: 仅供 RPA 执行内存使用的明文。
|
||
|
||
Raises:
|
||
ValidationError: 密文为空、已损坏或使用了错误主密钥。
|
||
"""
|
||
value = str(ciphertext or '').strip()
|
||
if not value:
|
||
raise ValidationError('RPA credential ciphertext is missing', code='SHIPPING.RPA_CREDENTIAL_MISSING')
|
||
try:
|
||
return _fernet().decrypt(value.encode('ascii')).decode('utf-8')
|
||
except (InvalidToken, UnicodeDecodeError) as exc:
|
||
raise ValidationError('RPA credential ciphertext is invalid', code='SHIPPING.RPA_CREDENTIAL_INVALID') from exc
|