From 4826859152194cb697f557b16ea808a307d6bfd6 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Fri, 14 Nov 2025 16:58:08 +0800 Subject: [PATCH] Payment information encryption --- .env.example | 8 +- requirements.txt | 3 +- .../migrate_encrypt_payment_configs.py | 81 ++++++++++++++ .../controllers/payment_channel.py | 37 ++++--- .../services/payment_channel_service.py | 34 +++--- services/api_service/utils/mcp_event_store.py | 26 ++--- services/common/models/payment_channel.py | 3 +- services/common/redis.py | 3 +- services/common/utils/secure_config.py | 102 ++++++++++++++++++ 9 files changed, 249 insertions(+), 48 deletions(-) create mode 100644 scripts/resource/migrate_encrypt_payment_configs.py create mode 100644 services/common/utils/secure_config.py diff --git a/.env.example b/.env.example index 124d120..b1ede9d 100644 --- a/.env.example +++ b/.env.example @@ -24,4 +24,10 @@ RABBITMQ_HOST=xpack-rabbitmq RABBITMQ_PORT=5672 RABBITMQ_USER=rabbitmq RABBITMQ_PASSWORD=rabbitmq_Gs123dA -RABBITMQ_VHOST=/ \ No newline at end of file +RABBITMQ_VHOST=/ + +# Payment config encryption key (Base64-encoded 32-byte random value for AES-GCM) +# Quick generation: python -c "import os,base64; print(base64.b64encode(os.urandom(32)).decode())" +PAYMENT_CONFIG_SECRET_KEY=uyyhfMJ+xpEE+IC5mPigpscekkR2ucz6Sj7sHYLhJQA= +# Optional: key ID used to support key rotation identification +PAYMENT_CONFIG_KEY_ID=default \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 1ff405e..1a8539d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,4 +15,5 @@ google-auth>=2.0.0 google-auth-oauthlib>=1.0.0 fastapi_mcp alipay-sdk-python>=3.0.0 -wechatpayv3[async] \ No newline at end of file +wechatpayv3[async] +cryptography>=41.0.0 \ No newline at end of file diff --git a/scripts/resource/migrate_encrypt_payment_configs.py b/scripts/resource/migrate_encrypt_payment_configs.py new file mode 100644 index 0000000..36330f4 --- /dev/null +++ b/scripts/resource/migrate_encrypt_payment_configs.py @@ -0,0 +1,81 @@ +""" +One-time migration: encrypt plaintext payment channel configs at rest. + +Usage: + python scripts/resource/migrate_encrypt_payment_configs.py [--dry-run] [--limit N] [--ids alipay,wechat,stripe] + +Requirements: + - Environment variable PAYMENT_CONFIG_SECRET_KEY must be set to a base64-encoded 32-byte key. + - cryptography library installed. +""" + +import argparse +import sys +from typing import List +from datetime import datetime, timezone + +from services.common.database import SessionLocal +from services.common.models.payment_channel import PaymentChannel +from services.common.utils.secure_config import is_encrypted, decrypt_config, encrypt_config + + +def migrate_configs(dry_run: bool = False, limit: int = 0, only_ids: List[str] | None = None) -> int: + db = SessionLocal() + migrated = 0 + try: + query = db.query(PaymentChannel) + if only_ids: + query = query.filter(PaymentChannel.id.in_(only_ids)) + rows = query.all() + if limit and len(rows) > limit: + rows = rows[:limit] + + for row in rows: + raw = row.config + if not raw: + continue + if is_encrypted(raw): + # already encrypted + continue + cfg = decrypt_config(raw) + if cfg is None: + # cannot parse plaintext json; skip but report + print(f"[WARN] Skip {row.id}: config not JSON or decrypt failed") + continue + try: + enc = encrypt_config(cfg) + except Exception as e: + print(f"[ERROR] Encrypt {row.id} failed: {e}") + continue + if dry_run: + print(f"[DRY-RUN] Would encrypt {row.id}") + else: + row.config = enc + row.updated_at = datetime.now(timezone.utc) + db.add(row) + migrated += 1 + if not dry_run and migrated: + db.commit() + print(f"Done. Migrated {migrated} rows. Dry-run={dry_run}") + return migrated + finally: + db.close() + + +def main(): + parser = argparse.ArgumentParser(description="Encrypt legacy payment channel configs") + parser.add_argument("--dry-run", action="store_true", help="Do not write changes, only report") + parser.add_argument("--limit", type=int, default=0, help="Limit number of rows to process") + parser.add_argument("--ids", type=str, default="", help="Comma-separated channel ids to process") + args = parser.parse_args() + + only_ids = [x.strip() for x in args.ids.split(",") if x.strip()] if args.ids else None + try: + migrate_configs(dry_run=args.dry_run, limit=args.limit, only_ids=only_ids) + except Exception as e: + print(f"Migration failed: {e}") + sys.exit(1) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/services/admin_service/controllers/payment_channel.py b/services/admin_service/controllers/payment_channel.py index 173feb3..1b64370 100644 --- a/services/admin_service/controllers/payment_channel.py +++ b/services/admin_service/controllers/payment_channel.py @@ -1,10 +1,11 @@ from fastapi import APIRouter, Depends, Query, Body -from pydantic import config from sqlalchemy.orm import Session from services.common.database import get_db from services.common.utils.response_utils import ResponseUtils from services.admin_service.services.payment_channel_service import PaymentChannelService +from services.common.utils.secure_config import decrypt_config, encrypt_config +from services.admin_service.tasks.order_monitor_task import OrderMonitorTask import json router = APIRouter() @@ -27,10 +28,9 @@ async def payment_channel_list( result = [] for item in list: enable = item.status == 1 - try: - cfg = json.loads(item.config) - except: - cfg = {} + cfg = {} + if item.config: + cfg = decrypt_config(item.config) or {} result.append( { "id": item.id, @@ -56,14 +56,16 @@ async def payment_channel_enable( if data: if id == "alipay": - from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask - alipay_monitor_task = AlipayOrderMonitorTask.get_instance() - alipay_monitor_task.start_monitor() + monitor = OrderMonitorTask.get_instance() + # Ensure monitor is running and enable Alipay client + monitor.start_monitor() + monitor.enable_client("alipay") + cfg = decrypt_config(data.config) if data.config else {} return ResponseUtils.success( { "id": id, "name": data.name, - "config": data.config, + "config": cfg or {}, "is_enabled": data.status == 1, "updated_time": data.updated_at, } @@ -83,14 +85,15 @@ async def payment_channel_disable( data = payment_channel_service.update_status(id, 0) if data: if id == "alipay": - from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask - alipay_monitor_task = AlipayOrderMonitorTask.get_instance() - alipay_monitor_task.stop_monitor() + monitor = OrderMonitorTask.get_instance() + # Disable Alipay client without stopping global monitor + monitor.disable_client("alipay") + cfg = decrypt_config(data.config) if data.config else {} return ResponseUtils.success( { "id": id, "name": data.name, - "config": data.config, + "config": cfg or {}, "is_enabled": data.status == 1, "updated_time": data.updated_at, } @@ -109,8 +112,12 @@ async def payment_channel_config( return ResponseUtils.error("Payment channel id cannot be empty") config = body.get("config") if config: - configStr = json.dumps(config) - data = payment_channel_service.update_config(id=id, config=configStr) + # Encrypt config before persisting to DB + try: + encrypted = encrypt_config(config) + except Exception as e: + return ResponseUtils.error(f"Failed to encrypt config: {str(e)}") + data = payment_channel_service.update_config(id=id, config=encrypted) if data: # Convert str to object return ResponseUtils.success( diff --git a/services/admin_service/services/payment_channel_service.py b/services/admin_service/services/payment_channel_service.py index 17336ef..157dbae 100644 --- a/services/admin_service/services/payment_channel_service.py +++ b/services/admin_service/services/payment_channel_service.py @@ -6,6 +6,7 @@ from services.common.database import SessionLocal from datetime import datetime from services.admin_service.repositories.payment_channel_repository import PaymentChannelRepository from services.common.models.payment_channel import PaymentChannel +from services.common.utils.secure_config import decrypt_config logger = logging.getLogger(__name__) @@ -35,13 +36,14 @@ class PaymentChannelService: channel_config = self.payment_channel_repository.payment_channel_get(id) if channel_config is None: return None + # Support encrypted-at-rest config config = {} - if channel_config.config is not None: - try: - config = json.loads(channel_config.config) - except json.JSONDecodeError as e: - logger.error(f"Failed to parse payment channel config JSON: {str(e)}") + if channel_config.config: + cfg = decrypt_config(channel_config.config) + if cfg is None: + logger.error("Failed to decrypt or parse payment channel config") return None + config = cfg config["enable"] = channel_config.status == 1 config["id"] = channel_config.id return config @@ -64,19 +66,17 @@ class PaymentChannelService: logger.warning("Stripe payment channel config is empty") return None - # Parse config JSON - try: - config = json.loads(stripe_channel.config) - # Validate required fields - if not config.get("secret") or not config.get("webhook_secret"): - logger.warning("Stripe config missing required fields: secret or webhook_secret") - return None - - logger.info("Successfully retrieved Stripe config") - return config - except json.JSONDecodeError as e: - logger.error(f"Failed to parse Stripe config JSON: {str(e)}") + # Decrypt/parse config JSON + config = decrypt_config(stripe_channel.config) + if config is None: + logger.error("Failed to decrypt Stripe config") return None + # Validate required fields + if not config.get("secret") or not config.get("webhook_secret"): + logger.warning("Stripe config missing required fields: secret or webhook_secret") + return None + logger.info("Successfully retrieved Stripe config") + return config except Exception as e: logger.error(f"Failed to get Stripe config: {str(e)}") diff --git a/services/api_service/utils/mcp_event_store.py b/services/api_service/utils/mcp_event_store.py index 45732ec..48360f3 100644 --- a/services/api_service/utils/mcp_event_store.py +++ b/services/api_service/utils/mcp_event_store.py @@ -1,4 +1,6 @@ import json +import asyncio +from typing import List, cast from mcp.server.streamable_http import ( EventStore, @@ -16,9 +18,9 @@ class RedisEventStore(EventStore): self.namespace = namespace self.ttl_seconds = ttl_seconds - # Typed helpers to normalize Redis sync results + # Synchronous helpers; wrap at call sites to avoid blocking def _rpush(self, key: str, value: str) -> int: - return int(redis_client.client.rpush(key, value)) + return cast(int, redis_client.client.rpush(key, value)) def _expire(self, key: str, seconds: int) -> None: try: @@ -28,12 +30,12 @@ class RedisEventStore(EventStore): pass def _llen(self, key: str) -> int: - return int(redis_client.client.llen(key) or 0) + return cast(int, redis_client.client.llen(key)) - def _lrange(self, key: str, start: int, end: int) -> list[str]: - items = redis_client.client.lrange(key, int(start), int(end)) - # decode_responses=True ensures str, but cast defensively - return [str(i) for i in (items or [])] + def _lrange(self, key: str, start: int, end: int) -> List[str]: + raw = redis_client.client.lrange(key, int(start), int(end)) + items: List[str] = cast(List[str], raw or []) + return [str(i) for i in items] def _key(self, stream_id: StreamId) -> str: return f"xpack:mcp:event:{self.namespace}:{stream_id}" @@ -44,10 +46,10 @@ class RedisEventStore(EventStore): async def store_event(self, stream_id: StreamId, message: JSONRPCMessage) -> EventId: key = self._key(stream_id) payload = json.dumps(message.model_dump(by_alias=True, exclude_none=True)) - # Redis list append is synchronous - seq: int = self._rpush(key, payload) + # Append to Redis list via thread wrapper to avoid blocking + seq: int = await asyncio.to_thread(self._rpush, key, payload) # rpush returns new length; sequence index is length-1 - self._expire(key, self.ttl_seconds) + await asyncio.to_thread(self._expire, key, self.ttl_seconds) return self._event_id(stream_id, seq - 1) async def replay_events_after( @@ -65,7 +67,7 @@ class RedisEventStore(EventStore): key = self._key(stream_id) try: - length: int = self._llen(key) + length: int = await asyncio.to_thread(self._llen, key) except Exception: # Redis unavailable or key type mismatch; cannot replay return stream_id @@ -74,7 +76,7 @@ class RedisEventStore(EventStore): # Fetch range [start_idx, length-1] try: - items: list[str] = self._lrange(key, start_idx, length - 1) + items: list[str] = await asyncio.to_thread(self._lrange, key, start_idx, length - 1) except Exception: return stream_id for item in items: diff --git a/services/common/models/payment_channel.py b/services/common/models/payment_channel.py index eafba93..aa7dfc2 100644 --- a/services/common/models/payment_channel.py +++ b/services/common/models/payment_channel.py @@ -14,5 +14,6 @@ class PaymentChannel(Base): id: Mapped[str] = mapped_column(String(36), primary_key=True, autoincrement=False, comment="Primary key") name: Mapped[str] = mapped_column(String(255), nullable=False, comment="Channel name") status: Mapped[int] = mapped_column(Integer, nullable=False, comment="Channel status, 0: disabled, 1: enabled") - config: Mapped[str] = mapped_column(Text, nullable=True, comment="Channel config") + # Store encrypted JSON envelope for channel configuration (AES-GCM). See secure_config.py + config: Mapped[str] = mapped_column(Text, nullable=True, comment="Channel config (encrypted envelope JSON)") updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=True, comment="Update time") diff --git a/services/common/redis.py b/services/common/redis.py index 9d6e8c0..87cfe82 100644 --- a/services/common/redis.py +++ b/services/common/redis.py @@ -1,4 +1,5 @@ import redis +from redis import Redis from typing import Optional, Any from .config import Config @@ -9,7 +10,7 @@ class RedisClient: def __init__(self): """Initialize Redis connection""" try: - self.client = redis.Redis( + self.client: Redis = redis.Redis( host=Config.REDIS_HOST, port=Config.REDIS_PORT, password=Config.REDIS_PASSWORD, diff --git a/services/common/utils/secure_config.py b/services/common/utils/secure_config.py new file mode 100644 index 0000000..6a1545f --- /dev/null +++ b/services/common/utils/secure_config.py @@ -0,0 +1,102 @@ +import os +import json +import base64 +import secrets +from typing import Optional, Any, Dict + +try: + from cryptography.hazmat.primitives.ciphers.aead import AESGCM +except Exception: + AESGCM = None + + +ENC_MARKER = "__enc__" + + +def _get_key() -> bytes: + """Load symmetric encryption key from environment. + + Expects `PAYMENT_CONFIG_SECRET_KEY` to be a base64-encoded 32-byte key. + Optionally supports `PAYMENT_CONFIG_KEY_ID` for key rotation tracking. + """ + key_b64 = os.getenv("PAYMENT_CONFIG_SECRET_KEY", "") + if not key_b64: + raise RuntimeError("Missing PAYMENT_CONFIG_SECRET_KEY environment variable") + try: + key = base64.b64decode(key_b64) + except Exception as e: + raise RuntimeError("Invalid base64 in PAYMENT_CONFIG_SECRET_KEY") from e + if len(key) != 32: + raise RuntimeError("PAYMENT_CONFIG_SECRET_KEY must decode to 32 bytes (AES-256)") + return key + + +def is_encrypted(value: Optional[str]) -> bool: + """Heuristically determine if the stored config string is an encrypted envelope.""" + if not value: + return False + try: + obj = json.loads(value) + return isinstance(obj, dict) and obj.get(ENC_MARKER) is True and "ct" in obj and "nonce" in obj + except Exception: + return False + + +def encrypt_config(config_obj: Dict[str, Any]) -> str: + """Encrypt config object using AES-GCM and return envelope JSON string. + + Envelope format: + { + "__enc__": true, + "v": 1, + "alg": "AESGCM", + "kid": "default", + "nonce": base64, + "ct": base64 + } + """ + if AESGCM is None: + raise RuntimeError("cryptography library is required for encryption") + key = _get_key() + aesgcm = AESGCM(key) + nonce = secrets.token_bytes(12) # AES-GCM standard 96-bit nonce + plaintext = json.dumps(config_obj, ensure_ascii=False).encode("utf-8") + ciphertext = aesgcm.encrypt(nonce, plaintext, None) + envelope = { + ENC_MARKER: True, + "v": 1, + "alg": "AESGCM", + "kid": os.getenv("PAYMENT_CONFIG_KEY_ID", "default"), + "nonce": base64.b64encode(nonce).decode("ascii"), + "ct": base64.b64encode(ciphertext).decode("ascii"), + } + return json.dumps(envelope, ensure_ascii=False) + + +def decrypt_config(value: Optional[str]) -> Optional[Dict[str, Any]]: + """Decrypt envelope if present; otherwise parse plaintext JSON. + + Returns dict on success, or None on failure. + """ + if not value: + return None + # If looks like encrypted envelope, decrypt. + if is_encrypted(value): + if AESGCM is None: + # Cannot decrypt without cryptography + return None + try: + obj = json.loads(value) + key = _get_key() + aesgcm = AESGCM(key) + nonce = base64.b64decode(obj["nonce"]) + ct = base64.b64decode(obj["ct"]) + plaintext = aesgcm.decrypt(nonce, ct, None) + return json.loads(plaintext.decode("utf-8")) + except Exception: + return None + # Fallback: treat as plaintext JSON + try: + return json.loads(value) + except Exception: + return None \ No newline at end of file