Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 119 additions & 1 deletion services/platform/backend/domains/projects/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,18 @@ import {
PROJECT_INSTRUCTIONS_MAX_CHARS,
PROJECT_NAME_MAX,
} from '@tale/shared/schemas/projects';
import type { Context } from 'hono';
import { Hono, type Context } from 'hono';
import { requestId } from 'hono/request-id';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import type { OrgEnv } from '../../auth/org.ts';
import { appErrorHandler } from '../../error-reporting.ts';
import { appJsonBody, INVALID_JSON_MESSAGE } from '../../lib/app-json-body.ts';
import { checkUserRateLimit } from '../../lib/rate-limit.ts';

const service = vi.hoisted(() => ({
createProject: vi.fn(),
duplicateProject: vi.fn(),
updateProjectIdentity: vi.fn(),
updateProjectInstructions: vi.fn(),
deleteProject: vi.fn(),
Expand Down Expand Up @@ -279,3 +284,116 @@ describe('project routes — the shared schemas guard the door', () => {
expect(service.deleteProject).not.toHaveBeenCalled();
});
});

describe('duplicate — the name is optional, its JSON is not (#3599)', () => {
// The project routes as `app.ts` mounts them: behind the app door's one
// JSON reader and its error handler, which answer a body that does not
// parse with the door's 400 `INVALID_JSON`.
function door(): Hono {
const hono = new Hono();
hono.onError(appErrorHandler);
hono.use(requestId());
hono.use('/api/app/*', appJsonBody());
hono.route(
'/api/app/projects',
createProjectRoutes({ sql: {} as never, auth: {} as never }),
);
return hono;
}

async function post(route: string, body: string): Promise<Response> {
return await door().request(
`http://localhost/api/app/projects${route}?orgId=o1`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
'x-request-id': 'req-duplicate',
},
body,
},
);
}

beforeEach(() => {
service.duplicateProject.mockResolvedValue('p2');
});

it.each([
['a lone brace', '{'],
['a truncated name', '{"name":"Cop'],
['a body that is not JSON', 'name=Copy'],
])(
'refuses %s with 400 INVALID_JSON and duplicates nothing',
async (_name, body) => {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const res = await post('/p1/duplicate', body);

expect(res.status).toBe(400);
expect(await res.json()).toEqual({
error: INVALID_JSON_MESSAGE,
code: 'INVALID_JSON',
requestId: 'req-duplicate',
});
// Refused after the session and membership gates, before the
// route's own project lookup, its rate-limit charge and the copy.
expect(service.getProjectAuthContext).not.toHaveBeenCalled();
expect(checkUserRateLimit).not.toHaveBeenCalled();
expect(service.duplicateProject).not.toHaveBeenCalled();
// A client's mistake, not a defect to report.
expect(errors).not.toHaveBeenCalled();
} finally {
errors.mockRestore();
}
},
);

it.each([
['no body', ''],
['only whitespace', ' \n\t'],
['an empty object', '{}'],
])('duplicates under the default name for %s', async (_name, body) => {
const res = await post('/p1/duplicate', body);

expect(res.status).toBe(200);
expect(await res.json()).toEqual({ projectId: 'p2' });
expect(service.duplicateProject).toHaveBeenCalledExactlyOnceWith(
expect.anything(),
expect.anything(),
'p1',
undefined,
);
});

it('duplicates under the name a valid body gives', async () => {
const res = await post('/p1/duplicate', '{"name":"Copy of P"}');

expect(res.status).toBe(200);
expect(service.duplicateProject).toHaveBeenCalledExactlyOnceWith(
expect.anything(),
expect.anything(),
'p1',
'Copy of P',
);
});

it('refuses a name over its cap as an invalid body', async () => {
const res = await post(
'/p1/duplicate',
JSON.stringify({ name: 'x'.repeat(201) }),
);

expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ error: 'invalid body' });
expect(service.duplicateProject).not.toHaveBeenCalled();
});

