Skip to content

fix(leads): return 401 from the search route instead of 500 - #88

Merged
juancodedev merged 1 commit into
mainfrom
fix/leads-search-error-handling
Nov 13, 2026
Merged

juancodedev merged 1 commit into
mainfrom
fix/leads-search-error-handling

Conversation

@juancodedev

Copy link
Copy Markdown
Owner

Qué

GET /api/leads/search era la única ruta de leads sin el wrapper apiHandler. El UnauthorizedError que lanza withAuth se escapaba sin manejar y el endpoint respondía 500 a cualquier caller anónimo, incluido un integrador que mandaba una API key revocada.

Ahora pasa por el handler compartido y responde 401 como el resto de las rutas de leads.

Por qué tenía 500 y no lo cazamos

El spec original (search/__tests__/route.spec.ts) no testea el handler: reimplementa una copia del filtrado y testea esa copia. Nunca ejecutó el código real de la ruta, así que el manejo de errores quedó sin cobertura.

Cambios

  • src/app/api/leads/search/route.ts: GET envuelto en apiHandler.
  • src/app/api/leads/search/__tests__/route-handler.spec.ts: test nuevo contra el handler real — 401 sin credenciales, repository scopeado por el user_id de la API key, match por externalId y leads sin email.

Verificación

  • jest — 111 suites / 816 tests
  • tsc --noEmit limpio
  • Reproducido en prod antes del fix: curl https://crm.juancode.dev/api/leads/search?q=test → 500

Scope

Solo cambio de status code y cobertura. No toca el contrato de respuesta (mismos campos, mismo filtrado).

Risk: none.

GET /api/leads/search was the only leads route without the apiHandler
wrapper, so the UnauthorizedError thrown by withAuth escaped unhandled and
the endpoint answered 500 for anonymous callers — including integrations
that sent a revoked API key. It now goes through the shared handler and maps
to 401 like every other leads route.

The route lost its coverage when the original spec tested a re-implemented
copy of the filtering logic instead of the handler, so the regression test
exercises the real route: 401 without credentials, repository scoped by the
API-key user id, externalId matching and leads without email.
@juancodedev
juancodedev merged commit d6a8c30 into main Nov 13, 2026
4 checks passed
@juancodedev
juancodedev deleted the fix/leads-search-error-handling branch November 13, 2026 00:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant