global-ingest-smoke-test.mjs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. const PORT = 4100;
  8. const BASE = `http://127.0.0.1:${PORT}`;
  9. const ADMIN_KEY = 'relay-smoke-admin';
  10. const CALLBACK_SECRET = 'relay-smoke-callback';
  11. const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-relay-smoke-'));
  12. const child = spawn(process.execPath, ['dist/server.js'], {
  13. cwd: path.resolve(import.meta.dirname, '..'),
  14. env: {
  15. ...process.env,
  16. PORT: String(PORT),
  17. DB_PATH: path.join(tempRoot, 'relay.db'),
  18. ADMIN_KEY,
  19. UPSTREAM_CALLBACK_SECRET: CALLBACK_SECRET,
  20. RELAY_PUBLIC_URL: BASE,
  21. },
  22. stdio: ['ignore', 'pipe', 'pipe'],
  23. });
  24. async function request(route, { method = 'GET', body, headers = {} } = {}) {
  25. const response = await fetch(`${BASE}${route}`, {
  26. method,
  27. headers: {
  28. ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
  29. ...headers,
  30. },
  31. body: body === undefined ? undefined : JSON.stringify(body),
  32. });
  33. return { response, data: await response.json().catch(() => ({})) };
  34. }
  35. async function waitForHealth() {
  36. const deadline = Date.now() + 15000;
  37. while (Date.now() < deadline) {
  38. try {
  39. const { response } = await request('/api/health');
  40. if (response.ok) return;
  41. } catch {}
  42. await new Promise(resolve => setTimeout(resolve, 150));
  43. }
  44. throw new Error('Relay smoke server did not become healthy');
  45. }
  46. function decrypt(encryptedPayload, privateKeyPem) {
  47. assert.ok(encryptedPayload.startsWith('v2:'));
  48. const envelope = JSON.parse(Buffer.from(encryptedPayload.slice(3), 'base64').toString('utf8'));
  49. const privateKey = crypto.createPrivateKey(privateKeyPem);
  50. const aesKey = crypto.privateDecrypt(
  51. { key: privateKey, oaepHash: 'sha256' },
  52. Buffer.from(envelope.key, 'base64'),
  53. );
  54. const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, Buffer.from(envelope.iv, 'base64'));
  55. decipher.setAuthTag(Buffer.from(envelope.tag, 'base64'));
  56. return Buffer.concat([
  57. decipher.update(Buffer.from(envelope.ciphertext, 'base64')),
  58. decipher.final(),
  59. ]).toString('utf8');
  60. }
  61. try {
  62. await waitForHealth();
  63. const tenantResponse = await request('/api/admin/tenant', {
  64. method: 'POST',
  65. headers: { 'X-Admin-Key': ADMIN_KEY },
  66. body: { name: 'global-ingest-smoke' },
  67. });
  68. assert.equal(tenantResponse.response.status, 200);
  69. const tenant = tenantResponse.data;
  70. const guid = `smoke-guid-${crypto.randomUUID()}`;
  71. const deviceResponse = await request('/api/tenant/device', {
  72. method: 'POST',
  73. headers: { Authorization: `Bearer ${tenant.apiSecret}` },
  74. body: { guid, deviceName: 'smoke-device' },
  75. });
  76. assert.equal(deviceResponse.response.status, 200);
  77. const callbackBody = {
  78. code: 0,
  79. data: [{
  80. guid,
  81. msgUniqueIdentifier: `smoke-${crypto.randomUUID()}`,
  82. msgType: 1,
  83. content: 'x'.repeat(5000),
  84. }],
  85. };
  86. const rawBody = JSON.stringify(callbackBody);
  87. const signature = crypto.createHmac('sha256', CALLBACK_SECRET).update(rawBody).digest('hex');
  88. const ingest = await request('/api/webhook/ingest', {
  89. method: 'POST',
  90. headers: { 'X-Signature': signature },
  91. body: callbackBody,
  92. });
  93. assert.equal(ingest.response.status, 200);
  94. assert.equal(ingest.data.queued, 1);
  95. const duplicate = await request('/api/webhook/ingest', {
  96. method: 'POST',
  97. headers: { 'X-Signature': signature },
  98. body: callbackBody,
  99. });
  100. assert.equal(duplicate.response.status, 200);
  101. assert.equal(duplicate.data.duplicates, 1);
  102. const poll = await request('/api/relay/poll', {
  103. method: 'POST',
  104. headers: { Authorization: `Bearer ${tenant.apiSecret}` },
  105. body: { guid, batchSize: 10, waitMs: 1000 },
  106. });
  107. assert.equal(poll.response.status, 200);
  108. assert.equal(poll.data.events.length, 1);
  109. const decrypted = JSON.parse(decrypt(poll.data.events[0].encryptedPayload, tenant.privateKey));
  110. assert.equal(decrypted.data[0].guid, guid);
  111. assert.equal(decrypted.data[0].content.length, 5000);
  112. const ack = await request('/api/relay/ack', {
  113. method: 'POST',
  114. headers: { Authorization: `Bearer ${tenant.apiSecret}` },
  115. body: { guid, eventIds: [poll.data.events[0].eventId] },
  116. });
  117. assert.equal(ack.response.status, 200);
  118. assert.equal(ack.data.ackedCount, 1);
  119. const missingGuid = await request('/api/webhook/ingest', {
  120. method: 'POST',
  121. headers: {
  122. 'X-Signature': crypto.createHmac('sha256', CALLBACK_SECRET).update('{}').digest('hex'),
  123. },
  124. body: {},
  125. });
  126. assert.equal(missingGuid.response.status, 400);
  127. const invalidSignature = await request('/api/webhook/ingest', {
  128. method: 'POST',
  129. headers: { 'X-Signature': 'invalid' },
  130. body: callbackBody,
  131. });
  132. assert.equal(invalidSignature.response.status, 401);
  133. process.stdout.write(JSON.stringify({
  134. status: 'ok',
  135. globalRouting: true,
  136. largePayloadBytes: 5000,
  137. duplicateProtected: true,
  138. missingGuidRejected: true,
  139. invalidSignatureRejected: true,
  140. }, null, 2));
  141. } finally {
  142. child.kill('SIGTERM');
  143. fs.rmSync(tempRoot, { recursive: true, force: true });
  144. }