Mitmproxy在商城系统中的实战应用指南
一、商城流量分析场景
1. 核心监控点
graph TD A[用户端] -->|HTTPS流量| B[Mitmproxy] B --> C[商城服务器] C --> B B --> A B --> D[流量分析系统]
2. 典型抓包目标
用户登录 | 加密参数、Session管理 | /api/login |
商品搜索 | 查询参数、返回数据结构 | /api/search?q=手机 |
订单创建 | 请求体校验、支付参数 | /api/order/create |
支付回调 | 签名验证、异步通知 | /api/payment/callback |
二、环境配置技巧
1. 移动端配置
# 启动代理(允许远程连接) mitmweb --listen-host 0.0.0.0 -p 8080 # 手机设置代理(以Android为例) adb shell settings put global http_proxy 电脑IP:8080
2. 证书安装
# 获取证书文件 openssl x509 -in ~/.mitmproxy/mitmproxy-ca-cert.pem -out mitmproxy-ca-cert.crt # 安卓安装证书 adb push mitmproxy-ca-cert.crt /sdcard/ # 然后在设置->安全->安装证书中选择文件
三、请求/响应拦截实战
1. 修改搜索请求
# modify_search.py from mitmproxy import http def request(flow: http.HTTPFlow): if "api/search" in flow.request.path: # 强制添加排序参数 flow.request.query["sort"] = "price_asc" # 修改User-Agent flow.request.headers["User-Agent"] = "Mozilla/5.0 (Mitmproxy Test)"
2. Mock商品数据
# mock_products.py import json from mitmproxy import http def response(flow: http.HTTPFlow): if "/api/product/detail" in flow.request.path: data = { "id": 1001, "name": "测试商品", "price": 999.99, "stock": 1000 } flow.response = http.Response.make( 200, json.dumps(data), {"Content-Type": "application/json"} )
四、性能测试辅助
1. 流量录制与回放
# 录制测试流量 mitmdump -w mall_traffic.mitm -p 8080 # 重放流量(测试服务器性能) mitmdump -n -r mall_traffic.mitm -p 8081
2. 延迟注入测试
# inject_latency.py from mitmproxy import http import time def request(flow: http.HTTPFlow): if "/api/" in flow.request.path: # 模拟网络延迟 time.sleep(1.5) # 1.5秒延迟
五、安全测试案例
1. 参数篡改测试
# test_params.py def request(flow: http.HTTPFlow): if flow.request.method == "POST": try: # 尝试修改价格参数 if "price" in flow.request.text: import json data = json.loads(flow.request.text) data["price"] = 0.01 flow.request.text = json.dumps(data) except: pass
2. 敏感信息检测
# check_sensitive.py import re def response(flow: http.HTTPFlow): # 检测返回中的手机号 phone_pattern = r'1[3-9]\d{9}' if re.search(phone_pattern, flow.response.text): print(f"发现手机号泄露: {flow.request.url}")
六、自动化测试集成
1. 与Pytest结合
# test_checkout.py import pytest import requests @pytest.fixture def proxy(): from mitmproxy.tools.main import mitmdump import threading def run(): mitmdump(["-s", "mock_payment.py", "-p", "8080"]) t = threading.Thread(target=run, daemon=True) t.start() yield # 测试结束自动停止 def test_payment_flow(proxy): proxies = {"http": "http://localhost:8080"} resp = requests.post( "http://mall.com/api/pay", json={"order_id": "TEST123"}, proxies=proxies ) assert resp.json()["status"] == "success"
2. 性能测试脚本
# load_test.py from locust import HttpUser, task class MallUser(HttpUser): def on_start(self): self.proxies = {"http": "http://localhost:8080"} @task def browse_product(self): self.client.get( "/api/product/1001", proxies=self.proxies, verify=False )
七、高级应用场景
1. 优惠券逻辑测试
# test_coupon.py def request(flow: http.HTTPFlow): if "/api/coupon/apply" in flow.request.path: # 修改优惠券金额为最大值 import json data = json.loads(flow.request.text) data["coupon_id"] = "STRESS_TEST_999" flow.request.text = json.dumps(data)
2. 灰度发布验证
# gray_release.py def request(flow: http.HTTPFlow): if "mall.com" in flow.request.host: # 强制访问新版本 flow.request.headers["X-Gray-Release"] = "true"
八、调试与问题排查
1. 常见错误处理
# error_handler.py from mitmproxy import ctx def request(flow): try: # 业务逻辑 if flow.request.method == "PUT": process_put(flow) except Exception as e: ctx.log.error(f"处理请求失败: {flow.request.url} - {str(e)}") flow.response = make_error_response(500)
2. 流量过滤技巧
# filter_traffic.py def request(flow: http.HTTPFlow): # 只处理商城相关域名 if "mall.com" not in flow.request.host: flow.kill() # 排除静态资源 if flow.request.path.startswith("/static/"): flow.kill()
九、最佳实践建议
- 环境隔离:为测试/生产环境使用不同配置
- 敏感数据脱敏:在保存流量时过滤敏感信息
- 自动化脚本管理:按功能拆分脚本文件
- 性能监控:结合日志分析耗时请求
十、完整工作流示例
# 1. 启动代理并加载多个脚本 mitmweb -p 8080 \ -s ~/scripts/auth_monitor.py \ -s ~/scripts/price_alert.py \ --ssl-insecure # 2. 配置手机/浏览器代理 # 3. 执行典型用户操作流程 # 4. 分析Web界面中的请求/响应 # 5. 导出关键流量用于回归测试 mitmdump -nr captured.mitm -w filtered.mitm
通过Mitmproxy在商城系统中可以实现:
- 实时监控API调用情况
- 快速验证前后端数据交互
- 模拟异常场景测试系统容错
- 性能瓶颈定位与分析
- 安全漏洞检测
建议从核心交易链路开始(登录->加购->支付),逐步扩展到全功能测试,最终形成自动化测试体系。
进阶高级测试工程师 文章被收录于专栏
《高级软件测试工程师》专栏旨在为测试领域的从业者提供深入的知识和实践指导,帮助大家从基础的测试技能迈向高级测试专家的行列。 在本专栏中,主要涵盖的内容: 1. 如何设计和实施高效的测试策略; 2. 掌握自动化测试、性能测试和安全测试的核心技术; 3. 深入理解测试驱动开发(TDD)和行为驱动开发(BDD)的实践方法; 4. 测试团队的管理和协作能力。 ——For.Heart