Skip to content

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

chore: improve user identification in observability (#6575)

Max Deichmann237076bf9214
diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.ts
index 859cd25f68..c084bc3e95 100644
--- a/packages/shared/src/server/instrumentation/index.ts
+++ b/packages/shared/src/server/instrumentation/index.ts
@@ -142,7 +142,13 @@ export const traceException = (
};
export const addUserToSpan = (
- attributes: { userId?: string; projectId?: string; email?: string },
+ attributes: {
+ userId?: string;
+ projectId?: string;
+ email?: string;
+ orgId?: string;
+ plan?: string;
+ },
span?: opentelemetry.Span,
) => {
const activeSpan = span ?? getCurrentSpan();
@@ -155,6 +161,8 @@ export const addUserToSpan = (
attributes.email && activeSpan.setAttribute("user.email", attributes.email);
attributes.projectId &&
activeSpan.setAttribute("project.id", attributes.projectId);
+ attributes.orgId && activeSpan.setAttribute("org.id", attributes.orgId);
+ attributes.plan && activeSpan.setAttribute("org.plan", attributes.plan);
};
export const getTracer = (name: string) => opentelemetry.trace.getTracer(name);
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.ts
index fa72fd9dbe..2dfd4aa6ad 100644
--- a/web/src/features/public-api/server/apiAuth.ts
+++ b/web/src/features/public-api/server/apiAuth.ts
@@ -118,159 +118,172 @@ export class ApiAuthService {
async verifyAuthHeaderAndReturnScope(
authHeader: string | undefined,
): Promise<AuthHeaderVerificationResult> {
- return instrumentAsync({ name: "api-auth-verify" }, async () => {
- if (!authHeader) {
- logger.error("No authorization header");
- return {
- validKey: false,
- error: "No authorization header",
- };
- }
+ const result: AuthHeaderVerificationResult = await instrumentAsync(
+ { name: "api-auth-verify" },
+ async () => {
+ if (!authHeader) {
+ logger.error("No authorization header");
+ return {
+ validKey: false,
+ error: "No authorization header",
+ };
+ }
- try {
- // Basic auth, full scope, needs secret key and public key
- if (authHeader.startsWith("Basic ")) {
- const { username: publicKey, password: secretKey } =
- this.extractBasicAuthCredentials(authHeader);
+ try {
+ // Basic auth, full scope, needs secret key and public key
+ if (authHeader.startsWith("Basic ")) {
+ const { username: publicKey, password: secretKey } =
+ this.extractBasicAuthCredentials(authHeader);
+
+ const salt = env.SALT;
+ const hashFromProvidedKey = createShaHash(secretKey, salt);
+
+ // fetches by redis if available, fallback to postgres
+ // api key from redis does
+ const apiKey =
+ await this.fetchApiKeyAndAddToRedis(hashFromProvidedKey);
+
+ let finalApiKey = apiKey;
+
+ if (!apiKey || !apiKey.fastHashedSecretKey) {
+ const slowKey = await this.prisma.apiKey.findUnique({
+ where: { publicKey },
+ include: {
+ project: { include: { organization: true } },
+ organization: true,
+ },
+ });
+
+ if (!slowKey) {
+ logger.error("No key found for public key", publicKey);
+ if (this.redis) {
+ logger.info(
+ `No key found, storing ${API_KEY_NON_EXISTENT} in redis`,
+ );
+ await this.addApiKeyToRedis(
+ hashFromProvidedKey,
+ API_KEY_NON_EXISTENT,
+ );
+ }
+ throw new Error("Invalid credentials");
+ }
- const salt = env.SALT;
- const hashFromProvidedKey = createShaHash(secretKey, salt);
+ const isValid = await verifySecretKey(
+ secretKey,
+ slowKey.hashedSecretKey,
+ );
- // fetches by redis if available, fallback to postgres
- // api key from redis does
- const apiKey =
- await this.fetchApiKeyAndAddToRedis(hashFromProvidedKey);
+ if (!isValid) {
+ logger.debug(`Old key is invalid: ${publicKey}`);
+ throw new Error("Invalid credentials");
+ }
- let finalApiKey = apiKey;
+ const shaKey = createShaHash(secretKey, salt);
- if (!apiKey || !apiKey.fastHashedSecretKey) {
- const slowKey = await this.prisma.apiKey.findUnique({
- where: { publicKey },
- include: {
- project: { include: { organization: true } },
- organization: true,
- },
- });
-
- if (!slowKey) {
- logger.error("No key found for public key", publicKey);
- if (this.redis) {
- logger.info(
- `No key found, storing ${API_KEY_NON_EXISTENT} in redis`,
- );
- await this.addApiKeyToRedis(
- hashFromProvidedKey,
- API_KEY_NON_EXISTENT,
- );
- }
+ await this.prisma.apiKey.update({
+ where: { publicKey },
+ data: {
+ fastHashedSecretKey: shaKey,
+ },
+ });
+ finalApiKey = this.convertToRedisRepresentation({
+ ...slowKey,
+ fastHashedSecretKey: shaKey,
+ });
+ }
+
+ if (!finalApiKey) {
+ logger.info("No project id found for key", publicKey);
throw new Error("Invalid credentials");
}
- const isValid = await verifySecretKey(
- secretKey,
- slowKey.hashedSecretKey,
- );
+ addUserToSpan({ projectId: finalApiKey.projectId ?? "" });
- if (!isValid) {
- logger.debug(`Old key is invalid: ${publicKey}`);
+ const plan = finalApiKey.plan;
+
+ if (!isPlan(plan)) {
+ logger.error("Invalid plan type for key", finalApiKey.plan);
throw new Error("Invalid credentials");
}
- const shaKey = createShaHash(secretKey, salt);
-
- await this.prisma.apiKey.update({
- where: { publicKey },
- data: {
- fastHashedSecretKey: shaKey,
+ const accessLevel =
+ finalApiKey.scope === "ORGANIZATION" ? "organization" : "project";
+
+ return {
+ validKey: true,
+ scope: {
+ projectId: finalApiKey.projectId,
+ accessLevel,
+ orgId: finalApiKey.orgId,
+ plan: plan,
+ rateLimitOverrides: finalApiKey.rateLimitOverrides ?? [],
+ apiKeyId: finalApiKey.id,
+ scope: finalApiKey.scope,
},
- });
- finalApiKey = this.convertToRedisRepresentation({
- ...slowKey,
- fastHashedSecretKey: shaKey,
- });
- }
-
- if (!finalApiKey) {
- logger.info("No project id found for key", publicKey);
- throw new Error("Invalid credentials");
+ };
}
+ // Bearer auth, limited scope, only needs public key
+ if (authHeader.startsWith("Bearer ")) {
+ const publicKey = authHeader.replace("Bearer ", "");
- addUserToSpan({ projectId: finalApiKey.projectId ?? "" });
+ const dbKey = await this.findDbKeyOrThrow(publicKey);
- const plan = finalApiKey.plan;
+ if (dbKey.scope === "ORGANIZATION") {
+ throw new Error(
+ "Unauthorized: Cannot use organization key with bearer auth",
+ );
+ }
- if (!isPlan(plan)) {
- logger.error("Invalid plan type for key", finalApiKey.plan);
- throw new Error("Invalid credentials");
+ addUserToSpan({ projectId: dbKey.projectId ?? "" });
+
+ const { orgId, cloudConfig } =
+ this.extractOrgIdAndCloudConfig(dbKey);
+
+ return {
+ validKey: true,
+ scope: {
+ projectId: dbKey.projectId,
+ accessLevel: "scores",
+ orgId,
+ plan: getOrganizationPlanServerSide(cloudConfig),
+ rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],
+ apiKeyId: dbKey.id,
+ scope: dbKey.scope,
+ },
+ };
}
-
- const accessLevel =
- finalApiKey.scope === "ORGANIZATION" ? "organization" : "project";
-
- return {
- validKey: true,
- scope: {
- projectId: finalApiKey.projectId,
- accessLevel,
- orgId: finalApiKey.orgId,
- plan: plan,
- rateLimitOverrides: finalApiKey.rateLimitOverrides ?? [],
- apiKeyId: finalApiKey.id,
- scope: finalApiKey.scope,
- },
- };
- }
- // Bearer auth, limited scope, only needs public key
- if (authHeader.startsWith("Bearer ")) {
- const publicKey = authHeader.replace("Bearer ", "");
-
- const dbKey = await this.findDbKeyOrThrow(publicKey);
-
- if (dbKey.scope === "ORGANIZATION") {
- throw new Error(
- "Unauthorized: Cannot use organization key with bearer auth",
- );
+ } catch (error: unknown) {
+ logger.error(
+ `Error verifying auth header: ${error instanceof Error ? error.message : null}`,
+ error,
+ );
+
+ if (isPrismaException(error)) {
+ throw error;
}
- addUserToSpan({ projectId: dbKey.projectId ?? "" });
-
- const { orgId, cloudConfig } = this.extractOrgIdAndCloudConfig(dbKey);
-
return {
- validKey: true,
- scope: {
- projectId: dbKey.projectId,
- accessLevel: "scores",
- orgId,
- plan: getOrganizationPlanServerSide(cloudConfig),
- rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],
- apiKeyId: dbKey.id,
- scope: dbKey.scope,
- },
+ validKey: false,
+ error:
+ (error instanceof Error ? error.message : "Authorization error") +
+ ". Confirm that you've configured the correct host.",
};
}
- } catch (error: unknown) {
- logger.error(
- `Error verifying auth header: ${error instanceof Error ? error.message : null}`,
- error,
- );
-
- if (isPrismaException(error)) {
- throw error;
- }
-
return {
validKey: false,
- error:
- (error instanceof Error ? error.message : "Authorization error") +
- ". Confirm that you've configured the correct host.",
+ error: "Invalid authorization header",
};
- }
- return {
- validKey: false,
- error: "Invalid authorization header",
- };
- });
+ },
+ );
+ // this adds the projectid to the root span of the request which makes it easier to find traces for specific projects
+ if (result.validKey && result.scope?.projectId) {
+ addUserToSpan({
+ projectId: result.scope.projectId,
+ orgId: result.scope.orgId,
+ plan: result.scope.plan,
+ });
+ }
+ return result;
}
private extractBasicAuthCredentials(basicAuthHeader: string): {