'use strict'; const { app, assert } = require('egg-mock/bootstrap'); const { generateSalt, hashPassword } = require('../../app/lib/password'); const { SCENE_BIND, SCENE_LOGIN, computeSign, newState, saveState, } = require('../../app/lib/wechatGateway'); const APP_KEY = 'gwk_test_oms'; const APP_SECRET = 'gws_test_secret'; const USERNAME = 'wx_test_user'; const OTHER_USERNAME = 'wx_test_other'; const OPENID = 'oXTestOpenid0000000000000001'; const OPENID_OTHER = 'oXTestOpenid0000000000000002'; /** 原始 fetch:用例里会临时替换成假网关,结束后恢复 */ const originalFetch = global.fetch; describe('test/app/wechat.test.js', () => { let userId; let otherUserId; let token; before(async () => { // 清掉上一次执行留下的限流计数,避免重复运行时被 429 拦住 const limitKeys = await app.redis.keys('oms:wx:limit:*'); if (limitKeys.length) await app.redis.del(limitKeys); const salt = generateSalt(); const user = await app.model.User.create({ username: USERNAME, password: hashPassword('test123456', salt), salt, status: 1, }); userId = user.id; const other = await app.model.User.create({ username: OTHER_USERNAME, password: hashPassword('test123456', salt), salt, status: 1, }); otherUserId = other.id; token = app.jwt.sign({ user_id: userId }, app.config.jwt.secret, { expiresIn: '2h' }); }); after(async () => { await app.model.UserWechatBind.destroy({ where: { user_id: [ userId, otherUserId ] } }); await app.model.User.destroy({ where: { username: [ USERNAME, OTHER_USERNAME ] } }); global.fetch = originalFetch; }); /** * 组装一条合法的网关通知报文 * @param {Object} overrides 需要覆盖的字段 * @return {Object} 带签名的通知报文 */ function buildNotify(overrides = {}) { const body = { event: SCENE_LOGIN, appId: 1, appKey: APP_KEY, scene: SCENE_LOGIN, userId: 12, openid: OPENID, unionid: null, bindCode: null, tempCode: 'temp-code', state: '', timestamp: Date.now(), nonce: 'nonce123', ...overrides, }; body.sign = computeSign(APP_SECRET, body); return body; } describe('未配置网关', () => { it('should report disabled when appKey / appSecret missing', async () => { const res = await app.httpRequest() .get('/api/auth/wechat/enabled') .expect(200); assert(res.body.data.enabled === false); }); it('should 400 when apply login qrcode without config', async () => { const res = await app.httpRequest() .post('/api/auth/wechat/login/code') .expect(400); assert(res.body.code === 400); assert(/未配置微信登录网关/.test(res.body.message)); }); }); describe('已配置网关', () => { let original; beforeEach(() => { original = { ...app.config.wechatGateway }; Object.assign(app.config.wechatGateway, { baseUrl: 'https://gateway.test', appKey: APP_KEY, appSecret: APP_SECRET, }); }); afterEach(() => { Object.assign(app.config.wechatGateway, original); }); it('should 401 when bind qrcode requested without token', async () => { await app.httpRequest() .post('/api/auth/wechat/bind/code') .expect(401); }); it('should apply login qrcode and expose page url only', async () => { global.fetch = async () => ({ status: 200, text: async () => JSON.stringify({ code: 0, data: { appId: 1, appKey: APP_KEY, scene: SCENE_LOGIN, tempCode: 'temp-code-1', expiresIn: 600, state: 'ignored', pageUrl: 'https://gateway.test/#/auth?code=temp-code-1', }, }), }); const res = await app.httpRequest() .post('/api/auth/wechat/login/code') .expect(200); const data = res.body.data; assert(data.page_url === 'https://gateway.test/#/auth?code=temp-code-1'); assert(data.temp_code === 'temp-code-1'); assert(data.scene === SCENE_LOGIN); assert(data.state && data.state.length === 32); // 密钥绝不能出现在响应里 assert(!JSON.stringify(res.body).includes(APP_SECRET)); }); it('should 400 when gateway rejects credentials', async () => { global.fetch = async () => ({ status: 401, text: async () => JSON.stringify({ code: 40103, message: '应用凭证不正确' }), }); const res = await app.httpRequest() .post('/api/auth/wechat/login/code') .expect(400); assert(/应用凭证/.test(res.body.message)); }); it('should 429 when login qrcode requested too frequently', async () => { global.fetch = async () => ({ status: 200, text: async () => JSON.stringify({ code: 0, data: { tempCode: 'temp-code-2', pageUrl: 'https://gateway.test/#/auth?code=temp-code-2', expiresIn: 600 }, }), }); const keys = await app.redis.keys('oms:wx:limit:*'); if (keys.length) await app.redis.del(keys); Object.assign(app.config.wechatGateway, { loginLimitPerIp: 1, loginLimitWindow: 60 }); await app.httpRequest() .post('/api/auth/wechat/login/code') .expect(200); const res = await app.httpRequest() .post('/api/auth/wechat/login/code') .expect(429); assert(res.body.code === 429); }); it('should 401 when notify signature is invalid', async () => { const state = newState(); await saveState(app, state, { scene: SCENE_BIND, user_id: userId }); const body = buildNotify({ event: SCENE_BIND, scene: SCENE_BIND, state, openid: OPENID }); body.sign = 'deadbeef'; const res = await app.httpRequest() .post('/api/wx/notify') .send(body) .expect(401); assert(res.body.code === 401); }); it('should 401 when notify timestamp is expired', async () => { const state = newState(); await saveState(app, state, { scene: SCENE_BIND, user_id: userId }); const body = buildNotify({ event: SCENE_BIND, scene: SCENE_BIND, state, openid: OPENID, timestamp: Date.now() - 10 * 60 * 1000, }); await app.httpRequest() .post('/api/wx/notify') .send(body) .expect(401); }); it('should bind wechat and reflect it in bind info', async () => { const state = newState(); await saveState(app, state, { scene: SCENE_BIND, user_id: userId }); await app.httpRequest() .post('/api/wx/notify') .send(buildNotify({ event: SCENE_BIND, scene: SCENE_BIND, state, openid: OPENID })) .expect(200); const status = await app.httpRequest() .get(`/api/auth/wechat/bind/status?state=${state}`) .set('Authorization', `Bearer ${token}`) .expect(200); assert(status.body.data.status === 'success'); const info = await app.httpRequest() .get('/api/auth/wechat/bind') .set('Authorization', `Bearer ${token}`) .expect(200); assert(info.body.data.bound === true); assert(info.body.data.bind_scene === SCENE_BIND); // openid 只返回脱敏值 assert(!info.body.data.openid.includes(OPENID.slice(6, -4))); const bind = await app.model.UserWechatBind.findOne({ where: { user_id: userId } }); assert(bind.openid === OPENID); assert(bind.gateway_uid === 12); }); it('should 409 when the same openid is bound by another account', async () => { const state = newState(); await saveState(app, state, { scene: SCENE_BIND, user_id: otherUserId }); await app.httpRequest() .post('/api/wx/notify') .send(buildNotify({ event: SCENE_BIND, scene: SCENE_BIND, state, openid: OPENID })) .expect(409); const status = await app.httpRequest() .get(`/api/auth/wechat/bind/status?state=${state}`) .set('Authorization', `Bearer ${token}`) .expect(400); // 会话属于 otherUser,用当前账号查不到 assert(status.body.code === 400); const caused = await app.model.UserWechatBind.findOne({ where: { user_id: otherUserId } }); assert(!caused); }); it('should 409 when login with unbound openid', async () => { const state = newState(); await saveState(app, state, { scene: SCENE_LOGIN, user_id: null }); await app.httpRequest() .post('/api/wx/notify') .send(buildNotify({ event: SCENE_LOGIN, scene: SCENE_LOGIN, state, openid: OPENID_OTHER })) .expect(409); const res = await app.httpRequest() .get(`/api/auth/wechat/login/status?state=${state}`) .expect(200); assert(res.body.data.status === 'unbound'); }); it('should login by wechat and issue a working token once', async () => { const state = newState(); await saveState(app, state, { scene: SCENE_LOGIN, user_id: null }); await app.httpRequest() .post('/api/wx/notify') .send(buildNotify({ event: SCENE_LOGIN, scene: SCENE_LOGIN, state, openid: OPENID })) .expect(200); const res = await app.httpRequest() .get(`/api/auth/wechat/login/status?state=${state}`) .expect(200); assert(res.body.data.status === 'success'); assert(res.body.data.user_id === userId); assert(res.body.data.expires_in > 0); const decoded = app.jwt.verify(res.body.data.token, app.config.jwt.secret); assert(decoded.user_id === userId); await app.httpRequest() .get('/api/auth/profile') .set('Authorization', `Bearer ${res.body.data.token}`) .expect(200); // 登录态一次性:同一个 state 再取一次已被消费 const again = await app.httpRequest() .get(`/api/auth/wechat/login/status?state=${state}`) .expect(400); assert(again.body.code === 400); }); it('should unbind wechat', async () => { await app.httpRequest() .delete('/api/auth/wechat/bind') .set('Authorization', `Bearer ${token}`) .expect(200); const info = await app.httpRequest() .get('/api/auth/wechat/bind') .set('Authorization', `Bearer ${token}`) .expect(200); assert(info.body.data.bound === false); // 解绑后该微信无法再扫码登录 const state = newState(); await saveState(app, state, { scene: SCENE_LOGIN, user_id: null }); await app.httpRequest() .post('/api/wx/notify') .send(buildNotify({ event: SCENE_LOGIN, scene: SCENE_LOGIN, state, openid: OPENID })) .expect(409); }); }); });