it('answers the same lone brace on create as before', async () => {
const res = await post('', '{');

expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ code: 'INVALID_JSON' });
expect(service.createProject).not.toHaveBeenCalled();
});
});
3 changes: 2 additions & 1 deletion services/platform/backend/domains/projects/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { z } from 'zod';
import type { Auth } from '../../auth/auth.ts';
import { requireOrgMember, type OrgEnv } from '../../auth/org.ts';
import { requireSession } from '../../auth/session.ts';
import { readOptionalAppJsonBody } from '../../lib/app-json-body.ts';
import { invalidBodyResponse } from '../../lib/invalid-body-response.ts';
import { rateLimitedResponse } from '../../lib/rate-limit-response.ts';
import {
Expand Down Expand Up @@ -202,7 +203,7 @@ export function createProjectRoutes(deps: {
app.post('/:id/duplicate', async (c) => {
const body = z
.object({ name: z.string().max(200).optional() })
.safeParse(await c.req.json().catch(() => ({})));
.safeParse(await readOptionalAppJsonBody(c));
if (!body.success) {
return invalidBodyResponse(c, body.error);
}
Expand Down
81 changes: 80 additions & 1 deletion services/platform/backend/lib/app-json-body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { z } from 'zod';

import { appErrorHandler } from '../error-reporting.ts';
import { appJsonBody, INVALID_JSON_MESSAGE } from './app-json-body.ts';
import {
appJsonBody,
INVALID_JSON_MESSAGE,
readOptionalAppJsonBody,
} from './app-json-body.ts';

/**
* The app door's bare `await c.req.json()` — about 127 handlers — answered
Expand All @@ -33,6 +37,10 @@ function app(): Hono {
const body: unknown = await c.req.json().catch(() => ({}));
return c.json({ received: body });
});
// A handler whose body is optional (`domains/projects/routes.ts`).
hono.post('/api/app/projects/:id/duplicate', async (c) =>
c.json({ received: await readOptionalAppJsonBody(c) }),
);
// A SyntaxError that is not the body's: still the defect it is.
hono.post('/api/app/broken', async (c) => {
await c.req.json();
Expand Down Expand Up @@ -127,3 +135,74 @@ describe('appJsonBody', () => {
expect(seen).toEqual([aborted]);
});
});

describe('readOptionalAppJsonBody', () => {
it.each([
['no body', ''],
['only whitespace', ' \r\n\t'],
])('reads %s as an empty object', async (_n, body) => {
const res = await post('/api/app/projects/p1/duplicate', body);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ received: {} });
});

it('parses a body that is sent', async () => {
const res = await post(
'/api/app/projects/p1/duplicate',
' {"name":"Copy"} ',
);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ received: { name: 'Copy' } });
});

it.each([
['a lone brace', '{'],
['a truncated body', '{"name":"Co'],
['a body that is not JSON', 'name=Copy'],
])(
'answers %s with the door’s 400 INVALID_JSON, never as no body',
async (_n, body) => {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
const res = await post('/api/app/projects/p1/duplicate', body, {
'x-request-id': 'req-optional',
});
expect(res.status).toBe(400);
expect(await res.json()).toEqual({
error: INVALID_JSON_MESSAGE,
code: 'INVALID_JSON',
requestId: 'req-optional',
});
expect(errors).not.toHaveBeenCalled();
},
);

it('passes a body the client stopped sending through, never as no body', async () => {
const hono = new Hono();
const seen: unknown[] = [];
hono.onError((err, c) => {
seen.push(err);
return c.text('seen', 500);
});
hono.use('/api/app/*', appJsonBody());
hono.post('/api/app/optional', async (c) =>
c.json({ received: await readOptionalAppJsonBody(c) }),
);
const aborted = Object.assign(new Error('aborted'), {
code: 'ECONNRESET',
});
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode('{"name":'));
controller.error(aborted);
},
});
const res = await hono.request('http://localhost/api/app/optional', {
method: 'POST',
body,
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- duplex is required for stream bodies and missing from the lib type
...({ duplex: 'half' } as unknown as RequestInit),
});
expect(res.status).toBe(500);
expect(seen).toEqual([aborted]);
});
});
24 changes: 21 additions & 3 deletions services/platform/backend/lib/app-json-body.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Env, MiddlewareHandler } from 'hono';
import type { Context, Env, MiddlewareHandler } from 'hono';
import { HTTPException } from 'hono/http-exception';

import { requestIdOf } from '../error-reporting.ts';
Expand All @@ -20,8 +20,9 @@ export const INVALID_JSON_MESSAGE = 'The request body is not valid JSON';
* before, a handler that falls back on a failed read
* (`c.req.json().catch(() => ({}))`) still gets its fallback, and a body
* the client stopped sending still fails with Node's `Error: aborted`, for
* the error handler to recognise as the client leaving. The REST door
* reads its bodies through `readJsonBody` (`rest/shared.ts`) instead.
* the error handler to recognise as the client leaving. An optional body
* reads through `readOptionalAppJsonBody` below. The REST door reads its
* bodies through `readJsonBody` (`rest/shared.ts`) instead.
*/
export function appJsonBody<E extends Env>(): MiddlewareHandler<E> {
return async (c, next) => {
Expand Down Expand Up @@ -50,3 +51,20 @@ export function appJsonBody<E extends Env>(): MiddlewareHandler<E> {
await next();
};
}

/**
* The body of an app route whose body is OPTIONAL, read through the door's
* reader above: nothing sent (or only whitespace) reads as `{}`, and a body
* that is sent must be JSON — a truncated or malformed one answers the
* door's 400 `INVALID_JSON`, as a required body does. The former
* `c.req.json().catch(() => ({}))` read a corrupted body as an omitted one,
* so a lone `{` duplicated a project under its default name (#3599). The
* REST door's twin is `readOptionalJsonBody` (`rest/shared.ts`).
*/
export async function readOptionalAppJsonBody<E extends Env>(
c: Context<E>,
): Promise<unknown> {
// Hono keeps the text it read, so the parse below sees the same bytes.
if ((await c.req.text()).trim() === '') return {};
return await c.req.json<unknown>();
}
2 changes: 1 addition & 1 deletion services/platform/tests/manual/reference/automation.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s
| [metrics](../suites/metrics.md) | Usage metric and granularity are validated URL search fields | 🔶 route + component | `app/routes/dashboard/$id/settings/metrics/usage.search.test.ts`, `app/features/analytics/usage/usage-metrics-page.test.tsx`; browser reload and history remain manual |
| [metrics](../suites/metrics.md) / [accessibility](../suites/accessibility.md) | The metrics charts (bar, area, line and donut) play their entry animation, and skip it when the reader prefers reduced motion, so the final figures show at once | ✅ component | `packages/ui/src/components/metrics/charts/charts-reduced-motion.test.tsx` |
| [metrics](../suites/metrics.md) | Backend error reporting sends no credential: a real HTTP request's cookies and body never leave, authorization, cookie, API-key, token, secret and session headers, webhook and share tokens in the URL, the transaction name and the recorded path, and credential query values are `[Filtered]` | ✅ automated | `backend/error-reporting.test.ts` (`scrubUrl`, `scrubEvent`, the real-server case) |
| [metrics](../suites/metrics.md) | Backend error reporting drops what is not a defect: a client that hangs up mid-upload (Node's `Error: aborted`, `ECONNRESET`, with the request's signal aborted) answers an unread 499 with one debug line on the app handler and the REST door, while the same error with the caller still connected (an outbound read cut short) and a defect thrown after the caller left are still reported; an empty, truncated or non-JSON app-door body answers 400 `INVALID_JSON` (`{error, code, requestId}`) through the one reader on `/api/app/*`, unreported, a handler's own `.catch` fallback intact | ✅ automated | `backend/error-reporting.test.ts` (the real-server abort cases), `backend/rest/v1.test.ts`, `backend/lib/app-json-body.test.ts`, `backend/app.json-body.test.ts` |
| [metrics](../suites/metrics.md) | Backend error reporting drops what is not a defect: a client that hangs up mid-upload (Node's `Error: aborted`, `ECONNRESET`, with the request's signal aborted) answers an unread 499 with one debug line on the app handler and the REST door, while the same error with the caller still connected (an outbound read cut short) and a defect thrown after the caller left are still reported; an empty, truncated or non-JSON app-door body answers 400 `INVALID_JSON` (`{error, code, requestId}`) through the one reader on `/api/app/*`, unreported, a handler's own `.catch` fallback intact, and an optional body (duplicating a project) reads none sent as `{}` but answers a sent one that does not parse the same way, duplicating nothing | ✅ automated | `backend/error-reporting.test.ts` (the real-server abort cases), `backend/rest/v1.test.ts`, `backend/lib/app-json-body.test.ts`, `backend/app.json-body.test.ts`, `backend/domains/projects/routes.test.ts` |
| [metrics](../suites/metrics.md) | Browser error reporting drops what is not a Tale defect: an error whose innermost frame is a browser extension (Chromium, Firefox, Safari, Safari-masked), a 4xx refusal (a `BackendApiError` under 500 or the `AppError` one becomes), a `fetch` transport failure (with or without the host the SDK appends) and a request the platform was briefly gone for (the edge's `UPSTREAM_UNAVAILABLE` at 502/503/504, the platform's `DATABASE_UNAVAILABLE` at 503, read from the real door's answer); it keeps every other 5xx, even one with structured data or either code at another status, an app TypeError and a stale-bundle import failure, and carries `NAV-B12`'s cancellation rule in the same `beforeSend`. Boundary errors reach the console as the Error itself; onboarding logs a readable code and warns on a taken slug or a forbidden creation; an invalid locale tag and a refused service worker warn | ✅ automated | `app/lib/sentry-normalize.test.ts` (`prepareSentryEvent`), `app/lib/backend/adapters.test.ts` (`isBackendRefusal`), `app/lib/backend/platform-unavailable.test.ts` (`isPlatformUnavailable`), `app/features/organization/components/onboarding/steps/workspace-step.test.tsx`, `packages/ui/src/components/error-boundaries/hooks/use-error-logger.test.ts`, `packages/ui/src/i18n/is-valid-locale.test.ts`, `packages/ui/src/pwa/sw-update-listener.test.tsx`; what a live GlitchTip project receives remains a deployment check |
| [knowledge](../suites/knowledge.md) | Contact bulk email/locale boundary validation; controlled-document filename remains readable beside its badge; failed website attempts are excluded from Indexed display | ✅ automated | `backend/domains/contacts/routes.test.ts`, `app/features/documents/hooks/use-documents-table-config.browser.test.tsx`, `app/features/websites/hooks/use-websites-table-config.test.tsx`, `app/features/websites/components/website-view-dialog.test.tsx`, `backend/integration-check.ts` (failed crawl is not indexed) |
| [responsive](../suites/responsive.md) | Long project titles retain the full Archived badge at 400 px in light and dark themes | ✅ Chromium | `app/features/projects/components/project-header.browser.test.tsx` |
Expand Down
2 changes: 1 addition & 1 deletion services/platform/tests/manual/reference/error-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ Never a rendered message — seeing one of these in the UI is itself a bug.
| `ORGANIZATION_CREATION_FORBIDDEN` (403) on organization creation | `POST /api/auth/organization/create` from a signed-in account whose address is not in `TALE_ORGANIZATION_CREATORS`, on a deployment that already holds an organization (the first one is always allowed; an unset variable keeps the route open to every signed-in user). The same rule answers `GET /api/app/organizations/capabilities` with `{"canCreate":false}`, which is why the app shows no **Create organization** entry. A managed deployment without `organizations.creators` never reaches this code: its proxy refuses the route first. |
| `API_KEY_CREATE_FORBIDDEN` (403) on key creation | `POST /api/auth/api-key/create` with the session of a Member or Editor who is Owner, Admin or Developer of no organization and holds no live `tale:models.api`, `tale:notifications.export` or `tale:rest.act-as` grant in any (SET-B27). The app shows such a member no **API** section, so the route is reached from DevTools or curl. A grant of any of the three admits the next create; a key made earlier keeps working with its holder's current role. |
| `UNAUTHORIZED` (401) with no credential at all | `GET /events`, `GET /api/app/…` or a control route with neither a session cookie nor a bearer key: the coded envelope (`{error, code: "UNAUTHORIZED"}`, `Cache-Control: no-store`) — it used to answer a bare `{"error":"unauthorized"}` a client branching on `code` could not read. In the app, a session that ends under an open tab meets it on the next request: the refused action says **Your session has ended. Sign in again.** (`common.errors.sessionEnded`) in the person's language, never the envelope's sentence for API clients, and a confirmation protects unsaved work before an explicit choice opens `/log-in` (AUTH-B12 – AUTH-B14). |
| `INVALID_JSON` (400) on the app door | Any `/api/app` write whose body is empty, cut short or not JSON at all — `curl -X POST -H 'Content-Type: application/json' -b <session cookie> https://<host>/api/app/users/notification-state/toast-shown` with no body, or `--data '{"version":"0.5'`: `{error: "The request body is not valid JSON", code: "INVALID_JSON", requestId}`, where it used to answer a text 500 and report a SyntaxError. Nothing reaches `SENTRY_DSN`. A route whose body is optional (closing a legal-hold matter) still reads a missing one as empty. The REST door answers the same mistake as `INVALID_BODY`. |
| `INVALID_JSON` (400) on the app door | Any `/api/app` write whose body is empty, cut short or not JSON at all — `curl -X POST -H 'Content-Type: application/json' -b <session cookie> https://<host>/api/app/users/notification-state/toast-shown` with no body, or `--data '{"version":"0.5'`: `{error: "The request body is not valid JSON", code: "INVALID_JSON", requestId}`, where it used to answer a text 500 and report a SyntaxError. Nothing reaches `SENTRY_DSN`. A route whose body is optional (closing a legal-hold matter) still reads a missing one as empty; duplicating a project (`POST /api/app/projects/<id>/duplicate`) does too, but answers a sent body that does not parse (`--data '{'`) with `INVALID_JSON` and creates no copy. The REST door answers the same mistake as `INVALID_BODY`. |
| `PROJECT_AGENT_HARNESS_INVALID` (400) | `POST /api/v1/projects/{id}/agents` with `harness: "cursor"` (shipped, but it brings its own credentials) or any unknown slug: the envelope names the eligible set in `data.harnesses` — the list `GET /api/v1/models` answers under `harnesses` — and nothing is written. |
| `PROJECT_AGENT_MANAGED` (409) | `PUT /api/v1/projects/{id}/agents/{agentId}` (or the app's `POST /api/app/projects/agents/{agentId}`) naming a project's standard agent: nobody edits it, and nothing is written. The Agents tab offers no **Edit agent** on its row; **Delete agent** still removes it. |
| `STANDARD_AGENT_NOT_NEEDED` (409) | `POST /api/app/projects/{id}/standard-agent` for a project that has agents of its own and no standard agent. The UI never offers **Standard agent** there; nothing is written. |
Expand Down