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
6 changes: 6 additions & 0 deletions .server-changes/sanitize-api-500-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
area: webapp
type: fix
---

Stop leaking raw exception messages on 500 responses across webapp API routes; return a generic error string and log the full error server-side instead.
6 changes: 6 additions & 0 deletions .server-changes/sentry-trace-id-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
area: webapp
type: improvement
---

Stamp the active OpenTelemetry trace_id and span_id onto every Sentry event so issues can be cross-referenced with traces in any OTel backend.
3 changes: 3 additions & 0 deletions apps/webapp/app/env.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ const EnvironmentSchema = z
SMTP_PASSWORD: z.string().optional(),

PLAIN_API_KEY: z.string().optional(),
PLAIN_CUSTOMER_CARDS_SECRET: z.string().optional(),
PLAIN_CUSTOMER_CARDS_KEY: z.string().optional(),
PLAIN_CUSTOMER_CARDS_HEADERS: z.string().optional(),
WORKER_SCHEMA: z.string().default("graphile_worker"),
WORKER_CONCURRENCY: z.coerce.number().int().default(10),
WORKER_POLL_INTERVAL: z.coerce.number().int().default(1000),
Expand Down
9 changes: 7 additions & 2 deletions apps/webapp/app/models/admin.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,13 @@ export async function adminGetOrganizations(userId: string, { page, search }: Se
};
}

