Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Return the documented JSON error envelope from every /api/v1 failure (#3213)

Luke Vellae6807b269a32
diff --git a/apps/web/src/app/api/middleware/api-error.ts b/apps/web/src/app/api/middleware/api-error.ts
index 2c6ad8936..30c99b961 100644
--- a/apps/web/src/app/api/middleware/api-error.ts
+++ b/apps/web/src/app/api/middleware/api-error.ts
@@ -1,3 +1,37 @@
+import type { Context } from "hono";
+
export const apiError = (code: string, message: string) => ({
error: { code, message },
});
+
+type ValidationIssue = {
+ readonly message: string;
+ readonly path?: ReadonlyArray<PropertyKey | { key: PropertyKey }> | undefined;
+};
+
+type ValidationResult =
+ | { success: true }
+ | { success: false; error: readonly ValidationIssue[] };
+
+// zod emits plain keys; the Standard Schema `{ key }` segment form never occurs.
+const describeIssue = (issue: ValidationIssue) => {
+ const path = (issue.path ?? []).map(String).join(".");
+ return path ? `${path}: ${issue.message}` : issue.message;
+};
+
+/**
+ * Hook for every `validator(...)` call. The standard-validator default
+ * response is `{ success, error, data }` with the request body echoed back,
+ * which both breaks the documented envelope and copies client input into
+ * logs and proxies. This replaces it with the envelope, one issue per
+ * sentence in `message`.
+ */
+export const validationHook = (result: ValidationResult, c: Context) => {
+ if (result.success) {
+ return;
+ }
+ return c.json(
+ apiError("VALIDATION_ERROR", result.error.map(describeIssue).join("; ")),
+ 400,
+ );
+};
diff --git a/apps/web/src/app/api/middleware/api-key.ts b/apps/web/src/app/api/middleware/api-key.ts
index 6ca7a7fa2..142c8e73d 100644
--- a/apps/web/src/app/api/middleware/api-key.ts
+++ b/apps/web/src/app/api/middleware/api-key.ts
@@ -118,6 +118,21 @@ const verifyKey = bearerAuth({
return true;
},
+ noAuthenticationHeader: {
+ message: apiError(
+ "UNAUTHORIZED",
+ "Missing API key. Send it as `Authorization: Bearer <key>`.",
+ ),
+ },
+ invalidAuthenticationHeader: {
+ message: apiError(
+ "INVALID_AUTHORIZATION_HEADER",
+ "Malformed Authorization header. Expected `Bearer <key>`.",
+ ),
+ },
+ invalidToken: {
+ message: apiError("UNAUTHORIZED", "Invalid, expired or revoked API key."),
+ },
});
// hono/bearer-auth can only turn a failed verifyToken into a 401, so the
diff --git a/apps/web/src/app/api/v1/[...route]/route.test.ts b/apps/web/src/app/api/v1/[...route]/route.test.ts
index 0356fa70a..90fef8d07 100644
--- a/apps/web/src/app/api/v1/[...route]/route.test.ts
+++ b/apps/web/src/app/api/v1/[...route]/route.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
// Mock server-only before any imports that might need it
vi.mock("server-only", () => ({}));
@@ -74,6 +74,7 @@ vi.mock("@/lib/posthog", () => ({
flushPostHog: vi.fn(),
}));
+import { logger } from "@rallly/logger";
import { after } from "next/server";
import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";
import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";
@@ -88,6 +89,7 @@ import {
createPollInputSchema,
createPollSuccessResponseSchema,
deletePollSuccessResponseSchema,
+ errorResponseSchema,
getPollParticipantsSuccessResponseSchema,
getPollResultsSuccessResponseSchema,
getPollSuccessResponseSchema,
@@ -107,6 +109,22 @@ const expectMatchesContract = (
expect(result.success).toBe(true);
};
+// Every failure must be the documented `{ error: { code, message } }` JSON
+// envelope, whichever layer produced it (bearer auth, validator, handler,
+// notFound, onError).
+const expectErrorEnvelope = async (
+ res: Response,
+ { status, code }: { status: number; code: string },
+) => {
+ expect(res.status).toBe(status);
+ expect(res.headers.get("content-type")).toMatch(/^application\/json/);
+ const json = await res.json();
+ expectMatchesContract(errorResponseSchema, json);
+ expect(json.error.code).toBe(code);
+ expect(typeof json.error.message).toBe("string");
+ return json as { error: { code: string; message: string } };
+};
+
// Pre-generated test API key fixture. The stored hash deliberately uses the
// deprecated scrypt format so every test in this file exercises the legacy
// verification path that existing production keys depend on.
@@ -173,7 +191,8 @@ describe("API v1 - /polls", () => {
}),
});
- expect(res.status).toBe(401);
+ await expectErrorEnvelope(res, { status: 401, code: "UNAUTHORIZED" });
+ expect(res.headers.get("WWW-Authenticate")).not.toBeNull();
});
it("should return 401 with invalid API key", async () => {
@@ -191,7 +210,8 @@ describe("API v1 - /polls", () => {
}),
});
- expect(res.status).toBe(401);
+ await expectErrorEnvelope(res, { status: 401, code: "UNAUTHORIZED" });
+ expect(res.headers.get("WWW-Authenticate")).not.toBeNull();
});
it("should return 401 with revoked API key", async () => {
@@ -210,7 +230,8 @@ describe("API v1 - /polls", () => {
}),
});
- expect(res.status).toBe(401);
+ await expectErrorEnvelope(res, { status: 401, code: "UNAUTHORIZED" });
+ expect(res.headers.get("WWW-Authenticate")).not.toBeNull();
});
it("should return 401 with expired API key", async () => {
@@ -229,7 +250,8 @@ describe("API v1 - /polls", () => {
}),
});
- expect(res.status).toBe(401);
+ await expectErrorEnvelope(res, { status: 401, code: "UNAUTHORIZED" });
+ expect(res.headers.get("WWW-Authenticate")).not.toBeNull();
});
});
@@ -781,12 +803,12 @@ describe("API v1 - /polls", () => {
// (e.g. TOO_MANY_OPTIONS) can't mask a regression.
expect(res.status).toBe(400);
expect(mockCreatePoll).not.toHaveBeenCalled();
- const json = await res.json();
- const issue = json.error.find((e: { path: (string | number)[] }) =>
- e.path.includes("endDate"),
- );
- expect(issue).toBeDefined();
- expect(issue.message).toContain(String(MAX_SLOT_GENERATION_DAYS));
+ const json = await expectErrorEnvelope(res, {
+ status: 400,
+ code: "VALIDATION_ERROR",
+ });
+ expect(json.error.message).toContain("endDate");
+ expect(json.error.message).toContain(String(MAX_SLOT_GENERATION_DAYS));
});
it("should reject a slot generator range where endDate precedes startDate", async () => {
@@ -816,11 +838,11 @@ describe("API v1 - /polls", () => {
expect(res.status).toBe(400);
expect(mockCreatePoll).not.toHaveBeenCalled();
- const json = await res.json();
- const issue = json.error.find((e: { path: (string | number)[] }) =>
- e.path.includes("endDate"),
- );
- expect(issue).toBeDefined();
+ const json = await expectErrorEnvelope(res, {
+ status: 400,
+ code: "VALIDATION_ERROR",
+ });
+ expect(json.error.message).toContain("endDate");
});
it("should reject a range spanning exactly MAX_SLOT_GENERATION_DAYS", async () => {
@@ -1887,4 +1909,151 @@ describe("API v1 - /polls", () => {
expect(res.status).toBe(401);
});
});
+
+ describe("Error envelope", () => {
+ const authed = { Authorization: `Bearer ${testApiKey}` };
+
+ it("should return 400 INVALID_AUTHORIZATION_HEADER as JSON for a malformed Authorization header", async () => {
+ const res = await app.request("/api/v1/polls", {
+ method: "GET",
+ headers: { Authorization: "Basic not-a-bearer-token" },
+ });
+
+ await expectErrorEnvelope(res, {
+ status: 400,
+ code: "INVALID_AUTHORIZATION_HEADER",
+ });
+ expect(res.headers.get("WWW-Authenticate")).toContain("invalid_request");
+ });
+
+ it("should return 400 VALIDATION_ERROR naming the fields, without echoing the body, for an invalid JSON body", async () => {
+ const res = await app.request("/api/v1/polls", {
+ method: "POST",
+ headers: { ...authed, "Content-Type": "application/json" },
+ body: JSON.stringify({ dates: ["not-a-date"], secret: "do-not-echo" }),
+ });
+
+ const json = await expectErrorEnvelope(res, {
+ status: 400,
+ code: "VALIDATION_ERROR",
+ });
+ expect(json.error.message).toContain("title:");
+ expect(json.error.message).toContain("dates.0:");
+ expect(Object.keys(json.error).sort()).toEqual(["code", "message"]);
+ expect(JSON.stringify(json)).not.toContain("do-not-echo");
+ expect(json).not.toHaveProperty("success");
+ expect(json).not.toHaveProperty("data");
+ expect(mockCreatePoll).not.toHaveBeenCalled();
+ });
+
+ it("should return 400 VALIDATION_ERROR as JSON for an invalid query string", async () => {
+ const res = await app.request("/api/v1/polls?limit=9999", {
+ method: "GET",
+ headers: authed,
+ });
+
+ const json = await expectErrorEnvelope(res, {
+ status: 400,
+ code: "VALIDATION_ERROR",
+ });
+ expect(json.error.message).toMatch(/^limit: /);
+ expect(mockListPolls).not.toHaveBeenCalled();
+ });
+
+ it("should return 400 VALIDATION_ERROR as JSON for a PATCH body that fails validation", async () => {
+ const res = await app.request("/api/v1/polls/test-poll-id", {
+ method: "PATCH",
+ headers: { ...authed, "Content-Type": "application/json" },
+ body: JSON.stringify({ status: "archived" }),
+ });
+
+ const json = await expectErrorEnvelope(res, {
+ status: 400,
+ code: "VALIDATION_ERROR",
+ });
+ expect(json.error.message).toMatch(/^status: /);
+ expect(json).not.toHaveProperty("data");
+ });
+
+ it("should return 400 VALIDATION_ERROR as JSON for a malformed JSON body", async () => {
+ const res = await app.request("/api/v1/polls", {
+ method: "POST",
+ headers: { ...authed, "Content-Type": "application/json" },
+ body: "{not json",
+ });
+
+ await expectErrorEnvelope(res, { status: 400, code: "VALIDATION_ERROR" });
+ });
+
+ it("should return 404 NOT_FOUND as JSON for an unknown route", async () => {
+ const res = await app.request("/api/v1/nope", {
+ method: "GET",
+ headers: authed,
+ });
+
+ await expectErrorEnvelope(res, { status: 404, code: "NOT_FOUND" });
+ });
+
+ it("should return 404 NOT_FOUND as JSON for an unsupported method on a known route", async () => {
+ const res = await app.request("/api/v1/polls", {
+ method: "PUT",
+ headers: authed,
+ });
+
+ await expectErrorEnvelope(res, { status: 404, code: "NOT_FOUND" });
+ });
+
+ it("should return 500 INTERNAL_ERROR as JSON and log the error when a handler behind the rate limiter throws", async () => {
+ const errorSpy = vi.spyOn(logger, "error").mockImplementation(() => {});
+ onTestFinished(() => errorSpy.mockRestore());
+ mockGetPollWithOptions.mockRejectedValue(new TypeError("db exploded"));
+
+ const res = await app.request("/api/v1/polls/test-poll-id", {
+ method: "GET",
+ headers: authed,
+ });
+
+ const json = await expectErrorEnvelope(res, {
+ status: 500,
+ code: "INTERNAL_ERROR",
+ });
+ // Never leak the underlying error message to the client.
+ expect(json.error.message).not.toContain("db exploded");
+ // The request was counted by the limiter before the handler threw.
+ expect(res.headers.get("RateLimit-Limit")).not.toBeNull();
+
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ expect(errorSpy.mock.calls[0][0]).toMatchObject({
+ service: "api-v1",
+ statusCode: 500,
+ errorType: "TypeError",
+ errorMessage: "db exploded",
+ spaceId: "test-space-id",
+ });
+ });
+
+ it("should document the full error code list in the spec", async () => {
+ const res = await app.request("/api/v1/openapi");
+ const json = await res.json();
+
+ for (const code of [
+ "VALIDATION_ERROR",
+ "UNAUTHORIZED",
+ "INVALID_AUTHORIZATION_HEADER",
+ "SPACE_NOT_PRO",
+ "RATE_LIMIT_EXCEEDED",
+ "NOT_FOUND",
+ "POLL_NOT_FOUND",
+ "ORGANIZER_NOT_MEMBER",
+ "TOO_MANY_OPTIONS",
+ "DUPLICATE_DATES",
+ "NO_OPTIONS_GENERATED",
+ "TRANSITION_NOT_AVAILABLE",
+ "SERVICE_UNAVAILABLE",
+ "INTERNAL_ERROR",
+ ]) {
+ expect(json.info.description).toContain(`\`${code}\``);
+ }
+ });
+ });
});
diff --git a/apps/web/src/app/api/v1/[...route]/route.ts b/apps/web/src/app/api/v1/[...route]/route.ts
index 71330c4c2..620e426a3 100644
--- a/apps/web/src/app/api/v1/[...route]/route.ts
+++ b/apps/web/src/app/api/v1/[...route]/route.ts
@@ -1,5 +1,6 @@
import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
import { Hono } from "hono";
+import { HTTPException } from "hono/http-exception";
import { handle } from "hono/vercel";
import {
describeRoute,
@@ -27,7 +28,7 @@ import {
} from "@/lib/datetime/slot-generator";
import { isMaintenanceModeEnabled } from "@/lib/maintenance";
import { flushPostHog, identifyGroup, track } from "@/lib/posthog";
-import { apiError } from "../../middleware/api-error";
+import { apiError, validationHook } from "../../middleware/api-error";
import { spaceApiKeyAuth } from "../../middleware/api-key";
import {
RATE_LIMIT_PER_DAY,
@@ -116,6 +117,33 @@ app.use("*", async (c, next) => {
await next();
});
+app.notFound((c) =>
+ c.json(
+ apiError("NOT_FOUND", `No route matches ${c.req.method} ${c.req.path}.`),
+ 404,
+ ),
+);
+
+// The wide event middleware reads `c.error`, which hono sets before calling
+// this handler, so the original error is logged there. The client only ever
+// sees a generic message.
+app.onError((error, c) => {
+ if (error instanceof HTTPException) {
+ // Bearer auth throws with a prebuilt JSON response.
+ if (error.res) {
+ return error.getResponse();
+ }
+ // hono's validator throws a bare 400 for a body it cannot parse.
+ if (error.status === 400) {
+ return c.json(apiError("VALIDATION_ERROR", error.message), 400);
+ }
+ }
+ return c.json(
+ apiError("INTERNAL_ERROR", "Something went wrong. Try again later."),
+ 500,
+ );
+});
+
const spaceNotProResponse = {
description:
"The space associated with the API key does not have a Pro subscription",
@@ -173,6 +201,27 @@ async function buildOpenApiSpec() {
"Every response from an authenticated request includes the standard `RateLimit-*` headers. Responses sent before the limiter runs (`401`, `403`, and the maintenance `503`) do not. `RateLimit-Policy` lists both limits; `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` describe whichever limit is closest to being exhausted. When either limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.",
"",
"If the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.",
+ "",
+ "## Errors",
+ "",
+ 'Every failure is `application/json` with the shape `{ "error": { "code", "message" } }`. `code` is stable and safe to branch on; `message` is human-readable and may change. `VALIDATION_ERROR` messages name each offending field.',
+ "",
+ "| Status | Code | When |",
+ "| --- | --- | --- |",
+ "| 400 | `VALIDATION_ERROR` | The body or query string did not match the schema, or the body was not valid JSON |",
+ "| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |",
+ "| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |",
+ "| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |",
+ "| 400 | `DUPLICATE_DATES` | `dates` contains the same date more than once |",
+ "| 400 | `NO_OPTIONS_GENERATED` | No slot generator produced a valid time slot |",
+ "| 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked |",
+ "| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |",
+ "| 404 | `NOT_FOUND` | No route matches the method and path |",
+ "| 404 | `POLL_NOT_FOUND` | The poll does not exist or belongs to another space |",
+ "| 422 | `TRANSITION_NOT_AVAILABLE` | The requested status change is not supported |",
+ "| 429 | `RATE_LIMIT_EXCEEDED` | A rate limit window is exhausted |",
+ "| 503 | `SERVICE_UNAVAILABLE` | Maintenance, or the rate limit store cannot be reached |",
+ "| 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |",
].join("\n"),
},
servers: [{ url: absoluteUrl() }],
@@ -255,7 +304,7 @@ app.post(
503: serviceUnavailableResponse,
},
}),
- validator("json", createPollInputSchema),
+ validator("json", createPollInputSchema, validationHook),
async (c) => {
const input = c.req.valid("json");
const { spaceId, spaceOwnerId } = c.get("apiAuth");
@@ -382,7 +431,10 @@ app.post(
// Process slots (time-based options)
if (!input.slots) {
return c.json(
- apiError("INVALID_INPUT", "Either 'dates' or 'slots' must be provided"),
+ apiError(
+ "VALIDATION_ERROR",
+ "Either 'dates' or 'slots' must be provided",
+ ),
400,
);
}
@@ -487,7 +539,7 @@ app.get(
503: serviceUnavailableResponse,
},
}),
- validator("query", listPollsQuerySchema),
+ validator("query", listPollsQuerySchema, validationHook),
async (c) => {
const { status, cursor, limit } = c.req.valid("query");
const { spaceId } = c.get("apiAuth");
@@ -608,7 +660,7 @@ app.patch(
},
},
}),
- validator("json", patchPollInputSchema),
+ validator("json", patchPollInputSchema, validationHook),
async (c) => {
const { pollId } = c.req.param();
const { status } = c.req.valid("json");
diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.ts
index f622d2693..2a24bcea2 100644
--- a/apps/web/src/app/api/v1/schemas.ts
+++ b/apps/web/src/app/api/v1/schemas.ts
@@ -141,10 +141,15 @@ export const createPollInputSchema = z
export const errorResponseSchema = z
.object({
error: z.object({
- code: z.string().openapi({ example: "TIMEZONE_REQUIRED" }),
+ code: z.string().openapi({
+ description:
+ "Machine-readable error code. The full list is in the API description.",
+ example: "VALIDATION_ERROR",
+ }),
message: z.string().openapi({
- example:
- "Timezone is required. Either provide a timezone in the request or set one in your profile.",
+ description:
+ "Human-readable explanation. For `VALIDATION_ERROR` it names each offending field, e.g. `title: Invalid input: expected string, received undefined; dates.0: Invalid ISO date`.",
+ example: "title: Invalid input: expected string, received undefined",
}),
}),
})