AnyProxy不单单能够抓包,还能够拦截请求并修改服务端响应,实现接口mock功能。
面试时候常常会问到第三方支付如何测试这种,若是对接的第三方没提供测试环境,那么就须要搭建一个mock服务器,模拟支付接口返回的各类状况。git
AnyProxy提供了二次开发的能力,你能够用js编写本身的规则模块(rule),来自定义网络请求的处理逻辑。github
注意:引用规则前,请务必确保文件来源可靠,以避免发生安全问题面试
可修改内容包括请求头(request header),请求体(request body),甚至是请求的目标地址等npm
可修改的内容包括http状态码(status code)、响应头(response header)、响应内容等浏览器
本质是中间人攻击(man-in-the-middle attack),须要客户端提早信任AnyProxy生成的CA安全
举个栗子: 须要编写一个规则模块,在 GET http://httpbin.org/user-agent 的返回值里加上测试信息,并延迟5秒返回服务器
Step 1,编写规则以下, 保存为sample.js文件,能够放电脑任意位置网络
// file: sample.js module.exports = { summary: 'a rule to hack response', *beforeSendResponse(requestDetail, responseDetail) { if (requestDetail.url === 'http://httpbin.org/user-agent') { const newResponse = responseDetail.response; newResponse.body += '- AnyProxy Hacked!'; return new Promise((resolve, reject) => { setTimeout(() => { // delay resolve({ response: newResponse }); }, 5000); }); } }, };
Step 2, 启动AnyProxy,加载规则curl
anyproxy -i --rule sample.js测试
当看到出现:Active rule is: a rule to hack response 那就是加载成功了
Step 3, 测试规则
用curl测试
curl http://httpbin.org/user-agent --proxy http://127.0.0.1:8001
也可使用浏览器测试,配置浏览器http代理为 127.0.0.1:8001,访问 http://httpbin.org/user-agent, 通过代理服务器后,指望的返回以下
{ "user-agent": "curl/7.43.0" } - AnyProxy Hacked!
Step 4, 查看请求信息.浏览器访问http://127.0.0.1:8002 ,界面上能看到刚才的请求信息
当http请求通过代理服务器时,具体处理过程是:
-收集请求全部请求参数,包括method, header, body等
当代理服务器收到https请求时,AnyProxy能够替换证书,对请求作明文解析。
以下几种方案均可以用来引用规则模块:
使用本地路径
anyproxy --rule ./rule.js
使用在线地址
anyproxy --rule https://sample.com/rule.js
使用npm包,AnyProxy使用require()加载本地规则,你能够在参数里传入一个本地的npm包路径,或是某个全局安装的npm包
anyproxy --rule ./myRulePkg/ #本地包 npm i -g myRulePkg && anyproxy --rule myRulePkg #全局包
规则模块应该符合cmd规范,一个典型的规则模块代码结构以下。模块中全部方法都是可选的,只需实现业务感兴趣的部分便可。
module.exports = { // 模块介绍 summary: 'my customized rule for AnyProxy', // 发送请求前拦截处理 *beforeSendRequest(requestDetail) { /* ... */ }, // 发送响应前处理 *beforeSendResponse(requestDetail, responseDetail) { /* ... */ }, // 是否处理https请求 *beforeDealHttpsRequest(requestDetail) { /* ... */ }, // 请求出错的事件 *onError(requestDetail, error) { /* ... */ }, // https链接服务器出错 *onConnectError(requestDetail, error) { /* ... */ } };
更多资料参考anyproxy 官方文档https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md