validation.test.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /**
  2. * tests/4 — Validation surface.
  3. *
  4. * Tests the endpoints that Turnstile Spin's wizard relies on during its
  5. * post-deploy validation step:
  6. *
  7. * - GET /health returns {ok: true, version}
  8. * - GET / returns the same shape
  9. * - POST / with dummy returns a structured error (success: false, error-codes,
  10. * _worker metadata) rather than a bare 500
  11. * - hostname mismatch when EXPECTED_HOSTNAME is set
  12. *
  13. * These match the assertions in the wizard's Step 7. If any of these fail,
  14. * the wizard's validation step will fail, and the customer will see a
  15. * misleading "setup complete" message followed by a broken integration.
  16. */
  17. import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
  18. import worker, { WORKER_VERSION } from '../src/index.js';
  19. import type { Env } from '../src/types.js';
  20. const ENV: Env = {
  21. TURNSTILE_SECRET_KEY: 'test-secret-key',
  22. ALLOWED_ORIGIN: '*',
  23. };
  24. describe('validation surface — /health', () => {
  25. it('returns ok:true and a semver version', async () => {
  26. const res = await worker.fetch(new Request('https://w/health'), ENV);
  27. expect(res.status).toBe(200);
  28. const body = (await res.json()) as { ok: boolean; version: string };
  29. expect(body.ok).toBe(true);
  30. expect(body.version).toMatch(/^\d+\.\d+\.\d+$/);
  31. expect(body.version).toBe(WORKER_VERSION);
  32. });
  33. it('GET / returns the same shape as /health', async () => {
  34. const [a, b] = await Promise.all([
  35. worker.fetch(new Request('https://w/'), ENV),
  36. worker.fetch(new Request('https://w/health'), ENV),
  37. ]);
  38. const ja = (await a.json()) as { ok: boolean; version: string };
  39. const jb = (await b.json()) as { ok: boolean; version: string };
  40. expect(ja.ok).toBe(jb.ok);
  41. expect(ja.version).toBe(jb.version);
  42. });
  43. it('responds in well under the wizard timeout (1s)', async () => {
  44. const start = Date.now();
  45. await worker.fetch(new Request('https://w/health'), ENV);
  46. expect(Date.now() - start).toBeLessThan(1000);
  47. });
  48. });
  49. describe('validation surface — dummy siteverify returns structured error', () => {
  50. beforeEach(() => vi.restoreAllMocks());
  51. afterEach(() => vi.restoreAllMocks());
  52. it('returns success:false + error-codes + _worker for a dummy token', async () => {
  53. vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async () => {
  54. return new Response(
  55. JSON.stringify({ success: false, 'error-codes': ['invalid-input-response'] }),
  56. { status: 200 },
  57. );
  58. });
  59. const res = await worker.fetch(
  60. new Request('https://w/', {
  61. method: 'POST',
  62. headers: { 'Content-Type': 'application/json' },
  63. body: JSON.stringify({ token: 'XXXX.DUMMY.TOKEN.XXXX' }),
  64. }),
  65. ENV,
  66. );
  67. expect(res.status).toBe(200);
  68. const body = (await res.json()) as {
  69. success: boolean;
  70. 'error-codes': string[];
  71. _worker?: { duration_ms: number; worker_version: string };
  72. };
  73. // Wizard's required assertions:
  74. expect(body.success).toBe(false);
  75. expect(Array.isArray(body['error-codes'])).toBe(true);
  76. expect(body['error-codes'].length).toBeGreaterThan(0);
  77. expect(body._worker).toBeDefined();
  78. expect(typeof body._worker?.duration_ms).toBe('number');
  79. expect(body._worker?.worker_version).toBe(WORKER_VERSION);
  80. });
  81. it('returns structured error on Worker-level failure (no bare 500)', async () => {
  82. // Force the upstream to be unreachable.
  83. vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async () => {
  84. throw new TypeError('network unreachable');
  85. });
  86. // Disable the retry loop by also failing the second attempt.
  87. vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async () => {
  88. throw new TypeError('network unreachable');
  89. });
  90. const res = await worker.fetch(
  91. new Request('https://w/', {
  92. method: 'POST',
  93. headers: { 'Content-Type': 'application/json' },
  94. body: JSON.stringify({ token: 'whatever' }),
  95. }),
  96. ENV,
  97. );
  98. // Worker-level failure still returns a *parseable* error body.
  99. const body = (await res.json()) as { success: boolean; 'error-codes': string[]; _worker?: unknown };
  100. expect(body.success).toBe(false);
  101. expect(body['error-codes'][0]).toBe('upstream-unreachable');
  102. expect(body._worker).toBeDefined();
  103. });
  104. });
  105. describe('validation surface — hostname mismatch', () => {
  106. beforeEach(() => vi.restoreAllMocks());
  107. afterEach(() => vi.restoreAllMocks());
  108. it('rejects success when EXPECTED_HOSTNAME does not match', async () => {
  109. vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async () => {
  110. return new Response(
  111. JSON.stringify({ success: true, hostname: 'attacker.example.com', 'error-codes': [] }),
  112. { status: 200 },
  113. );
  114. });
  115. const env: Env = { ...ENV, EXPECTED_HOSTNAME: 'www.example.com' };
  116. const res = await worker.fetch(
  117. new Request('https://w/', {
  118. method: 'POST',
  119. headers: { 'Content-Type': 'application/json' },
  120. body: JSON.stringify({ token: 'abc' }),
  121. }),
  122. env,
  123. );
  124. const body = (await res.json()) as { success: boolean; 'error-codes': string[] };
  125. expect(body.success).toBe(false);
  126. expect(body['error-codes']).toContain('hostname-mismatch');
  127. });
  128. });
  129. describe('validation surface — telemetry marker passthrough', () => {
  130. beforeEach(() => vi.restoreAllMocks());
  131. afterEach(() => vi.restoreAllMocks());
  132. it('passes data-action through to siteverify and surfaces it in the response', async () => {
  133. // Upstream echoes the action field. Spin marker should survive.
  134. vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async () => {
  135. return new Response(
  136. JSON.stringify({
  137. success: true,
  138. hostname: 'example.com',
  139. action: 'turnstile-spin-v1',
  140. 'error-codes': [],
  141. }),
  142. { status: 200 },
  143. );
  144. });
  145. const res = await worker.fetch(
  146. new Request('https://w/', {
  147. method: 'POST',
  148. headers: { 'Content-Type': 'application/json' },
  149. body: JSON.stringify({ token: 'abc' }),
  150. }),
  151. ENV,
  152. );
  153. const body = (await res.json()) as { success: boolean; action?: string };
  154. expect(body.success).toBe(true);
  155. expect(body.action).toBe('turnstile-spin-v1');
  156. });
  157. });
  158. describe('validation surface — post-deploy form is reachable', () => {
  159. it('GET /post-deploy returns 404 when ASSETS binding is missing (test env)', async () => {
  160. // In the unit-test env we don't have the ASSETS binding wired, so the
  161. // handler falls through. The real Worker has the binding from wrangler.toml.
  162. const res = await worker.fetch(new Request('https://w/post-deploy'), ENV);
  163. expect(res.status).toBe(404);
  164. });
  165. it('GET /post-deploy serves the HTML file when ASSETS is bound', async () => {
  166. const html = '<!doctype html><title>Post-deploy</title>';
  167. const mockAssets: Fetcher = {
  168. fetch: async () =>
  169. new Response(html, { status: 200, headers: { 'Content-Type': 'text/html' } }),
  170. } as unknown as Fetcher;
  171. const envWithAssets: Env = { ...ENV, ASSETS: mockAssets };
  172. const res = await worker.fetch(new Request('https://w/post-deploy'), envWithAssets);
  173. expect(res.status).toBe(200);
  174. expect(await res.text()).toContain('Post-deploy');
  175. });
  176. });