Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

Improve access control of traces (merge public and private implementation) (#480)

Marc Klingen7a988da0b862
diff --git a/src/components/trace/ObservationPreview.tsx b/src/components/trace/ObservationPreview.tsx
index c8aca69858..20286a2540 100644
--- a/src/components/trace/ObservationPreview.tsx
+++ b/src/components/trace/ObservationPreview.tsx
@@ -26,10 +26,12 @@ export const ObservationPreview = (props: {
projectId: string;
scores: Score[];
currentObservationId: string;
+ traceId: string;
}) => {
- const observationWithInputAndOutput = api.observations.byId.useQuery(
- props.currentObservationId,
- );
+ const observationWithInputAndOutput = api.observations.byId.useQuery({
+ observationId: props.currentObservationId,
+ traceId: props.traceId,
+ });
const preloadedObservation = props.observations.find(
(o) => o.id === props.currentObservationId,
diff --git a/src/components/trace/index.tsx b/src/components/trace/index.tsx
index f58ae0b573..fe8c71bbac 100644
--- a/src/components/trace/index.tsx
+++ b/src/components/trace/index.tsx
@@ -7,12 +7,12 @@ import Header from "@/src/components/layouts/header";
import { Badge } from "@/src/components/ui/badge";
import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
import Decimal from "decimal.js";
-import { type RouterOutput } from "@/src/utils/types";
import { StringParam, useQueryParam } from "use-query-params";
import { PublishTraceSwitch } from "@/src/features/public-traces/components/PublishTraceSwitch";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
import { useRouter } from "next/router";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
+import { api } from "@/src/utils/api";
export function Trace(props: {
observations: Array<ObservationReturnType>;
@@ -51,6 +51,7 @@ export function Trace(props: {
scores={props.scores}
projectId={props.projectId}
currentObservationId={currentObservationId}
+ traceId={props.trace.id}
/>
)}
</div>
@@ -67,13 +68,10 @@ export function Trace(props: {
);
}
-export function TracePage({
- trace,
-}: {
- trace: RouterOutput["traces"]["byId"];
-}) {
+export function TracePage({ traceId }: { traceId: string }) {
const router = useRouter();
- const totalCost = trace.observations.reduce(
+ const trace = api.traces.byId.useQuery({ traceId });
+ const totalCost = trace.data?.observations.reduce(
(acc, o) => {
if (!o.price) return acc;
@@ -84,6 +82,8 @@ export function TracePage({
undefined as Decimal | undefined,
);
+ if (!trace.data) return <div>loading...</div>;
+
return (
<div className="flex flex-col overflow-hidden xl:container lg:h-[calc(100vh-100px)] xl:h-[calc(100vh-50px)]">
<Header
@@ -91,12 +91,12 @@ export function TracePage({
actionButtons={
<>
<PublishTraceSwitch
- traceId={trace.id}
- projectId={trace.projectId}
- isPublic={trace.public}
+ traceId={trace.data.id}
+ projectId={trace.data.projectId}
+ isPublic={trace.data.public}
/>
<DetailPageNav
- currentId={router.query.traceId as string}
+ currentId={traceId}
path={(id) =>
`/project/${router.query.projectId as string}/traces/${id}`
}
@@ -106,10 +106,10 @@ export function TracePage({
}
/>
<div className="flex gap-2">
- {trace.userId ? (
- <Badge variant="outline">User ID: {trace.userId}</Badge>
+ {trace.data.userId ? (
+ <Badge variant="outline">User ID: {trace.data.userId}</Badge>
) : null}
- <TraceAggUsageBadge observations={trace.observations ?? []} />
+ <TraceAggUsageBadge observations={trace.data.observations ?? []} />
{totalCost ? (
<Badge variant="outline">
Total cost: {totalCost.toString()} USD
@@ -118,11 +118,11 @@ export function TracePage({
</div>
<div className="mt-5 flex-1 overflow-hidden border-t pt-5">
<Trace
- key={trace.id}
- trace={trace}
- scores={trace.scores}
- projectId={trace.projectId}
- observations={trace.observations ?? []}
+ key={trace.data.id}
+ trace={trace.data}
+ scores={trace.data.scores}
+ projectId={trace.data.projectId}
+ observations={trace.data.observations ?? []}
/>
</div>
</div>
diff --git a/src/pages/project/[projectId]/traces/[traceId].tsx b/src/pages/project/[projectId]/traces/[traceId].tsx
index 0da933ce1a..96b4cb2e90 100644
--- a/src/pages/project/[projectId]/traces/[traceId].tsx
+++ b/src/pages/project/[projectId]/traces/[traceId].tsx
@@ -1,15 +1,9 @@
import { useRouter } from "next/router";
-import { api } from "@/src/utils/api";
import { TracePage } from "@/src/components/trace";
export default function Trace() {
const router = useRouter();
const traceId = router.query.traceId as string;
- const trace = api.traces.byId.useQuery(traceId);
- if (trace.data) {
- return <TracePage trace={trace.data} />;
- } else {
- return <div>loading...</div>;
- }
+ return <TracePage traceId={traceId} />;
}
diff --git a/src/pages/public/traces/[traceId].tsx b/src/pages/public/traces/[traceId].tsx
index 420a1a9c26..7d1c7901e1 100644
--- a/src/pages/public/traces/[traceId].tsx
+++ b/src/pages/public/traces/[traceId].tsx
@@ -1,21 +1,12 @@
import { useRouter } from "next/router";
-import { api } from "@/src/utils/api";
import { TracePage } from "@/src/components/trace";
export default function PublicTracePage() {
const router = useRouter();
const traceId = router.query.traceId as string;
-
- const trace = api.traces.byIdPublic.useQuery(traceId);
-
- if (trace.isLoading) return <div>loading...</div>;
- if (trace.data) {
- return (
- <div className="py-5">
- <TracePage trace={trace.data} />
- </div>
- );
- } else {
- return <div>Not available</div>;
- }
+ return (
+ <div className="py-5">
+ <TracePage traceId={traceId} />
+ </div>
+ );
}
diff --git a/src/server/api/routers/observations.ts b/src/server/api/routers/observations.ts
index 3aea282fd1..340a0d0d12 100644
--- a/src/server/api/routers/observations.ts
+++ b/src/server/api/routers/observations.ts
@@ -1,34 +1,34 @@
-import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";
+import {
+ createTRPCRouter,
+ protectedGetTraceProcedure,
+} from "@/src/server/api/trpc";
import { z } from "zod";
export const observationsRouter = createTRPCRouter({
- byId: protectedProcedure.input(z.string()).query(async ({ input, ctx }) => {
- // also works for other observations
- const generation = await ctx.prisma.observation.findFirstOrThrow({
- where: {
- id: input,
- ...(ctx.session.user.admin === true
- ? undefined
- : {
- project: {
- members: {
- some: {
- userId: ctx.session.user.id,
- },
- },
- },
- }),
- },
- });
+ byId: protectedGetTraceProcedure
+ .input(
+ z.object({
+ observationId: z.string(),
+ traceId: z.string(), // required for protectedGetTraceProcedure
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ // also works for other observations
+ const generation = await ctx.prisma.observation.findFirstOrThrow({
+ where: {
+ id: input.observationId,
+ traceId: input.traceId,
+ },
+ });
- const scores = generation.traceId
- ? await ctx.prisma.score.findMany({
- where: {
- traceId: generation.traceId,
- },
- })
- : [];
+ const scores = generation.traceId
+ ? await ctx.prisma.score.findMany({
+ where: {
+ traceId: generation.traceId,
+ },
+ })
+ : [];
- return { ...generation, scores };
- }),
+ return { ...generation, scores };
+ }),
});
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 71a791789f..b953d43bb0 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -2,9 +2,8 @@ import { z } from "zod";
import {
createTRPCRouter,
- protectedProcedure,
+ protectedGetTraceProcedure,
protectedProjectProcedure,
- publicProcedure,
} from "@/src/server/api/trpc";
import {
type Observation,
@@ -211,102 +210,13 @@ export const traceRouter = createTRPCRouter({
};
return res;
}),
- byId: protectedProcedure.input(z.string()).query(async ({ input, ctx }) => {
- const [trace, observations, pricings] = await Promise.all([
- ctx.prisma.trace.findFirstOrThrow({
- where: {
- id: input,
- ...(ctx.session.user.admin === true
- ? undefined
- : {
- project: {
- members: {
- some: {
- userId: ctx.session.user.id,
- },
- },
- },
- }),
- },
- include: {
- scores: true,
- },
- }),
- ctx.prisma.observation.findMany({
- where: {
- traceId: {
- equals: input,
- not: null,
- },
- ...(ctx.session.user.admin === true
- ? undefined
- : {
- project: {
- members: {
- some: {
- userId: ctx.session.user.id,
- },
- },
- },
- }),
- },
- }),
- ctx.prisma.pricing.findMany(),
- ]);
-
- const obsStartTimes = observations
- .map((o) => o.startTime)
- .sort((a, b) => a.getTime() - b.getTime());
- const obsEndTimes = observations
- .map((o) => o.endTime)
- .filter((t) => t)
- .sort((a, b) => (a as Date).getTime() - (b as Date).getTime());
- const latencyMs =
- obsStartTimes.length > 0
- ? obsEndTimes.length > 0
- ? (obsEndTimes[obsEndTimes.length - 1] as Date).getTime() -
- obsStartTimes[0]!.getTime()
- : obsStartTimes.length > 1
- ? obsStartTimes[obsStartTimes.length - 1]!.getTime() -
- obsStartTimes[0]!.getTime()
- : undefined
- : undefined;
-
- const enrichedObservations = observations.map(
- ({ input, output, ...rest }) => {
- return {
- ...rest,
- price: rest.model
- ? calculateTokenCost(pricings, {
- model: rest.model,
- totalTokens: new Decimal(rest.totalTokens),
- promptTokens: new Decimal(rest.promptTokens),
- completionTokens: new Decimal(rest.completionTokens),
- input: input,
- output: output,
- })
- : undefined,
- };
- },
- );
-
- return {
- ...trace,
- latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
- observations: enrichedObservations as ObservationReturnType[],
- };
- }),
-
- // exact copy of previoud byId, but without the project member check
- // output must be the same as consumed by the same component
- byIdPublic: publicProcedure
- .input(z.string())
+ byId: protectedGetTraceProcedure
+ .input(z.object({ traceId: z.string() }))
.query(async ({ input, ctx }) => {
const [trace, observations, pricings] = await Promise.all([
- ctx.prisma.trace.findFirst({
+ ctx.prisma.trace.findFirstOrThrow({
where: {
- id: input,
- public: true,
+ id: input.traceId,
},
include: {
scores: true,
@@ -315,7 +225,7 @@ export const traceRouter = createTRPCRouter({
ctx.prisma.observation.findMany({
where: {
traceId: {
- equals: input,
+ equals: input.traceId,
not: null,
},
},
@@ -323,26 +233,6 @@ export const traceRouter = createTRPCRouter({
ctx.prisma.pricing.findMany(),
]);
- if (!trace) {
- return null;
- }
-
- const enrichedObservations = observations.map((observation) => {
- return {
- ...observation,
- price: observation.model
- ? calculateTokenCost(pricings, {
- model: observation.model,
- totalTokens: new Decimal(observation.totalTokens),
- promptTokens: new Decimal(observation.promptTokens),
- completionTokens: new Decimal(observation.completionTokens),
- input: observation.input,
- output: observation.output,
- })
- : undefined,
- };
- });
-
const obsStartTimes = observations
.map((o) => o.startTime)
.sort((a, b) => a.getTime() - b.getTime());
@@ -361,12 +251,28 @@ export const traceRouter = createTRPCRouter({
: undefined
: undefined;
+ const enrichedObservations = observations.map(
+ ({ input, output, ...rest }) => {
+ return {
+ ...rest,
+ price: rest.model
+ ? calculateTokenCost(pricings, {
+ model: rest.model,
+ totalTokens: new Decimal(rest.totalTokens),
+ promptTokens: new Decimal(rest.promptTokens),
+ completionTokens: new Decimal(rest.completionTokens),
+ input: input,
+ output: output,
+ })
+ : undefined,
+ };
+ },
+ );
+
return {
...trace,
latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
- observations: enrichedObservations as Array<
- (typeof observations)[0] & { traceId: string } & { price?: Decimal }
- >,
+ observations: enrichedObservations as ObservationReturnType[],
};
}),
});
diff --git a/src/server/api/trpc.ts b/src/server/api/trpc.ts
index 8792415393..fc0a3c65c9 100644
--- a/src/server/api/trpc.ts
+++ b/src/server/api/trpc.ts
@@ -181,3 +181,63 @@ const enforceUserIsAuthedAndProjectMember = t.middleware(
export const protectedProjectProcedure = t.procedure.use(
enforceUserIsAuthedAndProjectMember,
);
+
+/*
+ * Protect trace-level getter routes.
+ * - Users need to be member of the project to access the trace.
+ * - Alternatively, the trace needs to be public.
+ */
+
+const inputTraceSchema = z.object({
+ traceId: z.string(),
+});
+
+const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
+ const result = inputTraceSchema.safeParse(rawInput);
+ if (!result.success)
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid input, traceId is required",
+ });
+
+ const traceId = result.data.traceId;
+
+ const trace = await prisma.trace.findFirst({
+ where: {
+ id: traceId,
+ },
+ select: {
+ public: true,
+ projectId: true,
+ },
+ });
+
+ if (!trace)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found",
+ });
+
+ const sessionProject = ctx.session?.user?.projects?.find(
+ ({ id }) => id === trace.projectId,
+ );
+
+ if (!trace.public && !sessionProject && ctx.session?.user?.admin !== true)
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message:
+ "User is not a member of this project and this trace is not public",
+ });
+
+ return next({
+ ctx: {
+ session: {
+ ...ctx.session,
+ projectRole:
+ ctx.session?.user?.admin === true ? "ADMIN" : sessionProject?.role,
+ },
+ },
+ });
+});
+
+export const protectedGetTraceProcedure = t.procedure.use(enforceTraceAccess);