export async function redirectWithImpersonation(request: Request, userId: string, path: string) {
const user = await requireUser(request);
export async function redirectWithImpersonation(
request: Request,
userId: string,
path: string,
currentUser?: { id: string; admin: boolean }
) {
const user = currentUser ?? (await requireUser(request));
if (!user.admin) {
throw new Error("Unauthorized");
}
Expand Down
26 changes: 4 additions & 22 deletions apps/webapp/app/routes/admin._index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { MagnifyingGlassIcon } from "@heroicons/react/20/solid";
import { Form } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/server-runtime";
import { redirect } from "@remix-run/server-runtime";
import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
import { typedjson, useTypedLoaderData } from "remix-typedjson";
import { z } from "zod";
import { Button, LinkButton } from "~/components/primitives/Buttons";
import { CopyableText } from "~/components/primitives/CopyableText";
import { Header1 } from "~/components/primitives/Headers";
import { Input } from "~/components/primitives/Input";
import { PaginationControls } from "~/components/primitives/Pagination";
import { Paragraph } from "~/components/primitives/Paragraph";
Expand All @@ -19,9 +17,7 @@ import {
TableHeaderCell,
TableRow,
} from "~/components/primitives/Table";
import { useUser } from "~/hooks/useUser";
import { adminGetUsers, redirectWithImpersonation } from "~/models/admin.server";
import { commitImpersonationSession, setImpersonationId } from "~/services/impersonation.server";
import { adminGetUsers } from "~/models/admin.server";
import { requireUserId } from "~/services/session.server";
import { createSearchParams } from "~/utils/searchParams";

Expand All @@ -32,7 +28,7 @@ export const SearchParams = z.object({

export type SearchParams = z.infer<typeof SearchParams>;

export const loader = async ({ request, params }: LoaderFunctionArgs) => {
export const loader = async ({ request }: LoaderFunctionArgs) => {
const userId = await requireUserId(request);

const searchParams = createSearchParams(request.url, SearchParams);
Expand All @@ -44,21 +40,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
return typedjson(result);
};

const FormSchema = z.object({ id: z.string() });

export async function action({ request }: ActionFunctionArgs) {
if (request.method.toLowerCase() !== "post") {
return new Response("Method not allowed", { status: 405 });
}

const payload = Object.fromEntries(await request.formData());
const { id } = FormSchema.parse(payload);

return redirectWithImpersonation(request, id, "/");
}

export default function AdminDashboardRoute() {
const user = useUser();
const { users, filters, page, pageCount } = useTypedLoaderData<typeof loader>();

return (
Expand Down Expand Up @@ -136,7 +118,7 @@ export default function AdminDashboardRoute() {
</TableCell>
<TableCell>{user.admin ? "✅" : ""}</TableCell>
<TableCell isSticky={true}>
<Form method="post" reloadDocument>
<Form method="post" action="/admin/impersonate" reloadDocument>
<input type="hidden" name="id" value={user.id} />
<Button
type="submit"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { type ActionFunctionArgs, json } from "@remix-run/server-runtime";
import { err, ok, type Result } from "neverthrow";
import { logger } from "~/services/logger.server";
import { authenticateAdminRequest } from "~/services/personalAccessToken.server";
import {
createPlatformNotification,
Expand Down Expand Up @@ -42,7 +43,8 @@ export async function action({ request }: ActionFunctionArgs) {
return json({ error: "Validation failed", details: error.issues }, { status: 400 });
}

return json({ error: error.message }, { status: 500 });
logger.error("Failed to create platform notification", { error });
return json({ error: "Something went wrong, please try again." }, { status: 500 });
}

return json(result.value, { status: 201 });
Expand Down
57 changes: 57 additions & 0 deletions apps/webapp/app/routes/admin.impersonate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { redirect, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/server-runtime";
import { z } from "zod";
import { redirectWithImpersonation } from "~/models/admin.server";
import { requireUser } from "~/services/session.server";
import { validateAndConsumeImpersonationToken } from "~/services/impersonation.server";
import { logger } from "~/services/logger.server";

const FormSchema = z.object({ id: z.string() });

async function handleImpersonationRequest(request: Request, userId: string): Promise<Response> {
const user = await requireUser(request);
if (!user.admin) {
return redirect("/");
}
return redirectWithImpersonation(request, userId, "/", user);
}

export const loader = async ({ request }: LoaderFunctionArgs) => {
const url = new URL(request.url);
const impersonateUserId = url.searchParams.get("impersonate");
const impersonationToken = url.searchParams.get("impersonationToken");

if (!impersonateUserId) {
return redirect("/admin");
}

if (!impersonationToken) {
logger.warn("Impersonation request missing token");
return redirect("/");
}

// Check admin BEFORE consuming the one-time token
const user = await requireUser(request);
if (!user.admin) {
return redirect("/");
}

const validatedUserId = await validateAndConsumeImpersonationToken(impersonationToken);

if (!validatedUserId || validatedUserId !== impersonateUserId) {
logger.warn("Invalid or expired impersonation token");
return redirect("/");
}

return redirectWithImpersonation(request, impersonateUserId, "/", user);
};

export async function action({ request }: ActionFunctionArgs) {
if (request.method.toLowerCase() !== "post") {
return new Response("Method not allowed", { status: 405 });
}

const payload = Object.fromEntries(await request.formData());
const { id } = FormSchema.parse(payload);

return handleImpersonationRequest(request, id);
}
34 changes: 26 additions & 8 deletions apps/webapp/app/routes/admin.notifications.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
TableRow,
} from "~/components/primitives/Table";
import { prisma } from "~/db.server";
import { logger } from "~/services/logger.server";
import { requireUserId } from "~/services/session.server";
import {
archivePlatformNotification,
Expand Down Expand Up @@ -234,7 +235,8 @@ async function handleCreateAction(formData: FormData, userId: string, isPreview:
{ status: 400 }
);
}
return typedjson({ error: err.message }, { status: 500 });
logger.error("Failed to create platform notification", { error: err });
return typedjson({ error: "Something went wrong, please try again." }, { status: 500 });
}

if (isPreview) {
Expand All @@ -249,8 +251,13 @@ async function handleArchiveAction(formData: FormData) {
return typedjson({ error: "Missing notificationId" }, { status: 400 });
}

await archivePlatformNotification(notificationId);
return typedjson({ success: true });
try {
await archivePlatformNotification(notificationId);
return typedjson({ success: true });
} catch (error) {
logger.error("Failed to archive platform notification", { error, notificationId });
return typedjson({ error: "Failed to archive notification, please try again." }, { status: 500 });
}
}

async function handleDeleteAction(formData: FormData) {
Expand All @@ -259,8 +266,13 @@ async function handleDeleteAction(formData: FormData) {
return typedjson({ error: "Missing notificationId" }, { status: 400 });
}

await deletePlatformNotification(notificationId);
return typedjson({ success: true });
try {
await deletePlatformNotification(notificationId);
return typedjson({ success: true });
} catch (error) {
logger.error("Failed to delete platform notification", { error, notificationId });
return typedjson({ error: "Failed to delete notification, please try again." }, { status: 500 });
}
}

async function handlePublishNowAction(formData: FormData) {
Expand All @@ -269,8 +281,13 @@ async function handlePublishNowAction(formData: FormData) {
return typedjson({ error: "Missing notificationId" }, { status: 400 });
}

await publishNowPlatformNotification(notificationId);
return typedjson({ success: true });
try {
await publishNowPlatformNotification(notificationId);
return typedjson({ success: true });
} catch (error) {
logger.error("Failed to publish platform notification", { error, notificationId });
return typedjson({ error: "Failed to publish notification, please try again." }, { status: 500 });
}
}

async function handleEditAction(formData: FormData) {
Expand Down Expand Up @@ -310,7 +327,8 @@ async function handleEditAction(formData: FormData) {
{ status: 400 }
);
}
return typedjson({ error: err.message }, { status: 500 });
logger.error("Failed to update platform notification", { error: err });
return typedjson({ error: "Something went wrong, please try again." }, { status: 500 });
}

return typedjson({ success: true, id: result.value.id });
Expand Down
8 changes: 3 additions & 5 deletions apps/webapp/app/routes/api.v1.batches.$batchParam.results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { z } from "zod";
import { ApiBatchResultsPresenter } from "~/presenters/v3/ApiBatchResultsPresenter.server";
import { ApiRunResultPresenter } from "~/presenters/v3/ApiRunResultPresenter.server";
import { authenticateApiRequest } from "~/services/apiAuth.server";
import { logger } from "~/services/logger.server";

const ParamsSchema = z.object({
/* This is the batch friendly ID */
Expand Down Expand Up @@ -36,10 +37,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {

return json(result);
} catch (error) {
if (error instanceof Error) {
return json({ error: error.message }, { status: 500 });
} else {
return json({ error: JSON.stringify(error) }, { status: 500 });
}
logger.error("Failed to load batch results", { error });
return json({ error: "Something went wrong, please try again." }, { status: 500 });
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
} catch (error) {
if (error instanceof ServiceValidationError) {
return json({ error: error.message }, { status: 400 });
} else if (error instanceof Error) {
logger.error("Error finalizing deployment", { error: error.message });
return json({ error: `Internal server error: ${error.message}` }, { status: 500 });
} else {
logger.error("Error finalizing deployment", { error: String(error) });
return json({ error: "Internal server error" }, { status: 500 });
}

logger.error("Error finalizing deployment", { error });
return json({ error: "Internal server error" }, { status: 500 });
}
}
9 changes: 3 additions & 6 deletions apps/webapp/app/routes/api.v1.deployments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
} catch (error) {
if (error instanceof ServiceValidationError) {
return json({ error: error.message }, { status: 400 });
} else if (error instanceof Error) {
logger.error("Error initializing deployment", { error: error.message });
return json({ error: `Internal server error: ${error.message}` }, { status: 500 });
} else {
logger.error("Error initializing deployment", { error: String(error) });
return json({ error: "Internal server error" }, { status: 500 });
}

logger.error("Error initializing deployment", { error });
return json({ error: "Internal server error" }, { status: 500 });
}
}

Expand Down
Loading
Loading