global-ingest-smoke-test.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import assert from 'node:assert/strict';
  2. import crypto from 'node:crypto';
  3. import fs from 'node:fs';
  4. import os from 'node:os';
  5. import path from 'node:path';
  6. import { spawn } from 'node:child_process';
  7. import { createServer } from 'node:http';
  8. const PORT = 4100;
  9. const BASE = `http://127.0.0.1:${PORT}`;
  10. const ADMIN_KEY = 'relay-smoke-admin';
  11. const CALLBACK_SECRET = 'relay-smoke-callback';
  12. const FMODE_PORT = 4101;
  13. const fmodeServer = createServer((req, res) => {
  14. const authorization = String(req.headers.authorization || '');
  15. const userId = authorization.includes('account-b') ? 'fmode-account-b' : 'fmode-account-a';
  16. res.writeHead(200, { 'Content-Type': 'application/json' });
  17. res.end(JSON.stringify({ data: { userId } }));
  18. });
  19. await new Promise((resolve, reject) => {
  20. fmodeServer.once('error', reject);
  21. fmodeServer.listen(FMODE_PORT, '127.0.0.1', resolve);
  22. });
  23. const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-relay-smoke-'));
  24. const child = spawn(process.execPath, ['dist/server.js'], {
  25. cwd: path.resolve(import.meta.dirname, '..'),
  26. env: {
  27. ...process.env,
  28. PORT: String(PORT),
  29. DB_PATH: path.join(tempRoot, 'relay.db'),
  30. ADMIN_KEY,
  31. UPSTREAM_CALLBACK_SECRET: CALLBACK_SECRET,
  32. RELAY_PUBLIC_URL: BASE,
  33. FMODE_GATEWAY_URL: `http://127.0.0.1:${FMODE_PORT}`,
  34. },
  35. stdio: ['ignore', 'pipe', 'pipe'],
  36. });
  37. async function request(route, { method = 'GET', body, headers = {} } = {}) {
  38. const response = await fetch(`${BASE}${route}`, {
  39. method,
  40. headers: {
  41. ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
  42. ...headers,
  43. },
  44. body: body === undefined ? undefined : JSON.stringify(body),
  45. });
  46. return { response, data: await response.json().catch(() => ({})) };
  47. }
  48. async function waitForHealth() {
  49. const deadline = Date.now() + 15000;
  50. while (Date.now() < deadline) {
  51. try {
  52. const { response } = await request('/api/health');
  53. if (response.ok) return;
  54. } catch {}
  55. await new Promise(resolve => setTimeout(resolve, 150));
  56. }
  57. throw new Error('Relay smoke server did not become healthy');
  58. }
  59. function decrypt(encryptedPayload, privateKeyPem) {
  60. assert.ok(encryptedPayload.startsWith('v2:'));
  61. const envelope = JSON.parse(Buffer.from(encryptedPayload.slice(3), 'base64').toString('utf8'));
  62. const privateKey = crypto.createPrivateKey(privateKeyPem);
  63. const aesKey = crypto.privateDecrypt(
  64. { key: privateKey, oaepHash: 'sha256' },
  65. Buffer.from(envelope.key, 'base64'),
  66. );
  67. const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, Buffer.from(envelope.iv, 'base64'));
  68. decipher.setAuthTag(Buffer.from(envelope.tag, 'base64'));
  69. return Buffer.concat([
  70. decipher.update(Buffer.from(envelope.ciphertext, 'base64')),
  71. decipher.final(),
  72. ]).toString('utf8');
  73. }
  74. try {
  75. await waitForHealth();
  76. const tenantResponse = await request('/api/admin/tenant', {
  77. method: 'POST',
  78. headers: { 'X-Admin-Key': ADMIN_KEY },
  79. body: { name: 'global-ingest-smoke' },
  80. });
  81. assert.equal(tenantResponse.response.status, 200);
  82. const tenant = tenantResponse.data;
  83. const guid = `smoke-guid-${crypto.randomUUID()}`;
  84. const deviceResponse = await request('/api/tenant/device', {
  85. method: 'POST',
  86. headers: { Authorization: `Bearer ${tenant.apiSecret}` },
  87. body: { guid, deviceName: 'smoke-device' },
  88. });
  89. assert.equal(deviceResponse.response.status, 200);
  90. const callbackBody = {
  91. code: 0,
  92. data: [{
  93. guid,
  94. msgUniqueIdentifier: `smoke-${crypto.randomUUID()}`,
  95. msgType: 1,
  96. content: 'x'.repeat(5000),
  97. }],
  98. };
  99. const rawBody = JSON.stringify(callbackBody);
  100. const signature = crypto.createHmac('sha256', CALLBACK_SECRET).update(rawBody).digest('hex');
  101. const ingest = await request('/api/webhook/ingest', {
  102. method: 'POST',
  103. headers: { 'X-Signature': signature },
  104. body: callbackBody,
  105. });
  106. assert.equal(ingest.response.status, 200);
  107. assert.equal(ingest.data.queued, 1);
  108. const duplicate = await request('/api/webhook/ingest', {
  109. method: 'POST',
  110. headers: { 'X-Signature': signature },
  111. body: callbackBody,
  112. });
  113. assert.equal(duplicate.response.status, 200);
  114. assert.equal(duplicate.data.duplicates, 1);
  115. const rawAuthorization = await request('/api/webhook/ingest', {
  116. method: 'POST',
  117. headers: { Authorization: CALLBACK_SECRET },
  118. body: callbackBody,
  119. });
  120. assert.equal(rawAuthorization.response.status, 200);
  121. assert.equal(rawAuthorization.data.duplicates, 1);
  122. const setupProbe = await request('/api/webhook/ingest', {
  123. method: 'POST',
  124. headers: { Authorization: CALLBACK_SECRET },
  125. body: { msg: '设置订阅成功!!', callBackUrl: 'http://relay.example/api/webhook/ingest' },
  126. });
  127. assert.equal(setupProbe.response.status, 200);
  128. assert.equal(setupProbe.data.probe, true);
  129. assert.equal(setupProbe.data.queued, 0);
  130. const poll = await request('/api/relay/poll', {
  131. method: 'POST',
  132. headers: { Authorization: `Bearer ${tenant.apiSecret}` },
  133. body: { guid, batchSize: 10, waitMs: 1000 },
  134. });
  135. assert.equal(poll.response.status, 200);
  136. assert.equal(poll.data.events.length, 1);
  137. const decrypted = JSON.parse(decrypt(poll.data.events[0].encryptedPayload, tenant.privateKey));
  138. assert.equal(decrypted.data[0].guid, guid);
  139. assert.equal(decrypted.data[0].content.length, 5000);
  140. const ack = await request('/api/relay/ack', {
  141. method: 'POST',
  142. headers: { Authorization: `Bearer ${tenant.apiSecret}` },
  143. body: { guid, eventIds: [poll.data.events[0].eventId] },
  144. });
  145. assert.equal(ack.response.status, 200);
  146. assert.equal(ack.data.ackedCount, 1);
  147. const missingGuid = await request('/api/webhook/ingest', {
  148. method: 'POST',
  149. headers: {
  150. 'X-Signature': crypto.createHmac('sha256', CALLBACK_SECRET).update('{}').digest('hex'),
  151. },
  152. body: {},
  153. });
  154. assert.equal(missingGuid.response.status, 400);
  155. const invalidSignature = await request('/api/webhook/ingest', {
  156. method: 'POST',
  157. headers: { 'X-Signature': 'invalid' },
  158. body: callbackBody,
  159. });
  160. assert.equal(invalidSignature.response.status, 401);
  161. const transferGuid = `transfer-guid-${crypto.randomUUID()}`;
  162. const accountTenantResponse = await request('/api/tenant/register', {
  163. method: 'POST',
  164. headers: { Authorization: 'Bearer account-a-token' },
  165. body: { description: 'account-a-owner', deviceGuid: transferGuid },
  166. });
  167. assert.equal(accountTenantResponse.response.status, 200);
  168. const replacementTenantResponse = await request('/api/admin/tenant', {
  169. method: 'POST',
  170. headers: { 'X-Admin-Key': ADMIN_KEY },
  171. body: { name: 'account-a-replacement' },
  172. });
  173. assert.equal(replacementTenantResponse.response.status, 200);
  174. const replacementTenant = replacementTenantResponse.data;
  175. const transfer = await request('/api/tenant/device', {
  176. method: 'POST',
  177. headers: {
  178. Authorization: `Bearer ${replacementTenant.apiSecret}`,
  179. 'X-Fmode-Token': 'account-a-token',
  180. },
  181. body: { guid: transferGuid },
  182. });
  183. assert.equal(transfer.response.status, 200);
  184. const oldTenantStatus = await request('/api/tenant/status', {
  185. headers: { Authorization: `Bearer ${accountTenantResponse.data.apiSecret}` },
  186. });
  187. const replacementStatus = await request('/api/tenant/status', {
  188. headers: { Authorization: `Bearer ${replacementTenant.apiSecret}` },
  189. });
  190. assert.equal(oldTenantStatus.data.devices.some(item => item.guid === transferGuid), false);
  191. assert.equal(replacementStatus.data.devices.some(item => item.guid === transferGuid), true);
  192. const foreignTenantResponse = await request('/api/admin/tenant', {
  193. method: 'POST',
  194. headers: { 'X-Admin-Key': ADMIN_KEY },
  195. body: { name: 'account-b' },
  196. });
  197. const crossAccountTransfer = await request('/api/tenant/device', {
  198. method: 'POST',
  199. headers: {
  200. Authorization: `Bearer ${foreignTenantResponse.data.apiSecret}`,
  201. 'X-Fmode-Token': 'account-b-token',
  202. },
  203. body: { guid: transferGuid },
  204. });
  205. assert.equal(crossAccountTransfer.response.status, 409);
  206. const secondAccountAGuid = `account-a-second-${crypto.randomUUID()}`;
  207. const accountBGuid = `account-b-device-${crypto.randomUUID()}`;
  208. const secondAccountADevice = await request('/api/tenant/device', {
  209. method: 'POST',
  210. headers: {
  211. Authorization: `Bearer ${replacementTenant.apiSecret}`,
  212. 'X-Fmode-Token': 'account-a-token',
  213. },
  214. body: { guid: secondAccountAGuid },
  215. });
  216. const accountBDevice = await request('/api/tenant/device', {
  217. method: 'POST',
  218. headers: {
  219. Authorization: `Bearer ${foreignTenantResponse.data.apiSecret}`,
  220. 'X-Fmode-Token': 'account-b-token',
  221. },
  222. body: { guid: accountBGuid },
  223. });
  224. assert.equal(secondAccountADevice.response.status, 200);
  225. assert.equal(accountBDevice.response.status, 200);
  226. const multiDeviceBody = {
  227. code: 0,
  228. data: [
  229. { guid: transferGuid, cmd: 15000, msgType: 2, msgUniqueIdentifier: `multi-${crypto.randomUUID()}`, msgData: { content: 'account-a-primary' } },
  230. { guid: secondAccountAGuid, cmd: 15000, msgType: 2, msgUniqueIdentifier: `multi-${crypto.randomUUID()}`, msgData: { content: 'account-a-secondary' } },
  231. { guid: accountBGuid, cmd: 15000, msgType: 2, msgUniqueIdentifier: `multi-${crypto.randomUUID()}`, msgData: { content: 'account-b-primary' } },
  232. ],
  233. };
  234. const multiDeviceRaw = JSON.stringify(multiDeviceBody);
  235. const multiDeviceIngest = await request('/api/webhook/ingest', {
  236. method: 'POST',
  237. headers: { 'X-Signature': crypto.createHmac('sha256', CALLBACK_SECRET).update(multiDeviceRaw).digest('hex') },
  238. body: multiDeviceBody,
  239. });
  240. assert.equal(multiDeviceIngest.response.status, 200);
  241. assert.equal(multiDeviceIngest.data.queued, 3);
  242. for (const [deviceGuid, apiSecret, privateKey, expectedContent] of [
  243. [transferGuid, replacementTenant.apiSecret, replacementTenant.privateKey, 'account-a-primary'],
  244. [secondAccountAGuid, replacementTenant.apiSecret, replacementTenant.privateKey, 'account-a-secondary'],
  245. [accountBGuid, foreignTenantResponse.data.apiSecret, foreignTenantResponse.data.privateKey, 'account-b-primary'],
  246. ]) {
  247. const devicePoll = await request('/api/relay/poll', {
  248. method: 'POST',
  249. headers: { Authorization: `Bearer ${apiSecret}` },
  250. body: { guid: deviceGuid, batchSize: 10, waitMs: 1000 },
  251. });
  252. assert.equal(devicePoll.response.status, 200);
  253. assert.equal(devicePoll.data.events.length, 1);
  254. const devicePayload = JSON.parse(decrypt(devicePoll.data.events[0].encryptedPayload, privateKey));
  255. assert.equal(devicePayload.data[0].msgData.content, expectedContent);
  256. }
  257. process.stdout.write(JSON.stringify({
  258. status: 'ok',
  259. globalRouting: true,
  260. largePayloadBytes: 5000,
  261. duplicateProtected: true,
  262. missingGuidRejected: true,
  263. invalidSignatureRejected: true,
  264. sameAccountDeviceTransfer: true,
  265. crossAccountDeviceTransferRejected: true,
  266. multipleDevicesPerAccount: true,
  267. multipleAccountsIsolated: true,
  268. }, null, 2));
  269. } finally {
  270. if (child.exitCode === null) {
  271. const exited = new Promise(resolve => child.once('exit', resolve));
  272. child.kill('SIGTERM');
  273. await Promise.race([exited, new Promise(resolve => setTimeout(resolve, 3000))]);
  274. }
  275. await new Promise(resolve => fmodeServer.close(resolve));
  276. fs.rmSync(tempRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  277. }