Skip to content

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

fix: allow bearer auth for score ingestion via /api/public/ingestion (#1117)

Hassieb Pakzad85e5ea466192
diff --git a/src/__tests__/ingestion.servertest.ts b/src/__tests__/ingestion.servertest.ts
index 929f77f108..8e97a8cd87 100644
--- a/src/__tests__/ingestion.servertest.ts
+++ b/src/__tests__/ingestion.servertest.ts
@@ -795,10 +795,10 @@ describe("/api/public/ingestion API Endpoint", () => {
expect("errors" in responseOne.body).toBe(true);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body?.errors.length).toBe(1);
+ expect(responseOne.body.errors.length).toBe(1);
expect("successes" in responseOne.body).toBe(true);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body?.successes.length).toBe(1);
+ expect(responseOne.body.successes.length).toBe(1);
const dbTrace = await prisma.trace.findMany({
where: {
@@ -847,10 +847,10 @@ describe("/api/public/ingestion API Endpoint", () => {
expect("errors" in responseOne.body).toBe(true);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body?.errors.length).toBe(1);
+ expect(responseOne.body.errors.length).toBe(1);
expect("successes" in responseOne.body).toBe(true);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body?.successes.length).toBe(1);
+ expect(responseOne.body.successes.length).toBe(1);
const dbTrace = await prisma.trace.findMany({
where: {
@@ -897,10 +897,10 @@ describe("/api/public/ingestion API Endpoint", () => {
expect("errors" in responseOne.body).toBe(true);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body?.errors.length).toBe(1);
+ expect(responseOne.body.errors.length).toBe(1);
expect("successes" in responseOne.body).toBe(true);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body?.successes.length).toBe(1);
+ expect(responseOne.body.successes.length).toBe(1);
const dbTrace = await prisma.trace.findMany({
where: {
@@ -1414,4 +1414,355 @@ IB Home / . . . / News / News about the IB / Why ChatGPT is an o
expect(cleanedEvent).toStrictEqual(expected);
});
});
+
+ it("should allow score ingestion via Basic auth", async () => {
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+ const traceId = "trace_id";
+
+ const scoreId = "score_id";
+ const scoreEventId = "score_event_id";
+ const scoreName = "score-name";
+ const scoreValue = 100.5;
+
+ // Seed db with a trace to be scored
+ await prisma.trace.create({
+ data: {
+ id: traceId,
+ name: "trace-name",
+ project: { connect: { id: projectId } },
+ },
+ });
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: scoreEventId,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: scoreId,
+ name: scoreName,
+ value: scoreValue,
+ traceId: traceId,
+ },
+ },
+ ],
+ });
+
+ expect(response.status).toBe(207);
+ expect(response.body.successes.length).toBe(1);
+ expect(response.body.successes[0]?.id).toBe(scoreEventId);
+ expect(response.body.errors.length).toBe(0);
+
+ const dbScore = await prisma.score.findUnique({
+ where: {
+ id: scoreId,
+ },
+ });
+
+ expect(dbScore?.id).toBe(scoreId);
+ expect(dbScore?.traceId).toBe(traceId);
+ expect(dbScore?.name).toBe(scoreName);
+ expect(dbScore?.value).toBe(scoreValue);
+ });
+
+ it("should allow score ingestion via Bearer auth", async () => {
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+ const traceId = "trace_id";
+ const bearerAuth = "Bearer pk-lf-1234567890";
+
+ const scoreId = "score_id";
+ const scoreEventId = "score_event_id";
+ const scoreName = "score-name";
+ const scoreValue = 100.5;
+
+ // Seed db with a trace to be scored
+ await prisma.trace.create({
+ data: {
+ id: traceId,
+ name: "trace-name",
+ project: { connect: { id: projectId } },
+ },
+ });
+
+ const response = await makeAPICall(
+ "POST",
+ "/api/public/ingestion",
+ {
+ batch: [
+ {
+ id: scoreEventId,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: scoreId,
+ name: scoreName,
+ value: scoreValue,
+ traceId: traceId,
+ },
+ },
+ ],
+ },
+ bearerAuth,
+ );
+
+ expect(response.status).toBe(207);
+ expect(response.body.successes.length).toEqual(1);
+ expect(response.body.successes[0]?.id).toBe(scoreEventId);
+ expect(response.body.errors.length).toBe(0);
+
+ const dbScore = await prisma.score.findUnique({
+ where: {
+ id: scoreId,
+ },
+ });
+
+ expect(dbScore?.id).toBe(scoreId);
+ expect(dbScore?.traceId).toBe(traceId);
+ expect(dbScore?.name).toBe(scoreName);
+ expect(dbScore?.value).toBe(scoreValue);
+ });
+
+ it("should throw an Auth error on Bearer Auth for all events that are NOT 'score-create'", async () => {
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+ const traceId = "trace_id";
+ const bearerAuth = "Bearer pk-lf-1234567890";
+
+ const scoreId = "score_id";
+ const scoreEventId = "score_event_id";
+ const scoreName = "score-name";
+ const scoreValue = 100.5;
+
+ const generationId = v4();
+ const spanId = v4();
+
+ const anotherTraceId = "another_trace_id";
+
+ // Seed db with a trace to be scored
+ await prisma.trace.create({
+ data: {
+ id: traceId,
+ name: "trace-name",
+ project: { connect: { id: projectId } },
+ },
+ });
+
+ const response = await makeAPICall(
+ "POST",
+ "/api/public/ingestion",
+ {
+ metadata: {
+ sdk_verion: "1.0.0",
+ sdk_name: "python",
+ },
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: anotherTraceId,
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ tags: ["tag-1", "tag-2"],
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ modelParameters: { key: "value" },
+ input: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ type: "GENERATION",
+ output: { key: "this is a great gpt output" },
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: spanId,
+ traceId: traceId,
+ type: "SPAN",
+ name: "span-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ },
+ {
+ id: scoreEventId,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: scoreId,
+ name: "score-name",
+ value: 100.5,
+ traceId: traceId,
+ },
+ },
+ ],
+ },
+ bearerAuth,
+ );
+
+ expect(response.status).toBe(207);
+ expect(response.body.successes.length).toEqual(1);
+ expect(response.body.successes[0]?.id).toEqual(scoreEventId);
+
+ expect(response.body.errors.length).toEqual(4);
+
+ const dbScore = await prisma.score.findUnique({
+ where: {
+ id: scoreId,
+ },
+ });
+
+ expect(await prisma.trace.count()).toBe(1);
+ expect(await prisma.trace.count({ where: { id: traceId } })).toBe(1);
+ expect(await prisma.observation.count()).toBe(0);
+
+ expect(dbScore?.id).toBe(scoreId);
+ expect(dbScore?.traceId).toBe(traceId);
+ expect(dbScore?.name).toBe(scoreName);
+ expect(dbScore?.value).toBe(scoreValue);
+ });
+
+ it("should error on Bearer Auth for a trace from different project", async () => {
+ const otherProjectId = "other_project_id";
+ const traceId = "trace_id";
+ const bearerAuth = "Bearer pk-lf-1234567890";
+
+ const scoreId = "score_id";
+ const scoreEventId = "score_event_id";
+ const scoreName = "score-name";
+ const scoreValue = 100.5;
+
+ // Seed db with a trace to be scored
+ try {
+ await prisma.project.create({
+ data: {
+ id: otherProjectId,
+ name: "another-project",
+ },
+ });
+
+ await prisma.trace.create({
+ data: {
+ id: traceId,
+ name: "trace-name",
+ project: { connect: { id: otherProjectId } },
+ },
+ });
+
+ const response = await makeAPICall(
+ "POST",
+ "/api/public/ingestion",
+ {
+ batch: [
+ {
+ id: scoreEventId,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: scoreId,
+ name: scoreName,
+ value: scoreValue,
+ traceId: traceId,
+ },
+ },
+ ],
+ },
+ bearerAuth,
+ );
+
+ expect(response.status).toBe(207);
+ expect(response.body.successes.length).toBe(0);
+ expect(response.body).toHaveProperty("errors");
+ expect(response.body.errors.length).toEqual(1);
+ expect(response.body.errors[0]?.id).toEqual(scoreEventId);
+
+ expect(await prisma.trace.count()).toBe(1);
+ expect(await prisma.trace.count({ where: { id: traceId } })).toBe(1);
+
+ const dbScore = await prisma.score.findUnique({
+ where: {
+ id: scoreId,
+ },
+ });
+
+ expect(dbScore).toBeNull();
+ } finally {
+ await prisma.project.delete({ where: { id: otherProjectId } });
+ }
+ });
+
+ it("should error on Bearer Auth with a trace that does not exist", async () => {
+ const traceId = "trace_id";
+ const bearerAuth = "Bearer pk-lf-1234567890";
+
+ const scoreId = "score_id";
+ const scoreEventId = "score_event_id";
+ const scoreName = "score-name";
+ const scoreValue = 100.5;
+
+ const response = await makeAPICall(
+ "POST",
+ "/api/public/ingestion",
+ {
+ batch: [
+ {
+ id: scoreEventId,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: scoreId,
+ name: scoreName,
+ value: scoreValue,
+ traceId: traceId,
+ },
+ },
+ ],
+ },
+ bearerAuth,
+ );
+
+ expect(response.status).toBe(207);
+ expect(response.body.successes.length).toBe(0);
+ expect(response.body.errors.length).toBe(1);
+ expect(response.body.errors[0]?.id).toBe(scoreEventId);
+
+ expect(await prisma.trace.count()).toBe(0);
+
+ const dbScore = await prisma.score.findUnique({
+ where: {
+ id: scoreId,
+ },
+ });
+
+ expect(dbScore).toBeNull();
+ });
});
diff --git a/src/__tests__/test-utils.ts b/src/__tests__/test-utils.ts
index e20d459f04..954e20c81a 100644
--- a/src/__tests__/test-utils.ts
+++ b/src/__tests__/test-utils.ts
@@ -27,21 +27,38 @@ export function createBasicAuthHeader(
return `Basic ${base64Credentials}`;
}
+export type IngestionAPIResponse = {
+ errors: ErrorIngestion[];
+ successes: SuccessfulIngestion[];
+};
+
+export type SuccessfulIngestion = {
+ id: string;
+ status: number;
+};
+
+export type ErrorIngestion = {
+ id: string;
+ status: number;
+ message: string;
+ error: string;
+};
+
export async function makeAPICall(
method: "POST" | "GET" | "PUT" | "DELETE" | "PATCH",
url: string,
body?: unknown,
+ auth?: string,
) {
const finalUrl = `http://localhost:3000/${url}`;
+ const authorization =
+ auth || createBasicAuthHeader("pk-lf-1234567890", "sk-lf-1234567890");
const options = {
method: method,
headers: {
Accept: "application/json",
"Content-Type": "application/json;charset=UTF-8",
- Authorization: createBasicAuthHeader(
- "pk-lf-1234567890",
- "sk-lf-1234567890",
- ),
+ Authorization: authorization,
},
// Conditionally include the body property if the method is not "GET"
...(method !== "GET" &&
@@ -50,7 +67,7 @@ export async function makeAPICall(
const a = await fetch(finalUrl, options);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- return { body: await a.json(), status: a.status };
+ return { body: (await a.json()) as IngestionAPIResponse, status: a.status };
}
export const setupUserAndProject = async () => {
diff --git a/src/pages/api/public/ingestion.ts b/src/pages/api/public/ingestion.ts
index 5294b18140..bb2a0b7647 100644
--- a/src/pages/api/public/ingestion.ts
+++ b/src/pages/api/public/ingestion.ts
@@ -56,11 +56,6 @@ export default async function handler(
message: authCheck.error,
});
- if (authCheck.scope.accessLevel !== "all")
- return res.status(403).json({
- message: "Access denied",
- });
-
const batchType = z.object({
batch: z.array(z.unknown()),
metadata: jsonSchema.nullish(),
@@ -246,6 +241,12 @@ const handleSingleEvent = async (
processor = new SdkLogProcessor(cleanedEvent);
}
+ // Deny access to non-score events if the access level is not "all"
+ // This is an additional safeguard to auth checks in EventProcessor
+ if (apiScope.accessLevel !== "all" && type !== eventTypes.SCORE_CREATE) {
+ throw new AuthenticationError("Access denied. Event type not allowed.");
+ }
+
return await processor.process(apiScope);
};