🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ai-gateway): default service key user ID to the key name (#19459)
Tobias Wochinger5dbf97895ce4
diff --git a/ai-gateway/README.md b/ai-gateway/README.mdindex 6dca7a37d3..f65961d88c 100644--- a/ai-gateway/README.md+++ b/ai-gateway/README.md@@ -69,23 +69,23 @@ The binary reads configuration from the process environment. The pnpm developmenscript loads the root `.env` before starting it; production and direct Cargo runsdo not load dotenv files:-| Variable | Default | Validation |-| ---------------------------------------------- | -------------- | -------------------------------------------------- |-| `LANGFUSE_AI_GATEWAY_WEB_URL` | unset; inference disabled | Trusted Web base URL, including any deployment prefix |-| `LANGFUSE_AI_GATEWAY_SERVICE_KEY` | unset | Required with Web URL; same key configured in Web |-| `LANGFUSE_AI_GATEWAY_ALLOW_HTTP_WEB_URL` | `false` | `true`, `false`; `true` also accepts a plain `http://` Web URL on any host. Only for internal traffic, such as Web's in-cluster Kubernetes Service (`http://<release>-web.<namespace>.svc.cluster.local:3000`) or another private network; never for a URL that crosses the public internet, because resolve responses carry provider API keys and requests carry the service key and ingestion tokens unencrypted. Resolution, model catalogs and trace uploads all use this URL. The gateway logs a warning at startup when it is used |-| `LANGFUSE_AI_GATEWAY_LISTEN_ADDRESS` | `0.0.0.0:8080` | IP address and port; IPv6 uses `[::]:8080` |-| `LANGFUSE_AI_GATEWAY_AUTO_INCREMENT_LISTEN_PORT` | `false` | `true`, `false`; the pnpm dev task sets `true` |-| `LANGFUSE_LOG_FORMAT` | `text` | `text`, `json` |-| `LANGFUSE_LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error`, `fatal` |-| `LANGFUSE_AI_GATEWAY_CONNECTION_DRAIN_TIMEOUT_SECONDS` | `10` | Integer from 1 to 300; connection drain after the shutdown signal. Replaces the deprecated `LANGFUSE_AI_GATEWAY_SHUTDOWN_TIMEOUT_SECONDS`, which is still read when the new name is unset. On ECS behind an ALB, the deregistration delay drains streams before SIGTERM, so use `1`. On Kubernetes the gateway drains streams itself, so set it to the stream time to protect (for example `300`) |-| `LANGFUSE_AI_GATEWAY_TELEMETRY_SHUTDOWN_TIMEOUT_SECONDS` | `10` | Integer from 1 to 300; telemetry flush after the drain ends. On ECS use most of `stopTimeout` (max 120), for example `115`. On Kubernetes `30` is enough; set `terminationGracePeriodSeconds` above the `preStop` sleep plus both timeouts |-| `LANGFUSE_AI_GATEWAY_TELEMETRY_BUFFER_BYTES` | `67108864` (64 MiB) | Integer from 4194304 (4 MiB) to 4294967296 (4 GiB); span and credential bytes an instance holds for upload before dropping new records |-| `LANGFUSE_AI_GATEWAY_MAX_REQUEST_BYTES` | `16777216` (16 MiB) | Integer from 1048576 (1 MiB) to 4294967295; largest accepted request body |-| `LANGFUSE_AI_GATEWAY_MEMORY_BUDGET_BYTES` | `1073741824` (1 GiB) | Integer from the request limit plus the overhead up to Tokio's semaphore capacity; bytes all in-flight requests and model catalogs of an instance may reserve together |-| `LANGFUSE_AI_GATEWAY_REQUEST_MEMORY_OVERHEAD_BYTES` | `2097152` (2 MiB) | Integer from 0 to 4294967295; fixed bytes each request reserves on top of its body for response capture and buffers |-| `LANGFUSE_AI_GATEWAY_MAX_EXECUTION_SECONDS` | `600` | Integer of at least 60; ceiling from execution admission until the response completes. Web ingestion tokens last 15 minutes, so traces of longer executions may be dropped |-| `LANGFUSE_AI_GATEWAY_STALL_TIMEOUT_SECONDS` | `120` | Integer from 1 to the execution ceiling; longest wait without progress |+| Variable | Default | Validation |+| -------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `LANGFUSE_AI_GATEWAY_WEB_URL` | unset; inference disabled | Trusted Web base URL, including any deployment prefix |+| `LANGFUSE_AI_GATEWAY_SERVICE_KEY` | unset | Required with Web URL; same key configured in Web |+| `LANGFUSE_AI_GATEWAY_ALLOW_HTTP_WEB_URL` | `false` | `true`, `false`; `true` also accepts a plain `http://` Web URL on any host. Only for internal traffic, such as Web's in-cluster Kubernetes Service (`http://<release>-web.<namespace>.svc.cluster.local:3000`) or another private network; never for a URL that crosses the public internet, because resolve responses carry provider API keys and requests carry the service key and ingestion tokens unencrypted. Resolution, model catalogs and trace uploads all use this URL. The gateway logs a warning at startup when it is used |+| `LANGFUSE_AI_GATEWAY_LISTEN_ADDRESS` | `0.0.0.0:8080` | IP address and port; IPv6 uses `[::]:8080` |+| `LANGFUSE_AI_GATEWAY_AUTO_INCREMENT_LISTEN_PORT` | `false` | `true`, `false`; the pnpm dev task sets `true` |+| `LANGFUSE_LOG_FORMAT` | `text` | `text`, `json` |+| `LANGFUSE_LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error`, `fatal` |+| `LANGFUSE_AI_GATEWAY_CONNECTION_DRAIN_TIMEOUT_SECONDS` | `10` | Integer from 1 to 300; connection drain after the shutdown signal. Replaces the deprecated `LANGFUSE_AI_GATEWAY_SHUTDOWN_TIMEOUT_SECONDS`, which is still read when the new name is unset. On ECS behind an ALB, the deregistration delay drains streams before SIGTERM, so use `1`. On Kubernetes the gateway drains streams itself, so set it to the stream time to protect (for example `300`) |+| `LANGFUSE_AI_GATEWAY_TELEMETRY_SHUTDOWN_TIMEOUT_SECONDS` | `10` | Integer from 1 to 300; telemetry flush after the drain ends. On ECS use most of `stopTimeout` (max 120), for example `115`. On Kubernetes `30` is enough; set `terminationGracePeriodSeconds` above the `preStop` sleep plus both timeouts |+| `LANGFUSE_AI_GATEWAY_TELEMETRY_BUFFER_BYTES` | `67108864` (64 MiB) | Integer from 4194304 (4 MiB) to 4294967296 (4 GiB); span and credential bytes an instance holds for upload before dropping new records |+| `LANGFUSE_AI_GATEWAY_MAX_REQUEST_BYTES` | `16777216` (16 MiB) | Integer from 1048576 (1 MiB) to 4294967295; largest accepted request body |+| `LANGFUSE_AI_GATEWAY_MEMORY_BUDGET_BYTES` | `1073741824` (1 GiB) | Integer from the request limit plus the overhead up to Tokio's semaphore capacity; bytes all in-flight requests and model catalogs of an instance may reserve together |+| `LANGFUSE_AI_GATEWAY_REQUEST_MEMORY_OVERHEAD_BYTES` | `2097152` (2 MiB) | Integer from 0 to 4294967295; fixed bytes each request reserves on top of its body for response capture and buffers |+| `LANGFUSE_AI_GATEWAY_MAX_EXECUTION_SECONDS` | `600` | Integer of at least 60; ceiling from execution admission until the response completes. Web ingestion tokens last 15 minutes, so traces of longer executions may be dropped |+| `LANGFUSE_AI_GATEWAY_STALL_TIMEOUT_SECONDS` | `120` | Integer from 1 to the execution ceiling; longest wait without progress |The gateway shares `LANGFUSE_LOG_LEVEL` with Web and worker. Values are lowercase;`fatal` maps to Rust's `error` level and therefore includes ordinary error logs.@@ -497,14 +497,14 @@ is not reported as zero.The gateway sets these generation fields directly:-| Generation field | OTLP attribute | Value |-| ------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Model (`provided_model_name`) | `langfuse.observation.model.name` | The first known of `model.response`, `model.upstream` and `model.requested` below |-| User ID | `user.id` | For a gateway key bound to a user, always that user's ID; the caller's user ID is ignored, also with a `traceparent`. Otherwise the caller's `langfuse-user-id` header or `langfuse_user_id` baggage. The source is in `user_id_source` |-| Session ID, trace name, environment, tags | `session.id`, `langfuse.trace.name`, `langfuse.environment`, `langfuse.trace.tags` | Caller headers, baggage or a recognized coding agent; see [Caller tracing context](#caller-tracing-context) |-| Level, status message | `langfuse.observation.level`, `langfuse.observation.status_message` | Derived from the HTTP status, provider status and relay outcome |-| Model parameters, usage, input, output, completion start time | `langfuse.observation.*` | See [Response capture](#response-capture) |-| Metadata | `langfuse.observation.metadata` | Caller metadata plus the gateway keys below |+| Generation field | OTLP attribute | Value |+| ------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Model (`provided_model_name`) | `langfuse.observation.model.name` | The first known of `model.response`, `model.upstream` and `model.requested` below |+| User ID | `user.id` | For a gateway key bound to a user, always that user's email, or their Langfuse user ID if the email is unknown; the caller's user ID is ignored, also with a `traceparent`. Otherwise the caller's `langfuse-user-id` header or `langfuse_user_id` baggage, falling back to the key's name (cut to 512 bytes) when the gateway starts the trace; inside a caller's `traceparent` trace no `user.id` is emitted. The source is in `user_id_source` |+| Session ID, trace name, environment, tags | `session.id`, `langfuse.trace.name`, `langfuse.environment`, `langfuse.trace.tags` | Caller headers, baggage or a recognized coding agent; see [Caller tracing context](#caller-tracing-context) |+| Level, status message | `langfuse.observation.level`, `langfuse.observation.status_message` | Derived from the HTTP status, provider status and relay outcome |+| Model parameters, usage, input, output, completion start time | `langfuse.observation.*` | See [Response capture](#response-capture) |+| Metadata | `langfuse.observation.metadata` | Caller metadata plus the gateway keys below |The generation never emits `user.name` or `gen_ai.*` attributes: ingestion reads them as user ID and model fallbacks.@@ -527,7 +527,7 @@ Every gateway fact is a metadata key under `langfuse.gateway.`, grouped by the r| `model.requested` | string | Caller: request body `model` | When the request body is captured JSON with a model || `model.upstream` | string | Web: the connection's provider model, sent upstream | When the request reached the provider path || `model.response` | string | Provider: response `model` | When the provider reported one |-| `user_id_source` | string: `client` or `api_key_owner` | Gateway | When the generation has a user ID |+| `user_id_source` | string: `client`, `api_key_owner`, or `api_key_name` | Gateway | When the generation has a user ID || `request.id` | string | Gateway | Always; also the `langfuse-request-id` response header || `request.api_format` | string: `openai.responses`, `openai.chat-completions` or `anthropic.messages` | Gateway | Always || `request.body_bytes` | integer | Gateway: the caller's uncompressed request body | Always |diff --git a/ai-gateway/src/capture/mod.rs b/ai-gateway/src/capture/mod.rsindex cf5b9a0458..fe6160e145 100644--- a/ai-gateway/src/capture/mod.rs+++ b/ai-gateway/src/capture/mod.rs@@ -178,9 +178,10 @@ impl ExecutionCapture {metadata: json!({"organization_id": attribution.organization_id().as_str(),"key_id": attribution.key_id(),- "key_name": attribution.key_name().and_then(bounded_string),+ "key_name": attribution.key_name().map(truncated_string),"key_owner_user_id": attribution.user_id(),"key_owner_name": attribution.user_name().and_then(bounded_string),+ "key_owner_email": attribution.user_email().and_then(bounded_string),"provider_connection_id": attribution.provider_connection_id(),"connection_name": context.connection().name().and_then(bounded_string),"provider": context.connection().provider().as_str(),@@ -319,6 +320,13 @@ fn bounded_string(value: &str) -> Option<String> {(value.len() <= MAX_FACT_STRING).then(|| value.to_owned())}+/// Key names are the user ID fallback, so an over-long name is cut at a char+/// boundary instead of dropped. Web caps names at 500 UTF-16 code units, which+/// can exceed `MAX_FACT_STRING` bytes for non-Latin scripts.+fn truncated_string(value: &str) -> String {+ value[..value.floor_char_boundary(MAX_FACT_STRING)].to_owned()+}+fn identity_encoding(headers: &HeaderMap) -> bool {headers.get_all(header::CONTENT_ENCODING)@@ -347,4 +355,14 @@ mod tests {assert_eq!(retry_after_ms(&headers), expected, "{value:?}");}}++ #[test]+ fn long_multibyte_key_names_are_truncated_not_dropped() {+ let name = "名".repeat(171);+ let truncated = truncated_string(&name);+ assert!(truncated.len() <= MAX_FACT_STRING);+ assert!(name.starts_with(&truncated));+ assert_eq!(truncated.chars().count(), MAX_FACT_STRING / 3);+ assert_eq!(truncated_string("checkout-agent"), "checkout-agent");+ }}diff --git a/ai-gateway/src/resolution/contracts.rs b/ai-gateway/src/resolution/contracts.rsindex e6fc53d554..9927e7e171 100644--- a/ai-gateway/src/resolution/contracts.rs+++ b/ai-gateway/src/resolution/contracts.rs@@ -251,6 +251,8 @@ pub struct RequestAttribution {key_name: Option<String>,#[serde(default)]user_name: Option<String>,+ #[serde(default)]+ user_email: Option<String>,key_metadata: BTreeMap<String, MetadataValue>,provider_connection_id: String,}@@ -274,6 +276,9 @@ impl RequestAttribution {pub fn user_name(&self) -> Option<&str> {non_blank(self.user_name.as_deref())}+ pub fn user_email(&self) -> Option<&str> {+ non_blank(self.user_email.as_deref())+ }pub fn key_metadata(&self) -> &BTreeMap<String, MetadataValue> {&self.key_metadata}diff --git a/ai-gateway/src/resolution/tests.rs b/ai-gateway/src/resolution/tests.rsindex a732513306..bec6e4728c 100644--- a/ai-gateway/src/resolution/tests.rs+++ b/ai-gateway/src/resolution/tests.rs@@ -776,6 +776,7 @@ async fn accepts_unknown_response_fields_outside_provider_auth() {body["ingestion"]["unexpected"] = json!(1);body["attribution"]["key_name"] = json!("CI key");body["attribution"]["user_name"] = json!("Alice");+ body["attribution"]["user_email"] = json!("[email protected]");let web = FakeWeb::start(move |_| {let body = body.clone();async move { response(body) }@@ -796,6 +797,7 @@ async fn accepts_unknown_response_fields_outside_provider_auth() {assert_eq!(attribution.key_name(), Some("CI key"));assert_eq!(attribution.user_id(), Some("user-1"));assert_eq!(attribution.user_name(), Some("Alice"));+ assert_eq!(attribution.user_email(), Some("[email protected]"));}#[tokio::test]@@ -803,7 +805,7 @@ async fn treats_missing_or_blank_key_snapshots_as_absent() {for value in [None, Some(json!("")), Some(json!(" ")), Some(Value::Null)] {let mut body = success("project-1", "provider-token");if let Some(value) = value {- for field in ["key_name", "user_name"] {+ for field in ["key_name", "user_name", "user_email"] {body["attribution"][field] = value.clone();}}@@ -826,6 +828,7 @@ async fn treats_missing_or_blank_key_snapshots_as_absent() {let attribution = context.attribution();assert_eq!(attribution.key_name(), None);assert_eq!(attribution.user_name(), None);+ assert_eq!(attribution.user_email(), None);}}diff --git a/ai-gateway/src/telemetry/mapping.rs b/ai-gateway/src/telemetry/mapping.rsindex f303f30385..8ec338afe5 100644--- a/ai-gateway/src/telemetry/mapping.rs+++ b/ai-gateway/src/telemetry/mapping.rs@@ -113,8 +113,11 @@ pub(super) fn span(facts: InferenceFacts, context: &GenerationContext) -> Valuespan}-/// A key bound to a user always attributes to that user, even inside a caller's-/// trace. Only keys without a bound user accept the caller's user ID.+/// A key bound to a user always attributes to that user's email, or to their+/// internal user ID when the email is unknown, even inside a caller's trace.+/// Keys without a bound user, such as service account keys, take the caller's+/// user ID. Only when the gateway starts the trace do they fall back to the+/// key's name, so a caller's trace keeps the user set on its own spans.fn user_id_source<'a>(facts: &'a InferenceFacts,context: &GenerationContext,@@ -124,12 +127,23 @@ fn user_id_source<'a>(.get("key_owner_user_id").and_then(Value::as_str){- return Some(("api_key_owner", Some(owner)));+ let email = facts+ .metadata+ .get("key_owner_email")+ .and_then(Value::as_str);+ return Some(("api_key_owner", Some(email.unwrap_or(owner))));+ }+ if context.attributes.contains_key(USER_ID_ATTRIBUTE) {+ return Some(("client", None));}- context- .attributes- .contains_key(USER_ID_ATTRIBUTE)- .then_some(("client", None))+ if context.parent_span_id.is_some() {+ return None;+ }+ facts+ .metadata+ .get("key_name")+ .and_then(Value::as_str)+ .map(|name| ("api_key_name", Some(name)))}pub(super) fn omit_input(span: &mut Value, reason: InputOmissionReason) -> bool {@@ -751,21 +765,26 @@ mod tests {.attributes.insert("user.id".into(), json!("caller"));for context in [context(), caller_in_child] {- let mut owned = facts();- owned.metadata["key_owner_user_id"] = json!("owner");- let span = span(owned, &context);- let user_ids: Vec<_> = span["attributes"]- .as_array()- .unwrap()- .iter()- .filter(|attribute| attribute["key"] == "user.id")- .map(|attribute| attribute["value"]["stringValue"].clone())- .collect();- assert_eq!(user_ids, [json!("owner")]);- assert_eq!(- metadata(&attributes(&span))["langfuse.gateway.user_id_source"],- "api_key_owner"- );+ for (email, expected) in [+ (json!("[email protected]"), "[email protected]"),+ (Value::Null, "owner"),+ ] {+ let mut owned = facts();+ owned.metadata["key_owner_user_id"] = json!("owner");+ owned.metadata["key_owner_email"] = email;+ let span = span(owned, &context);+ let user_ids: Vec<_> = span["attributes"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|attribute| attribute["key"] == "user.id")+ .map(|attribute| attribute["value"]["stringValue"].clone())+ .collect();+ assert_eq!(user_ids, [json!(expected)]);+ let metadata = metadata(&attributes(&span));+ assert_eq!(metadata["langfuse.gateway.user_id_source"], "api_key_owner");+ assert_eq!(metadata["langfuse.gateway.api_key.owner.user_id"], "owner");+ }}}@@ -790,6 +809,41 @@ mod tests {);}+ #[test]+ fn keys_without_a_bound_user_default_to_the_key_name() {+ let mut named = facts();+ named.metadata["key_name"] = json!("checkout-agent");+ let attrs = attributes(&span(named, &context()));+ assert_eq!(attrs["user.id"], "checkout-agent");+ assert_eq!(+ metadata(&attrs)["langfuse.gateway.user_id_source"],+ "api_key_name"+ );++ let mut caller = context();+ caller.attributes.insert("user.id".into(), json!("caller"));+ let mut named = facts();+ named.metadata["key_name"] = json!("checkout-agent");+ let attrs = attributes(&span(named, &caller));+ assert_eq!(attrs["user.id"], "caller");+ assert_eq!(+ metadata(&attrs)["langfuse.gateway.user_id_source"],+ "client"+ );++ let mut child = context();+ child.parent_span_id = Some("fedcba9876543210".into());+ let mut named = facts();+ named.metadata["key_name"] = json!("checkout-agent");+ let attrs = attributes(&span(named, &child));+ assert!(!attrs.contains_key("user.id"));+ assert!(+ metadata(&attrs)+ .get("langfuse.gateway.user_id_source")+ .is_none()+ );+ }+#[test]fn client_user_agent_is_recorded_as_gateway_metadata() {let mut context = context();diff --git a/web/src/__e2e__/ai-gateway.gatewaye2e.ts b/web/src/__e2e__/ai-gateway.gatewaye2e.tsindex a31b372fc4..078bb6afd4 100644--- a/web/src/__e2e__/ai-gateway.gatewaye2e.ts+++ b/web/src/__e2e__/ai-gateway.gatewaye2e.ts@@ -610,6 +610,7 @@ describe("AI gateway live end-to-end", () => {user_id: admin.userId,key_name: `Gateway E2E ${provider} ${apiFormat}`,user_name: admin.userName || null,+ user_email: admin.userEmail || null,key_metadata: {test: true,provider,@@ -758,7 +759,7 @@ async function createGatewayAdmin() {}),prisma.user.findUniqueOrThrow({where: { id: membership.userId },- select: { id: true, name: true },+ select: { id: true, name: true, email: true },}),]);const session: Session = {@@ -789,6 +790,7 @@ async function createGatewayAdmin() {caller: appRouter.createCaller({ ...context, prisma }),userId: user.id,userName: user.name,+ userEmail: user.email,};}diff --git a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts b/web/src/__tests__/server/ai-gateway-control-plane.servertest.tsindex 0b6c236d43..39384b0b12 100644--- a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts+++ b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts@@ -1082,6 +1082,7 @@ describe("AI gateway control plane", () => {await expect(caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: { nested: { rejected: true } } as never,}),).rejects.toThrow();@@ -1163,7 +1164,11 @@ describe("AI gateway control plane", () => {viewer.aiGateway.listApiKeys({ orgId: owner.org.id }),).rejects.toMatchObject({ code: "FORBIDDEN" });await expect(- viewer.aiGateway.createApiKey({ orgId: owner.org.id, metadata: {} }),+ viewer.aiGateway.createApiKey({+ orgId: owner.org.id,+ name: "Test key",+ metadata: {},+ }),).rejects.toMatchObject({ code: "FORBIDDEN" });});@@ -1188,6 +1193,7 @@ describe("AI gateway control plane", () => {await expect(member.aiGateway.createApiKey({orgId: owner.org.id,+ name: "Service key",metadata: {},issuedAs: "serviceAccount",}),@@ -1197,6 +1203,27 @@ describe("AI gateway control plane", () => {).toEqual([]);});+ it("requires a name for every gateway key", async () => {+ const owner = await prepare();++ for (const issuedAs of ["user", "serviceAccount"] as const) {+ for (const name of [undefined, " "]) {+ await expect(+ owner.caller.aiGateway.createApiKey({+ orgId: owner.org.id,+ // Deliberately invalid input to exercise server-side validation.+ name: name as string,+ metadata: {},+ issuedAs,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ }+ }+ expect(+ (await owner.caller.aiGateway.listApiKeys({ orgId: owner.org.id })).data,+ ).toEqual([]);+ });+it.each(["legacy", "shadow"] as const)("keeps gateway API key creation admin-only when API_AUTH_MIGRATION is %s",async (migration) => {@@ -1212,11 +1239,16 @@ describe("AI gateway control plane", () => {const admin = await createCallerForOrganizationRole(owner, Role.ADMIN);await expect(- member.aiGateway.createApiKey({ orgId: owner.org.id, metadata: {} }),+ member.aiGateway.createApiKey({+ orgId: owner.org.id,+ name: "Test key",+ metadata: {},+ }),).rejects.toMatchObject({ code: "FORBIDDEN" });await expect(owner.caller.aiGateway.createApiKey({orgId: owner.org.id,+ name: "Test key",metadata: {},}),).resolves.toMatchObject({@@ -1225,6 +1257,7 @@ describe("AI gateway control plane", () => {await expect(admin.aiGateway.createApiKey({orgId: owner.org.id,+ name: "Service key",metadata: {},issuedAs: "serviceAccount",}),@@ -1232,6 +1265,7 @@ describe("AI gateway control plane", () => {await expect(owner.caller.aiGateway.createApiKey({orgId: owner.org.id,+ name: "Service key",metadata: {},issuedAs: "serviceAccount",}),@@ -1250,6 +1284,7 @@ describe("AI gateway control plane", () => {await expect(caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},expiresAt: new Date(Date.now() - 1_000),}),@@ -1277,6 +1312,7 @@ describe("AI gateway control plane", () => {});const key = await apiKeyService.create({organizationId: org.id,+ name: "Test key",metadata: {},issuedAs: "user",session,@@ -1428,6 +1464,7 @@ describe("AI gateway control plane", () => {});const gatewayKey = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});@@ -1506,6 +1543,7 @@ describe("AI gateway control plane", () => {});const gatewayKey = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});const otherOrganization = await prepare();@@ -1578,6 +1616,7 @@ describe("AI gateway control plane", () => {});const gatewayKey = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});const fastHashedSecretKey = createShaHash(gatewayKey.secretKey, env.SALT);@@ -2016,6 +2055,7 @@ describe("AI gateway control plane", () => {});const key = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});const resolveParams = {@@ -2091,6 +2131,7 @@ describe("AI gateway control plane", () => {const { caller, org } = await prepare();const gatewayKey = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});const authenticator = new GatewayApiKeyAuthenticator(prisma);@@ -2210,6 +2251,7 @@ describe("AI gateway control plane", () => {});const key = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});await prisma.project.update({@@ -2250,6 +2292,7 @@ describe("AI gateway control plane", () => {});const key = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url) => {@@ -2401,6 +2444,7 @@ describe("AI gateway control plane", () => {});const key = await caller.aiGateway.createApiKey({orgId: org.id,+ name: "Test key",metadata: {},});const fetcher = vidiff --git a/web/src/__tests__/server/ai-gateway-user-bound-api-keys.servertest.ts b/web/src/__tests__/server/ai-gateway-user-bound-api-keys.servertest.tsindex 74fa6c2e0e..625ed2cc1c 100644--- a/web/src/__tests__/server/ai-gateway-user-bound-api-keys.servertest.ts+++ b/web/src/__tests__/server/ai-gateway-user-bound-api-keys.servertest.ts@@ -152,6 +152,7 @@ describe("user-bound API keys", () => {const key = await new GatewayApiKeyService(prisma).create({organizationId: org.id,+ name: "Test key",metadata: {},issuedAs: "user",session: orgSession(user, org, Role.MEMBER),@@ -169,6 +170,7 @@ describe("user-bound API keys", () => {const key = await new GatewayApiKeyService(prisma).create({organizationId: org.id,+ name: "Test key",metadata: {},issuedAs: "serviceAccount",session: orgSession(user, org, Role.ADMIN),@@ -197,6 +199,7 @@ describe("user-bound API keys", () => {await expect(new GatewayApiKeyService(prisma).create({organizationId: org.id,+ name: "Test key",metadata: {},issuedAs: "serviceAccount",session: orgSession(user, org, Role.ADMIN),@@ -216,6 +219,7 @@ describe("user-bound API keys", () => {await expect(new GatewayApiKeyService(prisma).create({organizationId: org.id,+ name: "Test key",metadata: {},issuedAs: "user",session: orgSession(user, org, Role.OWNER),@@ -232,6 +236,7 @@ describe("user-bound API keys", () => {await expect(new GatewayApiKeyService(prisma).create({organizationId: org.id,+ name: "Test key",metadata: {},issuedAs: "user",session: orgSession(user, org, Role.OWNER),diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tsindex a843e250fd..0d61efc0c6 100644--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts@@ -464,6 +464,7 @@ describe("organization API keys trpc", () => {userId: null,apiKeyName: "Original gateway key",userName: null,+ userEmail: null,keyMetadata: {},ingestionProjectId: null,ingestionMode: null,@@ -481,6 +482,37 @@ describe("organization API keys trpc", () => {expect(await cache.get(cacheEntry)).toBeNull();});+ it("rejects a blank name for a gateway key but not for other keys", async () => {+ const gatewayKey = await createApiKey(prisma, {+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId("user-1"),+ name: "Named gateway key",+ });++ await expect(+ ownerCaller.organizationApiKeys.updateName({+ orgId: organizationId,+ keyId: gatewayKey.id,+ name: " ",+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ await expect(+ prisma.apiKey.findUniqueOrThrow({ where: { id: gatewayKey.id } }),+ ).resolves.toMatchObject({ note: "Named gateway key" });++ const otherKey = await ownerCaller.organizationApiKeys.create({+ orgId: organizationId,+ name: "Named key",+ });+ await ownerCaller.organizationApiKeys.updateName({+ orgId: organizationId,+ keyId: otherKey.id,+ name: "",+ });+ });+it("returns NOT_FOUND for a missing API key", async () => {await expect(ownerCaller.organizationApiKeys.updateName({@@ -599,6 +631,7 @@ describe("organization API keys trpc", () => {userId: null,apiKeyName: "Cached gateway key",userName: null,+ userEmail: null,keyMetadata: {},ingestionProjectId: null,ingestionMode: null,@@ -770,6 +803,7 @@ describe("organization API keys trpc", () => {});const key = await ownerCallerForOrg(orgId).organizationApiKeys.create({orgId,+ name: `${role} key`,role,});expect(@@ -785,6 +819,23 @@ describe("organization API keys trpc", () => {},);+ it("rejects an AI_GATEWAY key without a name", async () => {+ Object.assign(env, { API_KEY_ORG_ROLES_ENABLE: "true" });+ const orgId = `org-${randomUUID()}`;+ await prisma.organization.create({+ data: { id: orgId, name: "Scoped" },+ });++ await expect(+ ownerCallerForOrg(orgId).organizationApiKeys.create({+ orgId,+ name: " ",+ role: "AI_GATEWAY",+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ await expect(prisma.apiKey.count({ where: { orgId } })).resolves.toBe(0);+ });+describe.each([{ migration: "legacy", enabled: "false" },{ migration: "legacy", enabled: "true" },diff --git a/web/src/__tests__/server/unit/gatewayResolveCache.servertest.ts b/web/src/__tests__/server/unit/gatewayResolveCache.servertest.tsindex 5639a117a9..5661d44397 100644--- a/web/src/__tests__/server/unit/gatewayResolveCache.servertest.ts+++ b/web/src/__tests__/server/unit/gatewayResolveCache.servertest.ts@@ -19,6 +19,7 @@ const context: CachedResolveContext = {userId: "user-1",apiKeyName: "CI key",userName: "Alice",+ userEmail: "[email protected]",keyMetadata: {},ingestionProjectId: null,ingestionMode: null,@@ -134,6 +135,7 @@ describe("GatewayResolveCache", () => {...legacy,apiKeyName: null,userName: null,+ userEmail: null,});});diff --git a/web/src/components/design-system/FormField/FormField.tsx b/web/src/components/design-system/FormField/FormField.tsxindex 76f31cffe7..9c0938a237 100644--- a/web/src/components/design-system/FormField/FormField.tsx+++ b/web/src/components/design-system/FormField/FormField.tsx@@ -34,6 +34,7 @@ export type FormFieldProps<label: string;name: TName;registerLabelTooltip?: TooltipTriggerPropsGetter;+ required?: boolean;};type StandaloneFormFieldProps = {@@ -46,6 +47,7 @@ type StandaloneFormFieldProps = {description?: string;label: string;registerLabelTooltip?: TooltipTriggerPropsGetter;+ required?: boolean;};function FormFieldLayout({@@ -56,6 +58,7 @@ function FormFieldLayout({errorMessage,errorId,registerLabelTooltip,+ required,children,}: {label: string;@@ -65,6 +68,7 @@ function FormFieldLayout({errorMessage?: string;errorId: string;registerLabelTooltip?: TooltipTriggerPropsGetter;+ required?: boolean;children: ReactElement;}) {return (@@ -72,6 +76,11 @@ function FormFieldLayout({<div className="flex items-center gap-1.5"><label htmlFor={controlId} className="text-sm leading-none font-bold">{label}+ {required ? (+ <span aria-hidden className="text-destructive ml-1">+ *+ </span>+ ) : null}</label>{registerLabelTooltip ? (<button@@ -119,7 +128,7 @@ export function FormField<const controlId = `${id}-control`;const descriptionId = `${id}-description`;const errorId = `${id}-error`;- const { label, description, registerLabelTooltip } = props;+ const { label, description, registerLabelTooltip, required } = props;if (props.control) {const { control, name, children } = props;@@ -144,6 +153,7 @@ export function FormField<errorMessage={errorMessage}errorId={errorId}registerLabelTooltip={registerLabelTooltip}+ required={required}>{children({...field,@@ -166,6 +176,7 @@ export function FormField<descriptionId={descriptionId}errorId={errorId}registerLabelTooltip={registerLabelTooltip}+ required={required}>{props.children({id: controlId,diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsxindex b218bc20dd..ce15bf7b2a 100644--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx@@ -3,6 +3,9 @@ import { useSession } from "next-auth/react";import { ChevronRight, Plus, X } from "@langfuse/icons";import { Alert } from "@/src/components/design-system/Alert/Alert";+import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";+import { FormField } from "@/src/components/design-system/FormField/FormField";+import { Input as DesignSystemInput } from "@/src/components/design-system/Input/Input";import { Dialog } from "@/src/components/design-system/Dialog/Dialog";import { DialogController } from "@/src/components/design-system/DialogController/DialogController";import { Tabs } from "@/src/components/design-system/Tabs/Tabs";@@ -87,19 +90,20 @@ export function CreateGatewayApiKeyDialogController({const metadataCount = metadata.filter((field) => field.key.trim()).length;const expiresAt = resolveApiKeyExpiration(expiryPreset, customExpiry);+ const effectiveIssuedAs = canIssueServiceAccountKeys ? issuedAs : "user";+ const isNameMissing = !name.trim();const submit = async () => {- if (expiresAt === undefined) return;+ if (expiresAt === undefined || isNameMissing) return;const metadataObject = Object.fromEntries(metadata.filter((field) => field.key.trim()).map((field) => [field.key.trim(), field.value]),);- const effectiveIssuedAs = canIssueServiceAccountKeys ? issuedAs : "user";try {const created = await create.mutateAsync({orgId: organizationId,- name: name.trim() || undefined,+ name: name.trim(),metadata: metadataObject,expiresAt,issuedAs: effectiveIssuedAs,@@ -144,32 +148,13 @@ export function CreateGatewayApiKeyDialogController({{label: "Create key",loading: create.isPending,- disabled: create.isPending || expiresAt === undefined,+ disabled:+ create.isPending || expiresAt === undefined || isNameMissing,onClick: submit,},]}><Dialog.Body>- <div>- <Label- htmlFor="gateway-key-name"- className="flex items-center gap-1.5"- >- Description- <InfoTooltip label="About gateway key descriptions">- Shown in the key list. Use it to describe what consumes the- key.- </InfoTooltip>- </Label>- <Input- id="gateway-key-name"- className="mt-1.5"- maxLength={500}- placeholder="e.g. Checkout agent, backend service"- value={name}- onChange={(event) => setName(event.target.value)}- />- </div>{canIssueServiceAccountKeys ? (<div className="flex flex-col gap-1.5"><Label>Issued as</Label>@@ -197,6 +182,34 @@ export function CreateGatewayApiKeyDialogController({</p></div>) : null}+ <CustomTooltip+ content={+ <span>+ Shown in the key list. Use it to describe what consumes the+ key.+ </span>+ }+ >+ {({ getTriggerProps }) => (+ <FormField+ label="Name"+ required+ registerLabelTooltip={getTriggerProps}+ >+ {(field) => (+ <DesignSystemInput+ id={field.id}+ aria-describedby={field.inputDescribedById}+ maxLength={500}+ required+ placeholder="e.g. Checkout agent, backend service"+ value={name}+ onChange={(event) => setName(event.target.value)}+ />+ )}+ </FormField>+ )}+ </CustomTooltip><ApiKeyExpirationInputid="gateway-key-expiry"expiryPreset={expiryPreset}diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsxindex 6f1183e7b6..b58afe71b4 100644--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx@@ -64,7 +64,7 @@ export function GatewayApiKeysTable({createTextTableColumn<GatewayApiKey>({accessorFn: (row) => row.apiKey.note,id: "description",- header: "Description",+ header: "Name",nullValue: "-",enableResizing: false,}),diff --git a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.tsindex 54d4068dc6..dadbbaa7d9 100644--- a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts+++ b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts@@ -49,7 +49,7 @@ export class GatewayApiKeyService {async create(params: {organizationId: string;- name?: string;+ name: string;metadata: GatewayMetadata;expiresAt?: Date | null;/** `user` keys are revoked with the creator's gateway access; `serviceAccount` keys belong to the organization. */diff --git a/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.ts b/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.tsindex a6e33a712b..9bc899af4d 100644--- a/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.ts+++ b/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.ts@@ -151,6 +151,7 @@ export class GatewayApiKeyAuthenticator {userId: row.userId,apiKeyName: row.note || null,userName: row.user?.name || null,+ userEmail: row.user?.email || null,keyMetadata: toKeyMetadata(row.gatewayAssociation?.metadata),ingestionProjectId: projectIsUsable? (gatewayConfig?.defaultIngestionProjectId ?? null)diff --git a/web/src/features/ai-gateway/server/provider/registry.ts b/web/src/features/ai-gateway/server/provider/registry.tsindex 70a8dcafb1..7caa1b9c16 100644--- a/web/src/features/ai-gateway/server/provider/registry.ts+++ b/web/src/features/ai-gateway/server/provider/registry.ts@@ -53,6 +53,7 @@ export const GatewayResolveResponseSchema = zuser_id: z.string().nullable(),key_name: z.string().nullable(),user_name: z.string().nullable(),+ user_email: z.string().nullable(),key_metadata: GatewayMetadataSchema,provider_connection_id: z.string(),})diff --git a/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.ts b/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.tsindex b909a55457..9e01069046 100644--- a/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.ts+++ b/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.ts@@ -30,6 +30,7 @@ export const CachedResolveContext = z.object({// Defaulted so entries cached before these fields existed still parse.apiKeyName: z.string().nullable().default(null),userName: z.string().nullable().default(null),+ userEmail: z.string().nullable().default(null),keyMetadata: GatewayMetadataSchema,ingestionProjectId: z.string().nullable(),ingestionMode: z.enum(["NONE", "USAGE", "FULL"]).nullable(),diff --git a/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.ts b/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.tsindex e59eb050f1..02761f7eb3 100644--- a/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.ts+++ b/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.ts@@ -22,7 +22,7 @@ export class GatewayResolveRepository {userId: true,expiresAt: true,note: true,- user: { select: { name: true } },+ user: { select: { name: true, email: true } },gatewayAssociation: { select: { metadata: true } },organization: {select: {diff --git a/web/src/features/ai-gateway/server/resolve/resolveService.servertest.ts b/web/src/features/ai-gateway/server/resolve/resolveService.servertest.tsindex d6e7e9b8b3..fcb80b7bed 100644--- a/web/src/features/ai-gateway/server/resolve/resolveService.servertest.ts+++ b/web/src/features/ai-gateway/server/resolve/resolveService.servertest.ts@@ -66,14 +66,17 @@ const row = (overrides: {metadata?: unknown;userId?: string | null;note?: string | null;- user?: { name: string | null } | null;+ user?: { name: string | null; email: string | null } | null;}) => ({id: "key-1",orgId: "org-1",userId: overrides.userId === undefined ? "user-1" : overrides.userId,expiresAt: null,note: overrides.note === undefined ? "CI key" : overrides.note,- user: overrides.user === undefined ? { name: "Alice" } : overrides.user,+ user:+ overrides.user === undefined+ ? { name: "Alice", email: "[email protected]" }+ : overrides.user,gatewayAssociation:overrides.metadata === undefined ? null : { metadata: overrides.metadata },organization: {@@ -133,6 +136,7 @@ describe("GatewayResolveService", () => {user_id: "user-1",key_name: "CI key",user_name: "Alice",+ user_email: "[email protected]",key_metadata: { team: "platform", project_id: "spoofed-project" },provider_connection_id: "connection-1",},@@ -147,8 +151,8 @@ describe("GatewayResolveService", () => {it.each([{ note: "", userId: null, user: null },- { note: null, userId: "user-1", user: { name: null } },- { note: null, userId: "user-1", user: { name: "" } },+ { note: null, userId: "user-1", user: { name: null, email: null } },+ { note: null, userId: "user-1", user: { name: "", email: "" } },])("sends absent key snapshots as null (%o)",async ({ note, userId, user }) => {@@ -166,6 +170,7 @@ describe("GatewayResolveService", () => {key_name: null,user_id: userId,user_name: null,+ user_email: null,},});},diff --git a/web/src/features/ai-gateway/server/resolve/resolveService.ts b/web/src/features/ai-gateway/server/resolve/resolveService.tsindex bce51ef904..f94352d227 100644--- a/web/src/features/ai-gateway/server/resolve/resolveService.ts+++ b/web/src/features/ai-gateway/server/resolve/resolveService.ts@@ -118,6 +118,7 @@ export class GatewayResolveService {user_id: context.userId,key_name: context.apiKeyName,user_name: context.userName,+ user_email: context.userEmail,key_metadata: context.keyMetadata,provider_connection_id: context.connection.id,},diff --git a/web/src/features/ai-gateway/server/router.ts b/web/src/features/ai-gateway/server/router.tsindex 9a2d1a4dd3..2cd0e085c6 100644--- a/web/src/features/ai-gateway/server/router.ts+++ b/web/src/features/ai-gateway/server/router.ts@@ -474,7 +474,7 @@ export const aiGatewayRouter = createTRPCRouter({createApiKey: protectedOrganizationProcedureWithoutTracing.input(organizationInput.extend({- name: z.string().max(500).optional(),+ name: z.string().trim().min(1, "Gateway keys need a name").max(500),metadata: GatewayMetadataSchema.default({}),expiresAt: z.date()diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.tsindex 518a70a681..b6ff75b2cb 100644--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts@@ -6,6 +6,7 @@ import {protectedOrganizationProcedure,} from "@/src/server/api/trpc";import * as z from "zod";+import { TRPCError } from "@trpc/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { redis } from "@langfuse/shared/src/server";import { LangfuseNotFoundError } from "@langfuse/shared";@@ -14,6 +15,10 @@ import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";import { apiKeyCreationRoleSchema } from "@/src/features/public-api/server/apiKeyCreationRoleSchema";import { excludeGatewayApiKeys } from "@/src/features/ai-gateway/server/apiKey/excludeGatewayApiKeys";import { invalidateGatewayResolveCacheForApiKey } from "@/src/features/ai-gateway/server";+import { GATEWAY_ROLE } from "@/src/features/ai-gateway/fns/separateGatewayApiKeys";++// Gateway traffic from keys without a bound user reports the key name as its user ID.+const GATEWAY_KEY_NAME_REQUIRED = "Gateway keys need a name";export const organizationApiKeysRouter = createTRPCRouter({byOrganizationId: protectedOrganizationProcedure@@ -67,17 +72,22 @@ export const organizationApiKeysRouter = createTRPCRouter({}),create: protectedOrganizationProcedure.input(- z.object({- orgId: z.string(),- name: z.string().optional(),- role: apiKeyCreationRoleSchema("organization"),- expiresAt: z- .date()- .nullish()- .refine((date) => date == null || date.getTime() > Date.now(), {- message: "Expiration date must be in the future",- }),- }),+ z+ .object({+ orgId: z.string(),+ name: z.string().optional(),+ role: apiKeyCreationRoleSchema("organization"),+ expiresAt: z+ .date()+ .nullish()+ .refine((date) => date == null || date.getTime() > Date.now(), {+ message: "Expiration date must be in the future",+ }),+ })+ .refine((input) => input.role !== GATEWAY_ROLE || hasName(input.name), {+ message: GATEWAY_KEY_NAME_REQUIRED,+ path: ["name"],+ }),).mutation(async ({ input, ctx }) => {throwIfNoOrganizationAccess({@@ -137,12 +147,25 @@ export const organizationApiKeysRouter = createTRPCRouter({orgId: input.orgId,isInAppAgentKey: false,},+ include: {+ roleAssignments: {+ where: { systemRole: GATEWAY_ROLE },+ select: { id: true },+ },+ },});if (!apiKey) {throw new LangfuseNotFoundError("API key not found");}+ if (apiKey.roleAssignments.length > 0 && !hasName(input.name)) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: GATEWAY_KEY_NAME_REQUIRED,+ });+ }+await auditLog({session: ctx.session,resourceType: "apiKey",@@ -219,3 +242,7 @@ export const organizationApiKeysRouter = createTRPCRouter({return deleted;}),});++function hasName(name: string | null | undefined) {+ return (name?.trim().length ?? 0) > 0;+}