diff --git a/backend/api-gateway/.env.example b/backend/api-gateway/.env.example new file mode 100644 index 00000000..55b166f5 --- /dev/null +++ b/backend/api-gateway/.env.example @@ -0,0 +1,60 @@ +# ============================================================================= +# API Gateway (Kong) - Environment Configuration +# ============================================================================= +# This file contains all environment variables needed for Kong API Gateway. +# +# Setup Instructions: +# 1. Copy this file: cp .env.example .env +# 2. Update values according to your deployment environment +# 3. Start services: ./deploy.sh up +# +# IMPORTANT: In production, change all default passwords and secrets! +# ============================================================================= + +# ============================================================================= +# Kong Database Configuration +# ============================================================================= +# PostgreSQL password for Kong database +# SECURITY: Change this in production! +KONG_PG_PASSWORD=kong_password + +# ============================================================================= +# Kong Admin GUI Configuration +# ============================================================================= +# Admin GUI URL - Update to match your deployment domain +# Examples: +# Development: http://localhost:8002 +# Production: https://admin.yourdomain.com +KONG_ADMIN_GUI_URL=http://localhost:8002 + +# ============================================================================= +# Monitoring Stack Configuration (Optional) +# ============================================================================= +# Grafana Admin Password +# SECURITY: Change this in production! +GRAFANA_ADMIN_PASSWORD=admin123 + +# Grafana Root URL - Update to match your deployment domain +# Examples: +# Development: http://localhost:3030 +# Production: https://monitor.yourdomain.com +GRAFANA_ROOT_URL=http://localhost:3030 + +# Docker network name for monitoring services +# Note: This should match the network created by docker-compose.yml +NETWORK_NAME=api-gateway_rwa-network + +# ============================================================================= +# Backend Services Configuration +# ============================================================================= +# Backend server IP address for connectivity checks +# IMPORTANT: Update this to the actual IP where your microservices are deployed! +# You MUST also update service URLs in kong.yml to match this IP +# Examples: +# Local development: 127.0.0.1 +# Remote server: 192.168.1.111 +# Same server: 127.0.0.1 +# +# Default is example IP - CHANGE THIS to your actual backend server IP! +# If backend is on same server as Kong, use 127.0.0.1 +BACKEND_SERVER_IP=192.168.1.111 diff --git a/backend/api-gateway/README.md b/backend/api-gateway/README.md index e0424369..7f3cb6cb 100644 --- a/backend/api-gateway/README.md +++ b/backend/api-gateway/README.md @@ -1,15 +1,27 @@ -# API Gateway - Kong +# API Gateway - Kong Deployment Guide RWADurian 项目的 API 网关,基于 Kong 实现。 -## 分布式部署架构 +## 目录 + +- [架构概览](#架构概览) +- [快速开始](#快速开始) +- [环境配置](#环境配置) +- [部署命令](#部署命令) +- [监控](#监控) +- [生产环境部署](#生产环境部署) +- [故障排除](#故障排除) + +## 架构概览 + +### 分布式部署架构 ``` ┌─────────────────────────────────────────────────────────────────────────────────┐ -│ 服务器 192.168.1.100 (网关服务器) │ +│ 网关服务器 │ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │ │ Nginx │ │ Nginx │ │ Nginx │ │ -│ │ rwaadmin:443 │ │ rwaapi:443 │ │ update:443 │ │ +│ │ (Admin Web) │ │ (API SSL) │ │ (Mobile Update) │ │ │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ @@ -20,27 +32,19 @@ RWADurian 项目的 API 网关,基于 Kong 实现。 │ └─────────────────┘ └────────┬────────┘ └─────────────────┘ │ └─────────────────────────────────┼───────────────────────────────────────────────┘ │ - 通过外部 IP (192.168.1.111) 访问 + 通过网络访问后端服务器 │ ▼ ┌─────────────────────────────────────────────────────────────────────────────────┐ -│ 服务器 192.168.1.111 (后端服务器) │ +│ 后端服务器 │ │ │ │ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ │ │identity-service│ │wallet-service │ │backup-service │ │planting-service│ │ │ │ :3000 │ │ :3001 │ │ :3002 │ │ :3003 │ │ │ └───────────────┘ └───────────────┘ └───────────────┘ └───────────────┘ │ │ │ -│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ -│ │referral-service│ │reward-service │ │ mpc-service │ │leaderboard │ │ -│ │ :3004 │ │ :3005 │ │ :3006 │ │ :3007 │ │ -│ └───────────────┘ └───────────────┘ └───────────────┘ └───────────────┘ │ +│ └ ... 更多微服务 ... │ │ │ -│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ -│ │reporting-svc │ │authorization │ │ admin-service │ ┌───────────────┐ │ -│ │ :3008 │ │ :3009 │ │ :3010 │ │presence-service│ │ -│ └───────────────┘ └───────────────┘ └───────────────┘ │ :3011 │ │ -│ └───────────────┘ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Infrastructure │ │ │ │ PostgreSQL / Redis / Kafka / Zookeeper │ │ @@ -69,14 +73,53 @@ api-gateway/ ## 快速开始 -### 1. 先启动后端微服务 +### 1. 配置环境变量 + +```bash +cd backend/api-gateway + +# 创建 .env 文件 +cp .env.example .env + +# 编辑 .env 并根据实际环境修改配置 +nano .env # 或使用你喜欢的编辑器 +``` + +**重要**: 必须修改 `.env` 中的以下配置项: + +```bash +# 修改数据库密码(生产环境必须) +KONG_PG_PASSWORD=your_secure_password_here + +# 更新后端服务器 IP(根据实际部署修改) +BACKEND_SERVER_IP=192.168.1.111 # 改为实际后端服务器IP + +# 如需监控,修改 Grafana 配置 +GRAFANA_ADMIN_PASSWORD=secure_password +GRAFANA_ROOT_URL=https://monitor.yourdomain.com +``` + +### 2. 修改 Kong 路由配置 + +编辑 `kong.yml`,更新后端服务的 URL: + +```bash +# 批量替换后端服务器 IP(如果不是 192.168.1.111) +sed -i 's/192.168.1.111/YOUR_BACKEND_IP/g' kong.yml +``` + +### 3. 先启动后端微服务 + +**在后端服务器上**执行: ```bash cd backend/services ./deploy.sh up ``` -### 2. 启动 Kong API Gateway +### 4. 启动 Kong API Gateway + +**在网关服务器上**执行: ```bash cd backend/api-gateway @@ -84,28 +127,98 @@ chmod +x deploy.sh ./deploy.sh up ``` -### 3. 配置 Nginx + SSL (生产环境) +### 5. 验证部署 + +```bash +# 检查Kong状态 +./deploy.sh status + +# 健康检查 +./deploy.sh health + +# 查看路由 +./deploy.sh routes + +# 测试API +curl http://localhost:8000/api/v1/versions +``` + +### 6. 配置 Nginx + SSL (生产环境,可选) ```bash cd nginx sudo chmod +x install.sh -sudo ./install.sh +sudo ./install.sh yourdomain.com ``` -## 部署脚本命令 +## 环境配置 + +所有配置通过 `.env` 文件管理。参考 `.env.example` 了解所有可用选项。 + +### 环境变量说明 + +| 变量名 | 说明 | 默认值 | 是否必需 | +|--------|------|--------|----------| +| `KONG_PG_PASSWORD` | Kong 数据库密码 | `kong_password` | 是 | +| `KONG_ADMIN_GUI_URL` | 管理界面URL | `http://localhost:8002` | 否 | +| `GRAFANA_ADMIN_PASSWORD` | Grafana 管理密码 | `admin123` | 否* | +| `GRAFANA_ROOT_URL` | Grafana 公开URL | `http://localhost:3030` | 否* | +| `NETWORK_NAME` | Docker 网络名称 | `api-gateway_rwa-network` | 否 | +| `BACKEND_SERVER_IP` | 后端服务器IP | `127.0.0.1` | 否 | + +\* 仅在使用监控时需要 + +### 生成安全密码 + +```bash +# 生成数据库密码 +openssl rand -base64 32 + +# 生成 Grafana 密码 +openssl rand -base64 24 +``` + +## 部署命令 + +### 基础操作 ```bash ./deploy.sh up # 启动 Kong 网关 ./deploy.sh down # 停止 Kong 网关 ./deploy.sh restart # 重启 Kong 网关 -./deploy.sh logs # 查看日志 -./deploy.sh status # 查看状态 -./deploy.sh health # 健康检查 -./deploy.sh reload # 重载 Kong 配置 +./deploy.sh logs # 查看日志 (实时) +./deploy.sh status # 查看服务状态 +``` + +### 配置管理 + +```bash +./deploy.sh reload # 重载 Kong 配置 (从 kong.yml) +./deploy.sh sync # 同步配置到数据库 (同 reload) +``` + +### 健康检查与监控 + +```bash +./deploy.sh health # Kong 健康检查 ./deploy.sh routes # 查看所有路由 ./deploy.sh services # 查看所有服务 ./deploy.sh test # 测试 API 路由 -./deploy.sh clean # 清理容器和数据 +./deploy.sh metrics # 查看 Prometheus 指标 +``` + +### 监控栈管理 + +```bash +./deploy.sh monitoring up # 启动 Prometheus + Grafana +./deploy.sh monitoring down # 停止监控服务 +./deploy.sh monitoring install [domain] # 完整安装 (Nginx+SSL+监控) +``` + +### 清理 + +```bash +./deploy.sh clean # 清理容器和数据 (警告:会删除数据!) ``` ## API 路由表 @@ -149,75 +262,124 @@ sudo ./install.sh | file-log | 请求日志记录 | | request-size-limiting | 请求大小限制 (50MB) | +## 监控 + +### 启动监控栈 + +```bash +# 启动 Prometheus + Grafana +./deploy.sh monitoring up +``` + +### 访问监控服务 + +启动后可以访问: + +- **Grafana**: http://localhost:3030 + - 用户名: `admin` + - 密码: 在 `.env` 中配置 (`GRAFANA_ADMIN_PASSWORD`) + +- **Prometheus**: http://localhost:9099 + +- **Kong 指标**: http://localhost:8001/metrics + +### 查看指标 + +```bash +# 快速查看关键指标 +./deploy.sh metrics +``` + +### 配置告警 (可选) + +在 Grafana 中可以配置告警规则,监控: +- 请求率 +- 错误率 (4xx, 5xx) +- 延迟 (p50, p95, p99) +- Kong 健康状态 + ## 生产环境部署 +### 部署前检查清单 + +- [ ] 修改 `.env` 中的所有默认密码 +- [ ] 更新 `.env` 中的 `BACKEND_SERVER_IP` 为实际后端服务器IP +- [ ] 更新 `kong.yml` 中的后端服务URL (替换IP地址) +- [ ] 配置 SSL/TLS 证书 (如使用 HTTPS) +- [ ] 设置 PostgreSQL 数据库备份 +- [ ] 配置防火墙规则 +- [ ] 启用监控栈 +- [ ] 配置日志聚合 + ### 分布式部署流程 -**服务器规划:** -- 192.168.1.100: 网关服务器 (Nginx + Kong + 前端) -- 192.168.1.111: 后端服务器 (微服务 + 基础设施) +**服务器规划示例:** +- 服务器A: 网关服务器 (Nginx + Kong + 前端) +- 服务器B: 后端服务器 (微服务 + 基础设施) -**步骤 1: 在后端服务器 (192.168.1.111) 部署微服务** +**步骤 1: 在后端服务器部署微服务** ```bash # 克隆代码 git clone /opt/rwadurian -cd /opt/rwadurian +cd /opt/rwadurian/backend/services # 配置环境变量 -cp backend/services/.env.example backend/services/.env -# 编辑 .env 文件 +cp .env.example .env +nano .env # 配置生产环境参数 -# 启动基础设施和微服务 -cd backend/services +# 启动服务 ./deploy.sh up -# 确保防火墙开放端口 3000-3011 +# 开放防火墙端口 3000-3011 (根据实际微服务数量) +sudo ufw allow 3000:3011/tcp ``` -**步骤 2: 在网关服务器 (192.168.1.100) 部署 Kong** +**步骤 2: 在网关服务器部署 Kong** ```bash # 克隆代码 git clone /opt/rwadurian -cd /opt/rwadurian +cd /opt/rwadurian/backend/api-gateway -# 修改 kong.yml 中的后端服务器 IP(如有变化) -# 默认配置为 192.168.1.111 +# 配置环境变量 +cp .env.example .env +nano .env # 配置 BACKEND_SERVER_IP 等参数 -# 启动 Kong API Gateway -cd backend/api-gateway +# 修改 kong.yml 中的后端服务器地址 +nano kong.yml # 更新服务URL中的IP地址 +# 或使用 sed: sed -i 's/OLD_IP/NEW_IP/g' kong.yml + +# 启动 Kong ./deploy.sh up -# 配置 Nginx + SSL -cd nginx -sudo ./install.sh - -# 验证 -curl https://rwaapi.szaiai.com/api/v1/versions +# 验证连接 +./deploy.sh health +./deploy.sh test ``` -### 修改后端服务器 IP - -如果后端服务器 IP 不是 192.168.1.111,需要修改 `kong.yml`: +**步骤 3: 配置 Nginx + SSL (可选)** ```bash -# 批量替换 IP 地址 -sed -i 's/192.168.1.111/YOUR_BACKEND_IP/g' kong.yml +cd nginx +sudo ./install.sh yourdomain.com + +# 验证HTTPS +curl https://yourdomain.com/api/v1/versions ``` ### 服务依赖关系 ``` -后端服务器 (192.168.1.111): +后端服务器: 1. Infrastructure (PostgreSQL, Redis, Kafka) ↓ - 2. Application Services (identity, wallet, admin, etc.) + 2. Application Services (微服务) -网关服务器 (192.168.1.100): - 3. Kong API Gateway (通过 IP 访问后端) +网关服务器: + 3. Kong API Gateway (通过网络访问后端) ↓ - 4. Nginx (SSL 终结) + 4. Nginx (SSL 终结, 可选) ``` ## 管理命令 diff --git a/backend/api-gateway/deploy.sh b/backend/api-gateway/deploy.sh index aa2841d6..fe2bc9f5 100644 --- a/backend/api-gateway/deploy.sh +++ b/backend/api-gateway/deploy.sh @@ -25,6 +25,12 @@ YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' +# 日志函数 +log_info() { echo -e "${BLUE}[INFO]${NC} $1"; } +log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; } +log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } +log_error() { echo -e "${RED}[ERROR]${NC} $1"; } + # 项目信息 PROJECT_NAME="rwa-api-gateway" KONG_ADMIN_URL="http://localhost:8001" @@ -36,11 +42,22 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # 切换到脚本所在目录 cd "$SCRIPT_DIR" -# 日志函数 -log_info() { echo -e "${BLUE}[INFO]${NC} $1"; } -log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; } -log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } -log_error() { echo -e "${RED}[ERROR]${NC} $1"; } +# 加载环境变量 +if [ -f ".env" ]; then + log_info "Loading environment from .env file" + set -a + source .env + set +a +elif [ -f ".env.example" ]; then + log_warn ".env file not found!" + log_warn "Creating .env from .env.example..." + cp .env.example .env + log_error "Please edit .env file to configure your environment, then run again" + exit 1 +else + log_error "Neither .env nor .env.example found!" + exit 1 +fi # 检查 Docker check_docker() { diff --git a/backend/api-gateway/docker-compose.monitoring.yml b/backend/api-gateway/docker-compose.monitoring.yml index db59357b..4cf9d6db 100644 --- a/backend/api-gateway/docker-compose.monitoring.yml +++ b/backend/api-gateway/docker-compose.monitoring.yml @@ -34,10 +34,10 @@ services: container_name: rwa-grafana environment: - GF_SECURITY_ADMIN_USER=admin - - GF_SECURITY_ADMIN_PASSWORD=admin123 + - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD:-admin123} - GF_USERS_ALLOW_SIGN_UP=false # 反向代理支持 - - GF_SERVER_ROOT_URL=https://monitor.szaiai.com + - GF_SERVER_ROOT_URL=${GRAFANA_ROOT_URL:-http://localhost:3030} - GF_SERVER_SERVE_FROM_SUB_PATH=false volumes: - grafana_data:/var/lib/grafana @@ -59,4 +59,4 @@ volumes: networks: rwa-network: external: true - name: api-gateway_rwa-network + name: ${NETWORK_NAME:-api-gateway_rwa-network} diff --git a/backend/api-gateway/docker-compose.yml b/backend/api-gateway/docker-compose.yml index 9b71b89b..bd3775ca 100644 --- a/backend/api-gateway/docker-compose.yml +++ b/backend/api-gateway/docker-compose.yml @@ -67,7 +67,7 @@ services: KONG_PROXY_ERROR_LOG: /dev/stderr KONG_ADMIN_ERROR_LOG: /dev/stderr KONG_ADMIN_LISTEN: 0.0.0.0:8001 - KONG_ADMIN_GUI_URL: http://localhost:8002 + KONG_ADMIN_GUI_URL: ${KONG_ADMIN_GUI_URL:-http://localhost:8002} ports: - "8000:8000" # Proxy HTTP - "8443:8443" # Proxy HTTPS diff --git a/backend/mpc-system/.env.example b/backend/mpc-system/.env.example index f7b22dec..d7bfb874 100644 --- a/backend/mpc-system/.env.example +++ b/backend/mpc-system/.env.example @@ -1,52 +1,93 @@ -# MPC-System 环境变量配置 -# 部署位置: 192.168.1.100 (Nginx + MPC 服务器) +# ============================================================================= +# MPC System - Environment Configuration +# ============================================================================= +# This file contains all environment variables needed for MPC System deployment. # -# 使用方法: -# 1. 复制此文件: cp .env.example .env -# 2. 修改为实际生产环境的值 -# 3. 启动: docker compose up -d +# Setup Instructions: +# 1. Copy this file: cp .env.example .env +# 2. Update ALL values according to your production environment +# 3. Generate secure random keys for secrets (see instructions below) +# 4. Start services: ./deploy.sh up +# +# IMPORTANT: This file contains examples only! +# In production, you MUST: +# - Change ALL passwords and keys to secure random values +# - Update ALLOWED_IPS to match your actual backend server IP +# - Keep the .env file secure and NEVER commit it to version control +# ============================================================================= -# ============================================ -# 环境标识 -# ============================================ +# ============================================================================= +# Environment Identifier +# ============================================================================= +# Options: development, staging, production ENVIRONMENT=production -# ============================================ -# PostgreSQL 数据库 -# ============================================ +# ============================================================================= +# PostgreSQL Database Configuration +# ============================================================================= +# Database user (can keep default or customize) POSTGRES_USER=mpc_user -POSTGRES_PASSWORD=your_secure_postgres_password_here -# ============================================ -# Redis 缓存 -# ============================================ -# 留空表示不需要密码 (内部网络) +# Database password +# SECURITY: Generate a strong password in production! +# Example command: openssl rand -base64 32 +POSTGRES_PASSWORD=change_this_to_secure_postgres_password + +# ============================================================================= +# Redis Cache Configuration +# ============================================================================= +# Redis password (leave empty if Redis is only accessible within Docker network) +# For production, consider setting a password for defense in depth +# Example command: openssl rand -base64 24 REDIS_PASSWORD= -# ============================================ -# RabbitMQ 消息队列 -# ============================================ +# ============================================================================= +# RabbitMQ Message Broker Configuration +# ============================================================================= +# RabbitMQ user (can keep default or customize) RABBITMQ_USER=mpc_user -RABBITMQ_PASSWORD=your_secure_rabbitmq_password_here -# ============================================ -# JWT 配置 -# ============================================ -# JWT 签名密钥 (至少 32 字符) -JWT_SECRET_KEY=your_super_secure_jwt_secret_key_at_least_32_characters +# RabbitMQ password +# SECURITY: Generate a strong password in production! +# Example command: openssl rand -base64 32 +RABBITMQ_PASSWORD=change_this_to_secure_rabbitmq_password -# ============================================ -# 加密配置 -# ============================================ -# 主加密密钥 (64 位十六进制字符 = 256 位密钥) -# 用于加密存储的密钥分片 +# ============================================================================= +# JWT Configuration +# ============================================================================= +# JWT signing secret key (minimum 32 characters) +# SECURITY: Generate a strong random key in production! +# Example command: openssl rand -base64 48 +JWT_SECRET_KEY=change_this_jwt_secret_key_to_random_value_min_32_chars + +# ============================================================================= +# Cryptography Configuration +# ============================================================================= +# Master encryption key for encrypting stored key shares +# MUST be exactly 64 hexadecimal characters (256-bit key) +# SECURITY: Generate a secure random key in production! +# Example command: openssl rand -hex 32 +# WARNING: If you lose this key, encrypted shares cannot be recovered! CRYPTO_MASTER_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef -# ============================================ -# API 安全配置 -# ============================================ -# API 认证密钥 (与后端服务器的 mpc-service 配置一致) -MPC_API_KEY=your_very_secure_api_key_at_least_32_characters +# ============================================================================= +# API Security Configuration +# ============================================================================= +# API authentication key for server-to-server communication +# This key must match the MPC_API_KEY in your backend mpc-service configuration +# SECURITY: Generate a strong random key and keep it synchronized! +# Example command: openssl rand -base64 48 +MPC_API_KEY=change_this_api_key_to_match_your_mpc_service_config -# 允许访问的 IP 地址 (后端服务器) -ALLOWED_IPS=192.168.1.111 +# Allowed IP addresses (comma-separated list) +# Only these IPs can access the MPC system APIs +# IMPORTANT: In production, restrict this to your actual backend server IP(s)! +# Examples: +# Single IP: ALLOWED_IPS=192.168.1.111 +# Multiple IPs: ALLOWED_IPS=192.168.1.111,192.168.1.112 +# Local only: ALLOWED_IPS=127.0.0.1 +# Allow all: ALLOWED_IPS= (empty, relies on API_KEY auth only - NOT RECOMMENDED for production) +# +# Default allows all IPs (protected by API_KEY authentication) +# SECURITY WARNING: Change this in production to specific backend server IP(s)! +ALLOWED_IPS= diff --git a/backend/mpc-system/README.md b/backend/mpc-system/README.md new file mode 100644 index 00000000..29acada0 --- /dev/null +++ b/backend/mpc-system/README.md @@ -0,0 +1,538 @@ +# MPC System Deployment Guide + +Multi-Party Computation (MPC) system for secure threshold signature scheme (TSS) implementation in the RWADurian project. + +## Table of Contents + +- [Overview](#overview) +- [Architecture](#architecture) +- [Quick Start](#quick-start) +- [Configuration](#configuration) +- [Deployment Commands](#deployment-commands) +- [Services](#services) +- [Security](#security) +- [Troubleshooting](#troubleshooting) +- [Production Deployment](#production-deployment) + +## Overview + +The MPC system implements a 2-of-3 threshold signature scheme where: +- 3 server parties hold key shares +- At least 2 parties are required to generate signatures +- User shares are generated dynamically and returned to the calling service +- All shares are encrypted using AES-256-GCM + +### Key Features + +- **Threshold Cryptography**: 2-of-3 TSS for enhanced security +- **Distributed Architecture**: Services communicate via gRPC and WebSocket +- **Secure Storage**: AES-256-GCM encryption for all stored shares +- **API Authentication**: API key and IP-based access control +- **Session Management**: Coordinated multi-party computation sessions + +## Architecture + +``` +┌────────────────────────────────────────────────────────────────┐ +│ MPC System │ +│ │ +│ ┌──────────────────┐ ┌──────────────────┐ │ +│ │ Account Service │ │ Server Party API │ │ +│ │ (Port 4000) │ │ (Port 8083) │ │ +│ │ External API │ │ User Share Gen │ │ +│ └────────┬─────────┘ └────────┬─────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌──────────────────┐ ┌──────────────────┐ │ +│ │ Session │◄──────►│ Message Router │ │ +│ │ Coordinator │ │ (Port 8082) │ │ +│ │ (Port 8081) │ │ WebSocket │ │ +│ └────────┬─────────┘ └────────┬─────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌────────────────────────────────────────────┐ │ +│ │ Server Parties (3 instances) │ │ +│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ +│ │ │ Party 1 │ │ Party 2 │ │ Party 3 │ │ │ +│ │ │ (TSS) │ │ (TSS) │ │ (TSS) │ │ │ +│ │ └──────────┘ └──────────┘ └──────────┘ │ │ +│ └────────────────────────────────────────────┘ │ +│ │ +│ ┌────────────────────────────────────────────┐ │ +│ │ Infrastructure Services │ │ +│ │ PostgreSQL │ Redis │ RabbitMQ │ │ +│ └────────────────────────────────────────────┘ │ +└────────────────────────────────────────────────────────────────┘ + │ + │ Network Access + ▼ + ┌──────────────────────────┐ + │ Backend Services │ + │ mpc-service (caller) │ + └──────────────────────────┘ +``` + +## Quick Start + +### Prerequisites + +- **Docker** (version 20.10+) +- **Docker Compose** (version 2.0+) +- **Network Access** from backend services +- **Ports Available**: 4000, 8081, 8082, 8083 + +### 1. Initial Setup + +```bash +cd backend/mpc-system + +# Create environment configuration +cp .env.example .env + +# Edit configuration for your environment +nano .env +``` + +### 2. Configure Environment + +Edit `.env` and update the following **REQUIRED** values: + +```bash +# Database password (REQUIRED) +POSTGRES_PASSWORD=your_secure_postgres_password + +# RabbitMQ password (REQUIRED) +RABBITMQ_PASSWORD=your_secure_rabbitmq_password + +# JWT secret key (REQUIRED, min 32 chars) +JWT_SECRET_KEY=your_jwt_secret_key_at_least_32_characters + +# Master encryption key (REQUIRED, exactly 64 hex chars) +# WARNING: If you lose this, encrypted shares cannot be recovered! +CRYPTO_MASTER_KEY=$(openssl rand -hex 32) + +# API key for server-to-server auth (REQUIRED) +# Must match the MPC_API_KEY in your backend mpc-service config +MPC_API_KEY=your_api_key_matching_mpc_service + +# Allowed IPs (REQUIRED - update to actual backend server IP!) +ALLOWED_IPS=192.168.1.111 +``` + +### 3. Deploy Services + +```bash +# Start all services +./deploy.sh up + +# Check status +./deploy.sh status + +# View logs +./deploy.sh logs +``` + +### 4. Verify Deployment + +```bash +# Health check +./deploy.sh health + +# Test API +./deploy.sh test-api +``` + +## Configuration + +All configuration is managed through `.env` file. See `.env.example` for complete documentation. + +### Critical Environment Variables + +| Variable | Description | Required | Example | +|----------|-------------|----------|---------| +| `POSTGRES_PASSWORD` | Database password | Yes | `openssl rand -base64 32` | +| `RABBITMQ_PASSWORD` | Message broker password | Yes | `openssl rand -base64 32` | +| `JWT_SECRET_KEY` | JWT signing key (≥32 chars) | Yes | `openssl rand -base64 48` | +| `CRYPTO_MASTER_KEY` | AES-256 key (64 hex chars) | Yes | `openssl rand -hex 32` | +| `MPC_API_KEY` | API authentication key | Yes | `openssl rand -base64 48` | +| `ALLOWED_IPS` | Comma-separated allowed IPs | Yes | `192.168.1.111,192.168.1.112` | +| `ENVIRONMENT` | Environment name | No | `production` (default) | +| `REDIS_PASSWORD` | Redis password | No | Leave empty for internal network | + +### Generating Secure Keys + +```bash +# PostgreSQL & RabbitMQ passwords +openssl rand -base64 32 + +# JWT Secret Key +openssl rand -base64 48 + +# Master Encryption Key (MUST be exactly 64 hex characters) +openssl rand -hex 32 + +# API Key +openssl rand -base64 48 +``` + +### Configuration Checklist + +Before deploying to production: + +- [ ] Change all default passwords +- [ ] Generate secure `CRYPTO_MASTER_KEY` and back it up securely +- [ ] Set `MPC_API_KEY` to match backend mpc-service configuration +- [ ] Update `ALLOWED_IPS` to actual backend server IP(s) +- [ ] Backup `.env` file to secure location (NOT in git!) + +## Deployment Commands + +### Basic Operations + +```bash +./deploy.sh up # Start all services +./deploy.sh down # Stop all services +./deploy.sh restart # Restart all services +./deploy.sh logs [svc] # View logs (all or specific service) +./deploy.sh status # Show service status +./deploy.sh health # Health check all services +``` + +### Build Commands + +```bash +./deploy.sh build # Build Docker images +./deploy.sh build-no-cache # Rebuild without cache +``` + +### Service Management + +```bash +# Infrastructure only +./deploy.sh infra up # Start postgres, redis, rabbitmq +./deploy.sh infra down # Stop infrastructure + +# MPC services only +./deploy.sh mpc up # Start MPC services +./deploy.sh mpc down # Stop MPC services +./deploy.sh mpc restart # Restart MPC services +``` + +### Debugging + +```bash +./deploy.sh logs-tail [service] # Last 100 log lines +./deploy.sh shell [service] # Open shell in container +./deploy.sh test-api # Test Account Service API +``` + +### Cleanup + +```bash +# WARNING: This removes all data! +./deploy.sh clean +``` + +## Services + +### External Services (Exposed Ports) + +| Service | Port | Protocol | Purpose | +|---------|------|----------|---------| +| account-service | 4000 | HTTP | Main API for backend integration | +| session-coordinator | 8081 | HTTP/gRPC | Session coordination | +| message-router | 8082 | WebSocket/gRPC | Message routing | +| server-party-api | 8083 | HTTP | User share generation | + +### Internal Services + +| Service | Purpose | +|---------|---------| +| server-party-1 | TSS party 1 (stores server shares) | +| server-party-2 | TSS party 2 (stores server shares) | +| server-party-3 | TSS party 3 (stores server shares) | +| postgres | Database for session/account data | +| redis | Cache and temporary data | +| rabbitmq | Message broker for inter-service communication | + +### Service Dependencies + +``` +Infrastructure Services (postgres, redis, rabbitmq) + ↓ +Session Coordinator & Message Router + ↓ +Server Parties (1, 2, 3) & Server Party API + ↓ +Account Service (external API) +``` + +## Security + +### Access Control + +1. **IP Whitelisting**: Only IPs in `ALLOWED_IPS` can access the API +2. **API Key Authentication**: Requires valid `MPC_API_KEY` header +3. **Network Isolation**: Services communicate within Docker network + +### Data Protection + +1. **Encryption at Rest**: All shares encrypted with AES-256-GCM +2. **Master Key**: `CRYPTO_MASTER_KEY` must be securely stored and backed up +3. **Secure Transport**: Use HTTPS/TLS for external communication + +### Best Practices + +- **Never commit `.env` to version control** +- **Backup `CRYPTO_MASTER_KEY` to multiple secure locations** +- **Rotate API keys regularly** +- **Use strong passwords (min 32 chars)** +- **Restrict database ports (don't expose to internet)** +- **Monitor failed authentication attempts** +- **Enable audit logging** + +### Key Backup + +```bash +# Backup master key (CRITICAL!) +echo "CRYPTO_MASTER_KEY=$(grep CRYPTO_MASTER_KEY .env | cut -d= -f2)" > master_key.backup + +# Store securely (encrypted USB, password manager, vault) +# NEVER store in plaintext on the server +``` + +## Troubleshooting + +### Services won't start + +```bash +# Check logs +./deploy.sh logs + +# Check specific service +./deploy.sh logs postgres + +# Common issues: +# 1. Ports already in use +# 2. .env file missing or misconfigured +# 3. Database initialization failed +``` + +### Database connection errors + +```bash +# Check postgres health +docker compose ps postgres + +# View postgres logs +./deploy.sh logs postgres + +# Restart infrastructure +./deploy.sh infra down +./deploy.sh infra up +``` + +### API returns 403 Forbidden + +```bash +# Check ALLOWED_IPS configuration +grep ALLOWED_IPS .env + +# Verify caller's IP is in the list +# Update .env and restart: +./deploy.sh restart +``` + +### API returns 401 Unauthorized + +```bash +# Verify MPC_API_KEY matches between: +# 1. This system's .env +# 2. Backend mpc-service configuration + +# Check API key +grep MPC_API_KEY .env + +# Restart after updating +./deploy.sh restart +``` + +### Keygen or signing fails + +```bash +# Check all server parties are healthy +./deploy.sh health + +# View server party logs +./deploy.sh logs server-party-1 +./deploy.sh logs server-party-2 +./deploy.sh logs server-party-3 + +# Check message router +./deploy.sh logs message-router + +# Restart MPC services +./deploy.sh mpc restart +``` + +### Lost master encryption key + +**CRITICAL**: If `CRYPTO_MASTER_KEY` is lost, encrypted shares cannot be recovered! + +Prevention: +- Backup key immediately after generation +- Store in multiple secure locations +- Use enterprise key management system in production + +## Production Deployment + +### Pre-Deployment Checklist + +- [ ] Generate all secure keys and passwords +- [ ] Backup `CRYPTO_MASTER_KEY` to secure locations +- [ ] Configure `ALLOWED_IPS` for actual backend server +- [ ] Sync `MPC_API_KEY` with backend mpc-service +- [ ] Set up database backups +- [ ] Configure log aggregation +- [ ] Set up monitoring and alerts +- [ ] Document recovery procedures +- [ ] Test disaster recovery + +### Deployment Steps + +**Step 1: Prepare Environment** + +```bash +# On MPC server +git clone /opt/rwadurian +cd /opt/rwadurian/backend/mpc-system + +# Configure environment +cp .env.example .env +nano .env # Set all required values + +# Generate and backup keys +openssl rand -hex 32 > master_key.txt +# Copy to secure storage, then delete: +# rm master_key.txt +``` + +**Step 2: Deploy Services** + +```bash +# Build images +./deploy.sh build + +# Start services +./deploy.sh up + +# Verify all healthy +./deploy.sh health +``` + +**Step 3: Configure Firewall** + +```bash +# Allow backend server to access MPC ports +sudo ufw allow from to any port 4000 +sudo ufw allow from to any port 8081 +sudo ufw allow from to any port 8082 +sudo ufw allow from to any port 8083 + +# Deny all other external access +sudo ufw default deny incoming +sudo ufw enable +``` + +**Step 4: Test Integration** + +```bash +# From backend server, test API access +curl -H "X-API-Key: YOUR_MPC_API_KEY" \ + http://:4000/health +``` + +### Monitoring + +Monitor these metrics: + +- Service health status +- API request rate and latency +- Failed authentication attempts +- Database connection pool usage +- RabbitMQ queue depths +- Key generation/signing success rates + +### Backup Strategy + +```bash +# Database backup (daily) +docker compose exec postgres pg_dump -U mpc_user mpc_system > backup_$(date +%Y%m%d).sql + +# Configuration backup +tar -czf config_backup_$(date +%Y%m%d).tar.gz .env kong.yml + +# Encryption key backup (secure storage only!) +``` + +### Disaster Recovery + +1. **Service Failure**: Restart affected service using `./deploy.sh restart` +2. **Database Corruption**: Restore from latest backup +3. **Key Loss**: If `CRYPTO_MASTER_KEY` lost, all encrypted shares are unrecoverable +4. **Full System Recovery**: Redeploy from backups, restore database + +### Performance Tuning + +```yaml +# docker-compose.yml - adjust resources +services: + session-coordinator: + deploy: + resources: + limits: + cpus: '2' + memory: 2G +``` + +## API Reference + +### Account Service API (Port 4000) + +```bash +# Health check +curl http://localhost:4000/health + +# Create account (keygen) +curl -X POST http://localhost:4000/api/v1/accounts \ + -H "X-API-Key: YOUR_MPC_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"user_id": "user123"}' + +# Sign transaction +curl -X POST http://localhost:4000/api/v1/accounts/{account_id}/sign \ + -H "X-API-Key: YOUR_MPC_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"message": "tx_hash"}' +``` + +### Server Party API (Port 8083) + +```bash +# Generate user share +curl -X POST http://localhost:8083/api/v1/shares/generate \ + -H "X-API-Key: YOUR_MPC_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"session_id": "session123"}' +``` + +## Getting Help + +- Check logs: `./deploy.sh logs` +- Health check: `./deploy.sh health` +- View commands: `./deploy.sh help` +- Review `.env.example` for configuration options + +## License + +Copyright © 2024 RWADurian. All rights reserved. diff --git a/backend/mpc-system/deploy.sh b/backend/mpc-system/deploy.sh index 22f0a442..e3da2c0c 100644 --- a/backend/mpc-system/deploy.sh +++ b/backend/mpc-system/deploy.sh @@ -2,8 +2,13 @@ # ============================================================================= # MPC System - Deployment Script # ============================================================================= -# 部署位置: 192.168.1.100 (Nginx + MPC 服务器) -# 对外端口: 4000 (Account Service HTTP) - 供 mpc-service 调用 +# This script manages the MPC System Docker services +# +# External Ports: +# 4000 - Account Service HTTP API +# 8081 - Session Coordinator API +# 8082 - Message Router WebSocket +# 8083 - Server Party API (user share generation) # ============================================================================= set -e @@ -25,14 +30,21 @@ cd "$SCRIPT_DIR" # Load environment if [ -f ".env" ]; then - export $(cat .env | grep -v '^#' | xargs) -elif [ -f ".env.production" ]; then - export $(cat .env.production | grep -v '^#' | xargs) + log_info "Loading environment from .env file" + set -a + source .env + set +a +elif [ ! -f ".env" ] && [ -f ".env.example" ]; then + log_warn ".env file not found. Creating from .env.example" + log_warn "Please edit .env and configure for your environment!" + cp .env.example .env + log_error "Please configure .env file and run again" + exit 1 fi # Core services list CORE_SERVICES="postgres redis rabbitmq" -MPC_SERVICES="session-coordinator message-router server-party-1 server-party-2 server-party-3 account-service" +MPC_SERVICES="session-coordinator message-router server-party-1 server-party-2 server-party-3 server-party-api account-service" ALL_SERVICES="$CORE_SERVICES $MPC_SERVICES" case "$1" in diff --git a/backend/mpc-system/docker-compose.yml b/backend/mpc-system/docker-compose.yml index b8554ce4..33ed63dc 100644 --- a/backend/mpc-system/docker-compose.yml +++ b/backend/mpc-system/docker-compose.yml @@ -1,12 +1,18 @@ +# ============================================================================= # MPC-System Docker Compose Configuration -# 部署位置: 192.168.1.100 (Nginx + MPC 服务器) -# 用途: TSS 密钥生成、签名服务 +# ============================================================================= +# Purpose: TSS (Threshold Signature Scheme) key generation and signing service # -# 启动命令: -# 生产环境: docker compose --env-file .env.production up -d -# 开发环境: docker compose up -d +# Usage: +# Development: docker compose up -d +# Production: docker compose --env-file .env up -d # -# 对外端口: 4000 (Account Service HTTP) - 供 mpc-service (192.168.1.111:3001) 调用 +# External Ports: +# 4000 - Account Service HTTP API (accessed by backend mpc-service) +# 8081 - Session Coordinator API (accessed by backend mpc-service) +# 8082 - Message Router WebSocket (accessed by backend mpc-service) +# 8083 - Server Party API (accessed by backend mpc-service for user share generation) +# ============================================================================= services: # ============================================ @@ -20,7 +26,7 @@ services: environment: POSTGRES_DB: mpc_system POSTGRES_USER: ${POSTGRES_USER:-mpc_user} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-mpc_secret_password} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set in .env} volumes: - postgres-data:/var/lib/postgresql/data - ./migrations:/docker-entrypoint-initdb.d:ro @@ -59,7 +65,7 @@ services: container_name: mpc-rabbitmq environment: RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-mpc_user} - RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-mpc_rabbit_password} + RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set in .env} RABBITMQ_DEFAULT_VHOST: / volumes: - rabbitmq-data:/var/lib/rabbitmq @@ -87,8 +93,7 @@ services: dockerfile: services/session-coordinator/Dockerfile container_name: mpc-session-coordinator ports: - # 对外暴露端口 8081,供 mpc-service 调用 - - "8081:8080" + - "8081:8080" # HTTP API for external access environment: MPC_SERVER_GRPC_PORT: 50051 MPC_SERVER_HTTP_PORT: 8080 @@ -96,7 +101,7 @@ services: MPC_DATABASE_HOST: postgres MPC_DATABASE_PORT: 5432 MPC_DATABASE_USER: ${POSTGRES_USER:-mpc_user} - MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-mpc_secret_password} + MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set} MPC_DATABASE_DBNAME: mpc_system MPC_DATABASE_SSLMODE: disable MPC_REDIS_HOST: redis @@ -105,7 +110,7 @@ services: MPC_RABBITMQ_HOST: rabbitmq MPC_RABBITMQ_PORT: 5672 MPC_RABBITMQ_USER: ${RABBITMQ_USER:-mpc_user} - MPC_RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:-mpc_rabbit_password} + MPC_RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set} MPC_JWT_SECRET_KEY: ${JWT_SECRET_KEY} MPC_JWT_ISSUER: mpc-system depends_on: @@ -132,8 +137,7 @@ services: dockerfile: services/message-router/Dockerfile container_name: mpc-message-router ports: - # 对外暴露端口 8082,供 mpc-service WebSocket 连接 - - "8082:8080" + - "8082:8080" # WebSocket for external connections environment: MPC_SERVER_GRPC_PORT: 50051 MPC_SERVER_HTTP_PORT: 8080 @@ -141,13 +145,13 @@ services: MPC_DATABASE_HOST: postgres MPC_DATABASE_PORT: 5432 MPC_DATABASE_USER: ${POSTGRES_USER:-mpc_user} - MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-mpc_secret_password} + MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set} MPC_DATABASE_DBNAME: mpc_system MPC_DATABASE_SSLMODE: disable MPC_RABBITMQ_HOST: rabbitmq MPC_RABBITMQ_PORT: 5672 MPC_RABBITMQ_USER: ${RABBITMQ_USER:-mpc_user} - MPC_RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:-mpc_rabbit_password} + MPC_RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set} depends_on: postgres: condition: service_healthy @@ -181,7 +185,7 @@ services: MPC_DATABASE_HOST: postgres MPC_DATABASE_PORT: 5432 MPC_DATABASE_USER: ${POSTGRES_USER:-mpc_user} - MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-mpc_secret_password} + MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set} MPC_DATABASE_DBNAME: mpc_system MPC_DATABASE_SSLMODE: disable SESSION_COORDINATOR_ADDR: session-coordinator:50051 @@ -218,7 +222,7 @@ services: MPC_DATABASE_HOST: postgres MPC_DATABASE_PORT: 5432 MPC_DATABASE_USER: ${POSTGRES_USER:-mpc_user} - MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-mpc_secret_password} + MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set} MPC_DATABASE_DBNAME: mpc_system MPC_DATABASE_SSLMODE: disable SESSION_COORDINATOR_ADDR: session-coordinator:50051 @@ -255,7 +259,7 @@ services: MPC_DATABASE_HOST: postgres MPC_DATABASE_PORT: 5432 MPC_DATABASE_USER: ${POSTGRES_USER:-mpc_user} - MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-mpc_secret_password} + MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set} MPC_DATABASE_DBNAME: mpc_system MPC_DATABASE_SSLMODE: disable SESSION_COORDINATOR_ADDR: session-coordinator:50051 @@ -280,9 +284,9 @@ services: restart: unless-stopped # ============================================ - # Server Party API - 用户 Share 生成服务 - # 端口 8083: 供 mpc-service 调用,生成用户的 share 并返回 - # 与其他 server-party 不同,此服务不存储 share,而是直接返回给调用方 + # Server Party API - User Share Generation Service + # Unlike other server-party services, this one returns shares to the caller + # instead of storing them internally # ============================================ server-party-api: build: @@ -290,8 +294,7 @@ services: dockerfile: services/server-party-api/Dockerfile container_name: mpc-server-party-api ports: - # 对外暴露端口 8083,供 mpc-service 调用生成用户 share - - "8083:8080" + - "8083:8080" # HTTP API for user share generation environment: MPC_SERVER_HTTP_PORT: 8080 MPC_SERVER_ENVIRONMENT: ${ENVIRONMENT:-production} @@ -316,8 +319,8 @@ services: restart: unless-stopped # ============================================ - # Account Service - 对外 API 入口 - # 端口 4000: 供 mpc-service (192.168.1.111:3001) 调用 + # Account Service - External API Entry Point + # Main HTTP API for backend mpc-service integration # ============================================ account-service: build: @@ -325,8 +328,7 @@ services: dockerfile: services/account/Dockerfile container_name: mpc-account-service ports: - # 对外暴露端口 4000,供后端服务器 (192.168.1.111) 的 mpc-service 调用 - - "4000:8080" + - "4000:8080" # HTTP API for external access environment: MPC_SERVER_GRPC_PORT: 50051 MPC_SERVER_HTTP_PORT: 8080 @@ -334,7 +336,7 @@ services: MPC_DATABASE_HOST: postgres MPC_DATABASE_PORT: 5432 MPC_DATABASE_USER: ${POSTGRES_USER:-mpc_user} - MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-mpc_secret_password} + MPC_DATABASE_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set} MPC_DATABASE_DBNAME: mpc_system MPC_DATABASE_SSLMODE: disable MPC_REDIS_HOST: redis @@ -343,13 +345,14 @@ services: MPC_RABBITMQ_HOST: rabbitmq MPC_RABBITMQ_PORT: 5672 MPC_RABBITMQ_USER: ${RABBITMQ_USER:-mpc_user} - MPC_RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:-mpc_rabbit_password} + MPC_RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set} MPC_COORDINATOR_URL: session-coordinator:50051 MPC_JWT_SECRET_KEY: ${JWT_SECRET_KEY} # API 认证密钥 (与 mpc-service 配置的 MPC_API_KEY 一致) MPC_API_KEY: ${MPC_API_KEY} - # 允许的来源 IP (后端服务器) - ALLOWED_IPS: ${ALLOWED_IPS:-192.168.1.111} + # Allowed source IPs (backend servers) + # Empty default = allow all (protected by API_KEY). Set in .env for production! + ALLOWED_IPS: ${ALLOWED_IPS:-} depends_on: postgres: condition: service_healthy diff --git a/backend/mpc-system/services/account/Dockerfile b/backend/mpc-system/services/account/Dockerfile index f90d2d4d..e70acc6c 100644 --- a/backend/mpc-system/services/account/Dockerfile +++ b/backend/mpc-system/services/account/Dockerfile @@ -1,15 +1,11 @@ # Build stage FROM golang:1.21-alpine AS builder -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk add --no-cache git ca-certificates -# Set Go proxy for China -ARG GOPROXY=https://goproxy.cn,https://goproxy.io,direct +# Set Go proxy (can be overridden with --build-arg GOPROXY=...) +ARG GOPROXY=https://proxy.golang.org,direct ENV GOPROXY=${GOPROXY} -ENV GOSUMDB=sum.golang.google.cn WORKDIR /app @@ -26,9 +22,6 @@ RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ # Final stage FROM alpine:3.18 -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk --no-cache add ca-certificates curl RUN adduser -D -s /bin/sh mpc diff --git a/backend/mpc-system/services/message-router/Dockerfile b/backend/mpc-system/services/message-router/Dockerfile index 2ab5be2b..2ab31071 100644 --- a/backend/mpc-system/services/message-router/Dockerfile +++ b/backend/mpc-system/services/message-router/Dockerfile @@ -1,15 +1,11 @@ # Build stage FROM golang:1.21-alpine AS builder -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk add --no-cache git ca-certificates -# Set Go proxy for China -ARG GOPROXY=https://goproxy.cn,https://goproxy.io,direct +# Set Go proxy (can be overridden with --build-arg GOPROXY=...) +ARG GOPROXY=https://proxy.golang.org,direct ENV GOPROXY=${GOPROXY} -ENV GOSUMDB=sum.golang.google.cn WORKDIR /app @@ -26,9 +22,6 @@ RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ # Final stage FROM alpine:3.18 -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk --no-cache add ca-certificates curl RUN adduser -D -s /bin/sh mpc diff --git a/backend/mpc-system/services/server-party-api/Dockerfile b/backend/mpc-system/services/server-party-api/Dockerfile index 09e1adf5..d88506e9 100644 --- a/backend/mpc-system/services/server-party-api/Dockerfile +++ b/backend/mpc-system/services/server-party-api/Dockerfile @@ -1,15 +1,11 @@ # Build stage FROM golang:1.21-alpine AS builder -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk add --no-cache git ca-certificates -# Set Go proxy for China -ARG GOPROXY=https://goproxy.cn,https://goproxy.io,direct +# Set Go proxy (can be overridden with --build-arg GOPROXY=...) +ARG GOPROXY=https://proxy.golang.org,direct ENV GOPROXY=${GOPROXY} -ENV GOSUMDB=sum.golang.google.cn WORKDIR /app @@ -26,9 +22,6 @@ RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ # Final stage FROM alpine:3.18 -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk --no-cache add ca-certificates curl RUN adduser -D -s /bin/sh mpc diff --git a/backend/mpc-system/services/server-party/Dockerfile b/backend/mpc-system/services/server-party/Dockerfile index c2b2a5f0..e5f21032 100644 --- a/backend/mpc-system/services/server-party/Dockerfile +++ b/backend/mpc-system/services/server-party/Dockerfile @@ -1,15 +1,11 @@ # Build stage FROM golang:1.21-alpine AS builder -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk add --no-cache git ca-certificates -# Set Go proxy for China -ARG GOPROXY=https://goproxy.cn,https://goproxy.io,direct +# Set Go proxy (can be overridden with --build-arg GOPROXY=...) +ARG GOPROXY=https://proxy.golang.org,direct ENV GOPROXY=${GOPROXY} -ENV GOSUMDB=sum.golang.google.cn WORKDIR /app @@ -26,9 +22,6 @@ RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ # Final stage FROM alpine:3.18 -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - RUN apk --no-cache add ca-certificates curl RUN adduser -D -s /bin/sh mpc diff --git a/backend/mpc-system/services/session-coordinator/Dockerfile b/backend/mpc-system/services/session-coordinator/Dockerfile index d8c17735..bbf335c8 100644 --- a/backend/mpc-system/services/session-coordinator/Dockerfile +++ b/backend/mpc-system/services/session-coordinator/Dockerfile @@ -1,16 +1,12 @@ # Build stage FROM golang:1.21-alpine AS builder -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - # Install dependencies RUN apk add --no-cache git ca-certificates -# Set Go proxy for China (use GOPROXY env from build args if provided) -ARG GOPROXY=https://goproxy.cn,https://goproxy.io,direct +# Set Go proxy (can be overridden with --build-arg GOPROXY=...) +ARG GOPROXY=https://proxy.golang.org,direct ENV GOPROXY=${GOPROXY} -ENV GOSUMDB=sum.golang.google.cn # Set working directory WORKDIR /app @@ -33,9 +29,6 @@ RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ # Final stage FROM alpine:3.18 -# Use Aliyun mirror for Alpine packages (China acceleration) -RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories - # Install ca-certificates and curl for HTTPS and health check RUN apk --no-cache add ca-certificates curl