test(api): lock the two webhook-deliveries operator routes

GET /api/webhook-endpoints/[id]/deliveries (246216a4 — powers the
drawer) and POST .../[deliveryId]/replay (bfd39b6d — the manual
retry button) both shipped to operators without handler-level tests.
Following the eb5fc998 pattern: writing the coverage proves the
contracts hold AND surfaces any silent bugs in the auth + ownership
chain before customers hit them.

11 tests across both routes:

GET (6 tests):
  - 401 when no session user
  - 404 (Webhook endpoint) when userOwnsEndpoint returns false
    (service not called)
  - happy path returns deliveries + default limit 50
  - ?limit=25 routed verbatim
  - ?limit=999 capped at MAX (100)
  - ?limit=abc / ?limit=0 fall back to DEFAULT (50)

POST replay (5 tests):
  - 401 when no session user (no service calls)
  - 404 (Webhook endpoint) when userOwnsEndpoint false; chain stops
  - 404 (Webhook delivery) when deliveryBelongsToEndpoint false;
    same envelope as endpoint-mismatch (probers can't distinguish)
  - 500 when enqueueDeliveryReplay returns false
  - happy path returns replayed:true with enqueue called with
    correct deliveryId

Mock pattern mirrors the existing services-api.test.ts shape:
explicit standardResponse mocks return shaped objects so handler-level
assertions are clean. A minimal `{ url }` shim avoids jsdom's missing
global Request constructor.

Suite: 50 suites · 659 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.7 committed 2026-06-04 02:25:12 +02:00
1 parent e407631c77
commit bdef16f4ff
1 file changed
+250
@@ -0,0 +1,250 @@
/**
* Webhook deliveries routes — handler-level branch tests.
*
* Covers the two operator-facing routes shipped without tests:
* - GET /api/webhook-endpoints/[id]/deliveries (246216a4)
* - POST /api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay (bfd39b6d)
*
* Both share the userOwnsEndpoint gate; the replay route adds a
* deliveryBelongsToEndpoint check on top. We mock the services so
* the handler logic is the only thing under test.
*
* Created: 2026-06-04
*/
jest.mock('@/lib/supabase/server', () => ({
createServerClient: jest.fn(),
}));
jest.mock('@/services/webhooks/webhookEndpointsService', () => ({
userOwnsEndpoint: jest.fn(),
}));
jest.mock('@/services/webhooks/deliveryService', () => ({
listRecentDeliveriesForEndpoint: jest.fn(),
deliveryBelongsToEndpoint: jest.fn(),
enqueueDeliveryReplay: jest.fn(),
}));
jest.mock('@/lib/api/standardResponse', () => ({
apiSuccess: jest.fn((payload: unknown) => ({ ok: true, data: payload, status: 200 })),
apiUnauthorized: jest.fn(() => ({ ok: false, error: 'Unauthorized', status: 401 })),
apiNotFound: jest.fn((what: string) => ({ ok: false, error: `${what} not found`, status: 404 })),
apiError: jest.fn((msg: string, code: string, status: number) => ({
ok: false,
error: msg,
code,
status,
})),
handleApiError: jest.fn((err: Error) => ({ ok: false, error: err.message, status: 500 })),
}));
import { GET } from '@/app/api/webhook-endpoints/[id]/deliveries/route';
import { POST as REPLAY_POST } from '@/app/api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay/route';
import { createServerClient } from '@/lib/supabase/server';
import { userOwnsEndpoint } from '@/services/webhooks/webhookEndpointsService';
import {
listRecentDeliveriesForEndpoint,
deliveryBelongsToEndpoint,
enqueueDeliveryReplay,
} from '@/services/webhooks/deliveryService';
import { apiSuccess, apiUnauthorized, apiNotFound, apiError } from '@/lib/api/standardResponse';
const mockUser = { id: 'u-1' };
function setSession(user: { id: string } | null) {
(createServerClient as jest.Mock).mockResolvedValue({
auth: {
getUser: jest.fn().mockResolvedValue({ data: { user } }),
},
});
}
// Handlers only read `.url`. jsdom doesn't expose the global Request
// constructor, so a minimal shim keeps the tests env-independent.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function makeRequest(url: string): any {
return { url };
}
function withParams<T extends Record<string, string>>(p: T): { params: Promise<T> } {
return { params: Promise.resolve(p) };
}
beforeEach(() => {
jest.clearAllMocks();
});
// =============================================================================
// GET /api/webhook-endpoints/[id]/deliveries
// =============================================================================
describe('GET /api/webhook-endpoints/[id]/deliveries', () => {
it('returns 401 when no session user', async () => {
setSession(null);
const res = (await GET(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries'),
withParams({ id: 'e-1' })
)) as { status: number };
expect(res.status).toBe(401);
expect(apiUnauthorized).toHaveBeenCalled();
});
it('returns 404 when the user does not own the endpoint', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(false);
const res = (await GET(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries'),
withParams({ id: 'e-1' })
)) as { status: number };
expect(res.status).toBe(404);
expect(apiNotFound).toHaveBeenCalledWith('Webhook endpoint');
expect(listRecentDeliveriesForEndpoint).not.toHaveBeenCalled();
});
it('returns deliveries on success and caps at default limit (50)', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(true);
const rows = [{ id: 'd-1' }, { id: 'd-2' }];
(listRecentDeliveriesForEndpoint as jest.Mock).mockResolvedValue(rows);
const res = (await GET(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries'),
withParams({ id: 'e-1' })
)) as { ok: boolean; data: { deliveries: Array<{ id: string }> } };
expect(res.ok).toBe(true);
expect(res.data.deliveries).toBe(rows);
expect(listRecentDeliveriesForEndpoint).toHaveBeenCalledWith('e-1', 50);
expect(apiSuccess).toHaveBeenCalledWith({ deliveries: rows });
});
it('honours ?limit= up to MAX (100)', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(true);
(listRecentDeliveriesForEndpoint as jest.Mock).mockResolvedValue([]);
await GET(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries?limit=25'),
withParams({ id: 'e-1' })
);
expect(listRecentDeliveriesForEndpoint).toHaveBeenCalledWith('e-1', 25);
});
it('caps ?limit= at MAX (100) when the caller asks for more', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(true);
(listRecentDeliveriesForEndpoint as jest.Mock).mockResolvedValue([]);
await GET(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries?limit=999'),
withParams({ id: 'e-1' })
);
expect(listRecentDeliveriesForEndpoint).toHaveBeenCalledWith('e-1', 100);
});
it('falls back to DEFAULT when ?limit= is non-numeric or <=0', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(true);
(listRecentDeliveriesForEndpoint as jest.Mock).mockResolvedValue([]);
await GET(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries?limit=abc'),
withParams({ id: 'e-1' })
);
expect(listRecentDeliveriesForEndpoint).toHaveBeenLastCalledWith('e-1', 50);
await GET(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries?limit=0'),
withParams({ id: 'e-1' })
);
expect(listRecentDeliveriesForEndpoint).toHaveBeenLastCalledWith('e-1', 50);
});
});
// =============================================================================
// POST /api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay
// =============================================================================
describe('POST /api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay', () => {
it('returns 401 when no session user', async () => {
setSession(null);
const res = (await REPLAY_POST(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries/d-1/replay'),
withParams({ id: 'e-1', deliveryId: 'd-1' })
)) as { status: number };
expect(res.status).toBe(401);
expect(userOwnsEndpoint).not.toHaveBeenCalled();
expect(deliveryBelongsToEndpoint).not.toHaveBeenCalled();
expect(enqueueDeliveryReplay).not.toHaveBeenCalled();
});
it('returns 404 (Webhook endpoint) when the user does not own the endpoint', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(false);
const res = (await REPLAY_POST(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries/d-1/replay'),
withParams({ id: 'e-1', deliveryId: 'd-1' })
)) as { status: number };
expect(res.status).toBe(404);
expect(apiNotFound).toHaveBeenCalledWith('Webhook endpoint');
expect(deliveryBelongsToEndpoint).not.toHaveBeenCalled();
expect(enqueueDeliveryReplay).not.toHaveBeenCalled();
});
it('returns 404 (Webhook delivery) when delivery does not belong to endpoint', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(true);
(deliveryBelongsToEndpoint as jest.Mock).mockResolvedValue(false);
const res = (await REPLAY_POST(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries/d-1/replay'),
withParams({ id: 'e-1', deliveryId: 'd-1' })
)) as { status: number };
expect(res.status).toBe(404);
// Both 404s use the same generic envelope so probers can't distinguish
// endpoint-mismatch from delivery-mismatch.
expect(apiNotFound).toHaveBeenCalledWith('Webhook delivery');
expect(enqueueDeliveryReplay).not.toHaveBeenCalled();
});
it('returns 500 when the enqueue service signals failure', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(true);
(deliveryBelongsToEndpoint as jest.Mock).mockResolvedValue(true);
(enqueueDeliveryReplay as jest.Mock).mockResolvedValue(false);
const res = (await REPLAY_POST(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries/d-1/replay'),
withParams({ id: 'e-1', deliveryId: 'd-1' })
)) as { status: number };
expect(res.status).toBe(500);
expect(apiError).toHaveBeenCalledWith('Replay failed', 'INTERNAL_ERROR', 500);
});
it('returns 200 with replayed:true on the happy path', async () => {
setSession(mockUser);
(userOwnsEndpoint as jest.Mock).mockResolvedValue(true);
(deliveryBelongsToEndpoint as jest.Mock).mockResolvedValue(true);
(enqueueDeliveryReplay as jest.Mock).mockResolvedValue(true);
const res = (await REPLAY_POST(
makeRequest('http://x/api/webhook-endpoints/e-1/deliveries/d-1/replay'),
withParams({ id: 'e-1', deliveryId: 'd-1' })
)) as { ok: boolean; data: { replayed: boolean } };
expect(res.ok).toBe(true);
expect(apiSuccess).toHaveBeenCalledWith({ replayed: true });
expect(enqueueDeliveryReplay).toHaveBeenCalledWith('d-1');
});
});