Skip to content

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

feat: allow predefined api keys on create api route (#9872)

Steffen Schmitz1ded68ce4f9a
diff --git a/fern/apis/server/definition/projects.yml b/fern/apis/server/definition/projects.yml
index b1b4fcce8e..be2624ec78 100644
--- a/fern/apis/server/definition/projects.yml
+++ b/fern/apis/server/definition/projects.yml
@@ -80,6 +80,12 @@ service:
note:
type: optional<string>
docs: Optional note for the API key
+ publicKey:
+ type: optional<string>
+ docs: Optional predefined public key. Must start with 'pk-lf-'. If provided, secretKey must also be provided.
+ secretKey:
+ type: optional<string>
+ docs: Optional predefined secret key. Must start with 'sk-lf-'. If provided, publicKey must also be provided.
response: ApiKeyResponse
deleteApiKey:
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 1fcd93dae9..05b2cecdcf 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -3246,6 +3246,18 @@ paths:
type: string
nullable: true
description: Optional note for the API key
+ publicKey:
+ type: string
+ nullable: true
+ description: >-
+ Optional predefined public key. Must start with 'pk-lf-'. If
+ provided, secretKey must also be provided.
+ secretKey:
+ type: string
+ nullable: true
+ description: >-
+ Optional predefined secret key. Must start with 'sk-lf-'. If
+ provided, publicKey must also be provided.
/api/public/projects/{projectId}/apiKeys/{apiKeyId}:
delete:
description: Delete an API key for a project (requires organization-scoped API key)
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 1db080ef06..7a83f4c830 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -2374,7 +2374,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"note\": \"example\"\n}",
+ "raw": "{\n \"note\": \"example\",\n \"publicKey\": \"example\",\n \"secretKey\": \"example\"\n}",
"options": {
"raw": {
"language": "json"
diff --git a/web/src/__tests__/async/projects-api.servertest.ts b/web/src/__tests__/async/projects-api.servertest.ts
index 0da7686768..14b3f83135 100644
--- a/web/src/__tests__/async/projects-api.servertest.ts
+++ b/web/src/__tests__/async/projects-api.servertest.ts
@@ -722,6 +722,157 @@ describe("Projects API", () => {
expect(result.status).toBe(404);
expect(result.body.message).toContain("Project not found");
});
+
+ it("should create an API key with predefined keys", async () => {
+ const note = `Test API Key with Predefined Keys ${randomUUID().substring(0, 8)}`;
+ const predefinedPublicKey = `pk-lf-${randomUUID()}`;
+ const predefinedSecretKey = `sk-lf-${randomUUID()}`;
+
+ const response = await makeZodVerifiedAPICall(
+ ApiKeyCreationResponseSchema,
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ {
+ note,
+ publicKey: predefinedPublicKey,
+ secretKey: predefinedSecretKey,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ 201,
+ );
+
+ expect(response.status).toBe(201);
+ expect(response.body).toHaveProperty("id");
+ expect(response.body.publicKey).toBe(predefinedPublicKey);
+ expect(response.body.secretKey).toBe(predefinedSecretKey);
+ expect(response.body.note).toBe(note);
+
+ // Store for cleanup
+ createdApiKeyId = response.body.id;
+
+ // Verify the API key was created with the predefined keys
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { id: response.body.id },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.publicKey).toBe(predefinedPublicKey);
+ });
+
+ it("should return 400 when only publicKey is provided without secretKey", async () => {
+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;
+ const predefinedPublicKey = `pk-lf-${randomUUID()}`;
+
+ const result = await makeAPICall(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ {
+ note,
+ publicKey: predefinedPublicKey,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+
+ expect(result.status).toBe(400);
+ expect(result.body.message).toContain(
+ "Both publicKey and secretKey must be provided together",
+ );
+ });
+
+ it("should return 400 when only secretKey is provided without publicKey", async () => {
+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;
+ const predefinedSecretKey = `sk-lf-${randomUUID()}`;
+
+ const result = await makeAPICall(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ {
+ note,
+ secretKey: predefinedSecretKey,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+
+ expect(result.status).toBe(400);
+ expect(result.body.message).toContain(
+ "Both publicKey and secretKey must be provided together",
+ );
+ });
+
+ it("should return 400 when publicKey does not start with pk-lf-", async () => {
+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;
+ const invalidPublicKey = `invalid-${randomUUID()}`;
+ const predefinedSecretKey = `sk-lf-${randomUUID()}`;
+
+ const result = await makeAPICall(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ {
+ note,
+ publicKey: invalidPublicKey,
+ secretKey: predefinedSecretKey,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+
+ expect(result.status).toBe(400);
+ expect(result.body.message).toContain("publicKey must start with");
+ });
+
+ it("should return 400 when secretKey does not start with sk-lf-", async () => {
+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;
+ const predefinedPublicKey = `pk-lf-${randomUUID()}`;
+ const invalidSecretKey = `invalid-${randomUUID()}`;
+
+ const result = await makeAPICall(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ {
+ note,
+ publicKey: predefinedPublicKey,
+ secretKey: invalidSecretKey,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+
+ expect(result.status).toBe(400);
+ expect(result.body.message).toContain("secretKey must start with");
+ });
+
+ it("should return 409 when predefined publicKey already exists", async () => {
+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;
+ const duplicatePublicKey = `pk-lf-${randomUUID()}`;
+ const secretKey1 = `sk-lf-${randomUUID()}`;
+ const secretKey2 = `sk-lf-${randomUUID()}`;
+
+ // Create first API key with predefined keys
+ const firstResponse = await makeAPICall(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ {
+ note,
+ publicKey: duplicatePublicKey,
+ secretKey: secretKey1,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(firstResponse.status).toBe(201);
+ createdApiKeyId = firstResponse.body.id;
+
+ // Try to create second API key with same publicKey but different secretKey
+ const secondResponse = await makeAPICall(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ {
+ note: `${note} duplicate`,
+ publicKey: duplicatePublicKey,
+ secretKey: secretKey2,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+
+ expect(secondResponse.status).toBe(409);
+ expect(secondResponse.body.message).toContain("already exists");
+ });
});
describe("DELETE /api/public/projects/[projectId]/apiKeys/[apiKeyId]", () => {
diff --git a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts
index a77bed62bf..96a5c8d0f4 100644
--- a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts
+++ b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts
@@ -52,6 +52,8 @@ export async function handleCreateApiKey(
// Validate the request body
const createApiKeySchema = z.object({
note: z.string().optional(),
+ publicKey: z.string().optional(),
+ secretKey: z.string().optional(),
});
const validationResult = createApiKeySchema.safeParse(req.body);
@@ -63,30 +65,71 @@ export async function handleCreateApiKey(
});
}
- const { note } = validationResult.data;
+ const { note, publicKey, secretKey } = validationResult.data;
- // Create the API key
- const apiKeyMeta = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- note,
- scope: "PROJECT",
- });
+ // Validate predefined keys if provided
+ if (publicKey || secretKey) {
+ // Both keys must be provided together
+ if (!publicKey || !secretKey) {
+ return res.status(400).json({
+ message:
+ "Both publicKey and secretKey must be provided together when specifying predefined keys",
+ });
+ }
- // Log the API key creation
- await auditLog({
- resourceType: "apiKey",
- resourceId: apiKeyMeta.id,
- action: "create",
- orgId: orgId,
- projectId: projectId,
- orgRole: "ADMIN",
- apiKeyId: "ORG_KEY",
- });
+ // Validate key format
+ if (!publicKey.startsWith("pk-lf-")) {
+ return res.status(400).json({
+ message: "publicKey must start with 'pk-lf-'",
+ });
+ }
+
+ if (!secretKey.startsWith("sk-lf-")) {
+ return res.status(400).json({
+ message: "secretKey must start with 'sk-lf-'",
+ });
+ }
+ }
+
+ try {
+ // Create the API key
+ const apiKeyMeta = await createAndAddApiKeysToDb({
+ prisma,
+ entityId: projectId,
+ note,
+ scope: "PROJECT",
+ predefinedKeys:
+ publicKey && secretKey ? { publicKey, secretKey } : undefined,
+ });
- logger.info(
- `Created API key ${apiKeyMeta.id} for project ${projectId} via public API`,
- );
+ // Log the API key creation
+ await auditLog({
+ resourceType: "apiKey",
+ resourceId: apiKeyMeta.id,
+ action: "create",
+ orgId: orgId,
+ projectId: projectId,
+ orgRole: "ADMIN",
+ apiKeyId: "ORG_KEY",
+ });
- return res.status(201).json(apiKeyMeta);
+ logger.info(
+ `Created API key ${apiKeyMeta.id} for project ${projectId} via public API`,
+ );
+
+ return res.status(201).json(apiKeyMeta);
+ } catch (error) {
+ // Handle database unique constraint violations
+ if (
+ error instanceof Error &&
+ (error.message.includes("Unique constraint") ||
+ error.message.includes("unique constraint"))
+ ) {
+ return res.status(409).json({
+ message:
+ "API key with the provided publicKey or secretKey already exists",
+ });
+ }
+ throw error;
+ }
}