@langwatch/server 3.1.0-beta.19 → 3.1.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/langwatch/prisma/migrations/20260425000000_consolidate_gateway_audit_into_audit_log/migration.sql +44 -0
  2. package/langwatch/prisma/migrations/20260426150000_drop_redundant_audit_log_org_index/migration.sql +25 -0
  3. package/langwatch/prisma/schema.prisma +34 -41
  4. package/langwatch/scripts/seed-gateway-dogfood.ts +26 -26
  5. package/langwatch/src/app/api/gateway-platform/[[...route]]/app.ts +8 -4
  6. package/langwatch/src/app/api/middleware/trace-limit.ts +10 -0
  7. package/langwatch/src/components/MainMenu.tsx +4 -15
  8. package/langwatch/src/components/SettingsLayout.tsx +1 -1
  9. package/langwatch/src/components/llmPromptConfigs/__tests__/LLMConfigPopover.test.tsx +45 -0
  10. package/langwatch/src/components/llmPromptConfigs/parameterRegistry.ts +22 -13
  11. package/langwatch/src/components/prompts/PromptEditorDrawer.tsx +5 -3
  12. package/langwatch/src/components/settings/AddCustomModelDialog.tsx +7 -6
  13. package/langwatch/src/evaluations-v3/__tests__/TableDisplay.integration.test.tsx +90 -5
  14. package/langwatch/src/evaluations-v3/__tests__/TableSettingsMenu.integration.test.tsx +26 -26
  15. package/langwatch/src/evaluations-v3/components/DatasetSection/TableCell.tsx +2 -10
  16. package/langwatch/src/evaluations-v3/components/EvaluationsV3Table.tsx +10 -4
  17. package/langwatch/src/evaluations-v3/components/TableSettingsMenu.tsx +6 -6
  18. package/langwatch/src/evaluations-v3/components/TargetSection/EvaluatorChip.tsx +19 -11
  19. package/langwatch/src/evaluations-v3/components/TargetSection/TargetCell.tsx +55 -42
  20. package/langwatch/src/evaluations-v3/components/TargetSection/TargetHeader.tsx +2 -1
  21. package/langwatch/src/evaluations-v3/components/TargetSection/__tests__/EvaluatorChip.test.tsx +57 -0
  22. package/langwatch/src/evaluations-v3/components/TargetSection/__tests__/TargetCell.test.tsx +199 -11
  23. package/langwatch/src/evaluations-v3/components/VirtualizedTableBody.tsx +1 -1
  24. package/langwatch/src/evaluations-v3/constants.ts +9 -0
  25. package/langwatch/src/evaluations-v3/types/__tests__/persistence.test.ts +1 -1
  26. package/langwatch/src/evaluations-v3/types.ts +13 -1
  27. package/langwatch/src/evaluations-v3/utils/__tests__/evaluatorEditorCallbacks.test.ts +32 -0
  28. package/langwatch/src/evaluations-v3/utils/evaluatorEditorCallbacks.ts +36 -5
  29. package/langwatch/src/optimization_studio/components/datasets/DatasetSelection.tsx +1 -6
  30. package/langwatch/src/optimization_studio/components/datasets/__tests__/DatasetSelection.integration.test.tsx +194 -0
  31. package/langwatch/src/optimization_studio/components/drawers/SignaturePromptEditorBridge.tsx +6 -6
  32. package/langwatch/src/optimization_studio/components/drawers/__tests__/SignaturePromptEditorBridge.integration.test.tsx +36 -11
  33. package/langwatch/src/pages/[project]/gateway/budgets/[id].tsx +1 -1
  34. package/langwatch/src/pages/[project]/gateway/virtual-keys/[id].tsx +1 -1
  35. package/langwatch/src/pages/settings/audit-log.tsx +82 -59
  36. package/langwatch/src/routes.tsx +0 -4
  37. package/langwatch/src/server/agents/agent.service.ts +6 -2
  38. package/langwatch/src/server/api/__tests__/rbac-integration.test.ts +53 -0
  39. package/langwatch/src/server/api/__tests__/rbac.auditLog.test.ts +100 -0
  40. package/langwatch/src/server/api/rbac.ts +12 -0
  41. package/langwatch/src/server/api/root.ts +0 -2
  42. package/langwatch/src/server/api/routers/organization.ts +1 -1
  43. package/langwatch/src/server/app-layer/organizations/repositories/organization.prisma.repository.ts +58 -120
  44. package/langwatch/src/server/app-layer/organizations/repositories/organization.repository.ts +8 -11
  45. package/langwatch/src/server/evaluators/evaluator.service.ts +6 -2
  46. package/langwatch/src/server/gateway/__tests__/auditLog.consolidation.integration.test.ts +237 -0
  47. package/langwatch/src/server/gateway/__tests__/cacheRule.service.unit.test.ts +2 -2
  48. package/langwatch/src/server/gateway/__tests__/providerCredential.service.unit.test.ts +6 -6
  49. package/langwatch/src/server/gateway/__tests__/virtualKey.service.unit.test.ts +6 -6
  50. package/langwatch/src/server/gateway/auditLog.repository.ts +46 -8
  51. package/langwatch/src/server/gateway/auditSerializer.ts +2 -2
  52. package/langwatch/src/server/gateway/budget.service.ts +6 -6
  53. package/langwatch/src/server/gateway/cacheRule.service.ts +5 -5
  54. package/langwatch/src/server/gateway/providerCredential.service.ts +5 -5
  55. package/langwatch/src/server/gateway/virtualKey.service.ts +9 -9
  56. package/langwatch/src/server/pat/__tests__/auth-middleware.unit.test.ts +138 -3
  57. package/langwatch/src/server/pat/auth-middleware.ts +68 -13
  58. package/langwatch/src/server/routes/__tests__/otel.unit.test.ts +241 -0
  59. package/langwatch/src/server/routes/otel.ts +281 -45
  60. package/langwatch/src/server/scenarios/adapters/__tests__/http-agent.adapter.test.ts +271 -6
  61. package/langwatch/src/server/scenarios/adapters/http-agent.adapter.ts +43 -35
  62. package/langwatch/src/server/scenarios/execution/http-template-engine.ts +124 -0
  63. package/langwatch/src/server/scenarios/execution/serialized-adapters/__tests__/http-agent.adapter.unit.test.ts +180 -0
  64. package/langwatch/src/server/scenarios/execution/serialized-adapters/http-agent.adapter.ts +26 -30
  65. package/langwatch/src/tasks/__tests__/migrateCustomModels.unit.test.ts +0 -2
  66. package/langwatch/src/tasks/migrateCustomModels.ts +1 -1
  67. package/langwatch/src/utils/__tests__/dbMultiTenancyProtection.unit.test.ts +0 -17
  68. package/langwatch/src/utils/permissionsConfig.ts +6 -0
  69. package/langwatch/src/utils/routes.ts +0 -5
  70. package/package.json +1 -1
  71. package/packages/server/dist/cli.cjs +39 -70
  72. package/langwatch/src/pages/[project]/gateway/audit.tsx +0 -606
  73. package/langwatch/src/server/api/routers/gatewayAudit.ts +0 -109
  74. package/langwatch/src/server/gateway/__tests__/audit.service.unit.test.ts +0 -156
  75. package/langwatch/src/server/gateway/audit.service.ts +0 -104
@@ -0,0 +1,241 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import * as root from "@opentelemetry/otlp-transformer/build/src/generated/root";
3
+ import { classifyTokenType, peekCustomerTraceIds } from "../otel";
4
+
5
+ const traceRequestType = (root as any).opentelemetry.proto.collector.trace.v1
6
+ .ExportTraceServiceRequest;
7
+
8
+ // Two distinct 16-byte trace ids (hex) — used across the suite so we can
9
+ // assert the function emits hex regardless of whether the input was bytes
10
+ // or base64.
11
+ const TRACE_ID_HEX_1 = "0bcb2eb84dd52ac9bc1496a99c733880";
12
+ const TRACE_ID_HEX_2 = "1122334455667788aabbccddeeff0011";
13
+ const TRACE_ID_BYTES_1 = Buffer.from(TRACE_ID_HEX_1, "hex");
14
+ const TRACE_ID_BYTES_2 = Buffer.from(TRACE_ID_HEX_2, "hex");
15
+ const TRACE_ID_B64_1 = TRACE_ID_BYTES_1.toString("base64");
16
+ const TRACE_ID_B64_2 = TRACE_ID_BYTES_2.toString("base64");
17
+
18
+ const SPAN_ID_HEX = "1122334455667788";
19
+ const SPAN_ID_BYTES = Buffer.from(SPAN_ID_HEX, "hex");
20
+
21
+ function bufferToArrayBuffer(buf: Buffer): ArrayBuffer {
22
+ return buf.buffer.slice(
23
+ buf.byteOffset,
24
+ buf.byteOffset + buf.byteLength,
25
+ ) as ArrayBuffer;
26
+ }
27
+
28
+ function jsonOtlpBody(traceIdsB64: string[]): ArrayBuffer {
29
+ // Mirrors the wire shape an SDK produces when content-type is
30
+ // application/json: traceId/spanId are base64-encoded strings.
31
+ return bufferToArrayBuffer(
32
+ Buffer.from(
33
+ JSON.stringify({
34
+ resourceSpans: [
35
+ {
36
+ scopeSpans: [
37
+ {
38
+ spans: traceIdsB64.map((tid) => ({
39
+ traceId: tid,
40
+ spanId: SPAN_ID_BYTES.toString("base64"),
41
+ name: "test-span",
42
+ })),
43
+ },
44
+ ],
45
+ },
46
+ ],
47
+ }),
48
+ "utf-8",
49
+ ),
50
+ );
51
+ }
52
+
53
+ function protobufOtlpBody(traceIds: Buffer[]): ArrayBuffer {
54
+ // Use the protobuf encoder so we exercise the same decode path the
55
+ // production handler uses for application/x-protobuf bodies.
56
+ const encoded = traceRequestType
57
+ .encode({
58
+ resourceSpans: [
59
+ {
60
+ scopeSpans: [
61
+ {
62
+ spans: traceIds.map((tid) => ({
63
+ traceId: tid,
64
+ spanId: SPAN_ID_BYTES,
65
+ name: "test-span",
66
+ })),
67
+ },
68
+ ],
69
+ },
70
+ ],
71
+ })
72
+ .finish() as Uint8Array;
73
+ return bufferToArrayBuffer(Buffer.from(encoded));
74
+ }
75
+
76
+ describe("peekCustomerTraceIds", () => {
77
+ describe("when the body is missing or empty", () => {
78
+ it("returns an empty array for a zero-byte ArrayBuffer", () => {
79
+ const empty = new ArrayBuffer(0);
80
+ expect(peekCustomerTraceIds(empty, "application/x-protobuf")).toEqual([]);
81
+ });
82
+
83
+ it("returns an empty array when content-type is JSON and body is empty", () => {
84
+ const empty = new ArrayBuffer(0);
85
+ expect(peekCustomerTraceIds(empty, "application/json")).toEqual([]);
86
+ });
87
+ });
88
+
89
+ describe("when the body is malformed", () => {
90
+ it("returns an empty array for non-protobuf garbage", () => {
91
+ const garbage = bufferToArrayBuffer(Buffer.from([0xff, 0x00, 0xde, 0xad]));
92
+ expect(
93
+ peekCustomerTraceIds(garbage, "application/x-protobuf"),
94
+ ).toEqual([]);
95
+ });
96
+
97
+ it("returns an empty array for invalid JSON", () => {
98
+ const bad = bufferToArrayBuffer(Buffer.from("not-json", "utf-8"));
99
+ expect(peekCustomerTraceIds(bad, "application/json")).toEqual([]);
100
+ });
101
+ });
102
+
103
+ describe("when the body is well-formed JSON OTLP", () => {
104
+ it("decodes base64 trace_ids to lowercase hex", () => {
105
+ const body = jsonOtlpBody([TRACE_ID_B64_1]);
106
+ expect(peekCustomerTraceIds(body, "application/json")).toEqual([
107
+ TRACE_ID_HEX_1,
108
+ ]);
109
+ });
110
+
111
+ it.each([
112
+ "application/json; charset=utf-8",
113
+ "application/json;charset=utf-8",
114
+ " Application/JSON ",
115
+ "APPLICATION/JSON",
116
+ ])(
117
+ "still routes through the JSON parser when content-type is %j",
118
+ (contentType) => {
119
+ const body = jsonOtlpBody([TRACE_ID_B64_1]);
120
+ expect(peekCustomerTraceIds(body, contentType)).toEqual([
121
+ TRACE_ID_HEX_1,
122
+ ]);
123
+ },
124
+ );
125
+
126
+ it("preserves order across distinct trace_ids", () => {
127
+ const body = jsonOtlpBody([TRACE_ID_B64_1, TRACE_ID_B64_2]);
128
+ expect(peekCustomerTraceIds(body, "application/json")).toEqual([
129
+ TRACE_ID_HEX_1,
130
+ TRACE_ID_HEX_2,
131
+ ]);
132
+ });
133
+
134
+ it("deduplicates trace_ids that appear on multiple spans", () => {
135
+ const body = jsonOtlpBody([
136
+ TRACE_ID_B64_1,
137
+ TRACE_ID_B64_1,
138
+ TRACE_ID_B64_2,
139
+ ]);
140
+ expect(peekCustomerTraceIds(body, "application/json")).toEqual([
141
+ TRACE_ID_HEX_1,
142
+ TRACE_ID_HEX_2,
143
+ ]);
144
+ });
145
+ });
146
+
147
+ describe("when the body is well-formed protobuf OTLP", () => {
148
+ it("decodes Uint8Array trace_ids to lowercase hex", () => {
149
+ const body = protobufOtlpBody([TRACE_ID_BYTES_1]);
150
+ expect(
151
+ peekCustomerTraceIds(body, "application/x-protobuf"),
152
+ ).toEqual([TRACE_ID_HEX_1]);
153
+ });
154
+
155
+ it("decodes when no content-type is supplied (defaults to protobuf path)", () => {
156
+ const body = protobufOtlpBody([TRACE_ID_BYTES_1]);
157
+ expect(peekCustomerTraceIds(body, undefined)).toEqual([TRACE_ID_HEX_1]);
158
+ });
159
+
160
+ it("returns multiple unique trace_ids in the order they appear", () => {
161
+ const body = protobufOtlpBody([TRACE_ID_BYTES_1, TRACE_ID_BYTES_2]);
162
+ expect(
163
+ peekCustomerTraceIds(body, "application/x-protobuf"),
164
+ ).toEqual([TRACE_ID_HEX_1, TRACE_ID_HEX_2]);
165
+ });
166
+ });
167
+
168
+ describe("when the body has nothing useful to extract", () => {
169
+ it("returns an empty array for OTLP with no resourceSpans", () => {
170
+ const body = bufferToArrayBuffer(
171
+ Buffer.from(JSON.stringify({}), "utf-8"),
172
+ );
173
+ expect(peekCustomerTraceIds(body, "application/json")).toEqual([]);
174
+ });
175
+
176
+ it("returns an empty array for spans missing traceId", () => {
177
+ const body = bufferToArrayBuffer(
178
+ Buffer.from(
179
+ JSON.stringify({
180
+ resourceSpans: [{ scopeSpans: [{ spans: [{ name: "x" }] }] }],
181
+ }),
182
+ "utf-8",
183
+ ),
184
+ );
185
+ expect(peekCustomerTraceIds(body, "application/json")).toEqual([]);
186
+ });
187
+ });
188
+
189
+ describe("when the request has many distinct trace_ids", () => {
190
+ it("respects the max cap", () => {
191
+ // Build 20 distinct ids, ask for 5
192
+ const ids = Array.from({ length: 20 }, (_, i) =>
193
+ Buffer.from(
194
+ i.toString(16).padStart(2, "0").repeat(16).slice(0, 32),
195
+ "hex",
196
+ ),
197
+ );
198
+ const body = protobufOtlpBody(ids);
199
+ const result = peekCustomerTraceIds(
200
+ body,
201
+ "application/x-protobuf",
202
+ 5,
203
+ );
204
+ expect(result).toHaveLength(5);
205
+ // Each id must be 32 hex chars (16 bytes).
206
+ for (const id of result) {
207
+ expect(id).toMatch(/^[0-9a-f]{32}$/);
208
+ }
209
+ });
210
+ });
211
+ });
212
+
213
+ describe("classifyTokenType", () => {
214
+ describe("when given a PAT prefix", () => {
215
+ it("classifies pat-lw-… tokens as pat", () => {
216
+ expect(classifyTokenType("pat-lw-abcdef123456")).toBe("pat");
217
+ });
218
+ });
219
+
220
+ describe("when given a legacy SDK key prefix", () => {
221
+ it("classifies sk-lw-… tokens as legacy", () => {
222
+ expect(classifyTokenType("sk-lw-abcdef123456")).toBe("legacy");
223
+ });
224
+ });
225
+
226
+ describe("when given anything else", () => {
227
+ it("returns unknown for an arbitrary string", () => {
228
+ expect(classifyTokenType("abc123")).toBe("unknown");
229
+ });
230
+
231
+ it("returns unknown for an empty string", () => {
232
+ expect(classifyTokenType("")).toBe("unknown");
233
+ });
234
+
235
+ it("does not match a PAT prefix in the middle of the token", () => {
236
+ // Defensive: only the start of the string counts. This protects
237
+ // against pathological inputs from being misclassified.
238
+ expect(classifyTokenType("xpat-lw-abc")).toBe("unknown");
239
+ });
240
+ });
241
+ });
@@ -23,10 +23,12 @@ import { getApp } from "~/server/app-layer/app";
23
23
  import { prisma } from "~/server/db";
24
24
  import { TokenResolver } from "~/server/pat/token-resolver";
25
25
  import {
26
+ collectAuthDiagnostics,
26
27
  enforcePatCeiling,
27
28
  extractCredentials,
28
29
  patCeilingDenialResponse,
29
30
  } from "~/server/pat/auth-middleware";
31
+ import { decodeBase64OpenTelemetryId } from "~/server/tracer/utils";
30
32
  import { createLogger } from "~/utils/logger/server";
31
33
  import { captureException } from "~/utils/posthogErrorCapture";
32
34
 
@@ -84,21 +86,74 @@ app.use(loggerMiddleware());
84
86
 
85
87
  const tokenResolver = TokenResolver.create(prisma);
86
88
 
87
- async function authenticateAndCheckLimit(c: {
88
- req: { raw: Request; header: (name: string) => string | undefined };
89
- }) {
89
+ type RouteContext = {
90
+ req: {
91
+ raw: Request;
92
+ path: string;
93
+ method: string;
94
+ header: (name: string) => string | undefined;
95
+ };
96
+ };
97
+
98
+ /**
99
+ * Classifies a token by prefix without exposing the value. Mirrors the
100
+ * `tokenType` field emitted by the unified auth middleware so on-call can
101
+ * filter CloudWatch by SDK shape.
102
+ */
103
+ export function classifyTokenType(token: string): "pat" | "legacy" | "unknown" {
104
+ if (token.startsWith("pat-lw-")) return "pat";
105
+ if (token.startsWith("sk-lw-")) return "legacy";
106
+ return "unknown";
107
+ }
108
+
109
+ /**
110
+ * Resolves credentials and the active project. Logs an auth-diagnostic
111
+ * fingerprint on every failure path so on-call can attribute a 401 to a
112
+ * specific customer/SDK without needing the customer to reproduce. Mirrors
113
+ * the unified-auth middleware (PR #3520) — same fields, same shape, so
114
+ * existing CloudWatch queries work.
115
+ */
116
+ async function authenticate(c: RouteContext, logger: ReturnType<typeof createLogger>) {
117
+ const diag = collectAuthDiagnostics(c);
90
118
  const credentials = extractCredentials((name) => c.req.header(name));
91
119
 
92
120
  if (!credentials) {
93
- return { error: "Authentication token is required. Use X-Auth-Token header or Authorization: Bearer token.", status: 401 as const };
121
+ logger.warn(
122
+ diag,
123
+ diag.hasEmptyAuthToken
124
+ ? "Authentication failed: X-Auth-Token sent but empty"
125
+ : "Authentication failed: no auth header present",
126
+ );
127
+ return {
128
+ error:
129
+ "Authentication token is required. Use X-Auth-Token header or Authorization: Bearer token.",
130
+ status: 401 as const,
131
+ };
94
132
  }
95
133
 
96
- const resolved = await tokenResolver.resolve({
97
- token: credentials.token,
98
- projectId: credentials.projectId,
99
- });
134
+ let resolved;
135
+ try {
136
+ resolved = await tokenResolver.resolve({
137
+ token: credentials.token,
138
+ projectId: credentials.projectId,
139
+ });
140
+ } catch (error) {
141
+ logger.error(
142
+ { ...diag, error },
143
+ "Database error during authentication",
144
+ );
145
+ return { error: "Authentication service error.", status: 500 as const };
146
+ }
100
147
 
101
148
  if (!resolved) {
149
+ logger.warn(
150
+ {
151
+ ...diag,
152
+ tokenType: classifyTokenType(credentials.token),
153
+ hasProjectId: !!credentials.projectId,
154
+ },
155
+ "Authentication failed: invalid credentials",
156
+ );
102
157
  return { error: "Invalid auth token.", status: 401 as const };
103
158
  }
104
159
 
@@ -112,56 +167,132 @@ async function authenticateAndCheckLimit(c: {
112
167
  });
113
168
  } catch (error) {
114
169
  const denial = patCeilingDenialResponse(error);
170
+ logger.warn(
171
+ {
172
+ ...diag,
173
+ projectId: resolved.project.id,
174
+ tokenType: classifyTokenType(credentials.token),
175
+ denialStatus: denial.status,
176
+ },
177
+ "PAT permission denied for traces:create",
178
+ );
115
179
  return { error: denial.message, status: denial.status };
116
180
  }
117
181
 
118
- const project = resolved.project;
182
+ return { project: resolved.project, resolved };
183
+ }
119
184
 
120
- // Check usage limits
185
+ /**
186
+ * Checks usage limits for the project and returns a 429 result if exceeded.
187
+ * Logs `Project has reached plan limit` with `customerTraceIds` so a
188
+ * customer-supplied trace_id can be matched to the rejection. The check
189
+ * itself is wrapped in try/catch — on lookup failure we log and let the
190
+ * request through (same behaviour as before).
191
+ */
192
+ async function enforcePlanLimit(
193
+ project: { id: string; teamId: string; team: { organizationId: string } },
194
+ customerTraceIds: string[],
195
+ logger: ReturnType<typeof createLogger>,
196
+ ) {
121
197
  try {
122
198
  const limitResult = await getApp().usage.checkLimit({
123
199
  teamId: project.teamId,
124
200
  });
125
201
 
126
- if (limitResult.exceeded) {
127
- try {
128
- const activePlan = await getApp().planProvider.getActivePlan({
202
+ if (!limitResult.exceeded) return null;
203
+
204
+ try {
205
+ const activePlan = await getApp().planProvider.getActivePlan({
206
+ organizationId: project.team.organizationId,
207
+ });
208
+ getApp()
209
+ .usageLimits.notifyPlanLimitReached({
129
210
  organizationId: project.team.organizationId,
211
+ planName: activePlan.name ?? "free",
212
+ })
213
+ .catch((error: unknown) => {
214
+ logger.error(
215
+ { error, projectId: project.id },
216
+ "Error sending plan limit notification",
217
+ );
130
218
  });
131
- getApp()
132
- .usageLimits.notifyPlanLimitReached({
133
- organizationId: project.team.organizationId,
134
- planName: activePlan.name ?? "free",
135
- })
136
- .catch((error: unknown) => {
137
- loggerTraces.error(
138
- { error, projectId: project.id },
139
- "Error sending plan limit notification",
140
- );
141
- });
142
- } catch (error) {
143
- loggerTraces.error(
144
- { error, projectId: project.id },
145
- "Error getting active plan information",
146
- );
147
- }
148
-
149
- return {
150
- error: `ERR_PLAN_LIMIT: ${limitResult.message}`,
151
- status: 429 as const,
152
- };
219
+ } catch (error) {
220
+ logger.error(
221
+ { error, projectId: project.id },
222
+ "Error getting active plan information",
223
+ );
153
224
  }
225
+
226
+ logger.info(
227
+ {
228
+ projectId: project.id,
229
+ currentMonthMessagesCount: limitResult.count,
230
+ activePlanName: limitResult.planName,
231
+ maxMessagesPerMonth: limitResult.maxMessagesPerMonth,
232
+ customerTraceIds,
233
+ },
234
+ "Project has reached plan limit",
235
+ );
236
+
237
+ return {
238
+ error: `ERR_PLAN_LIMIT: ${limitResult.message}`,
239
+ status: 429 as const,
240
+ };
154
241
  } catch (error) {
155
- loggerTraces.error(
156
- { error, projectId: project.id },
242
+ logger.error(
243
+ { error, projectId: project.id, customerTraceIds },
157
244
  "Error checking trace limit",
158
245
  );
159
246
  captureException(error as Error, {
160
247
  extra: { projectId: project.id },
161
248
  });
249
+ return null;
162
250
  }
251
+ }
163
252
 
164
- return { project, resolved };
253
+ /**
254
+ * Best-effort extraction of customer trace_ids from an OTLP traces body.
255
+ * Returns up to `max` unique hex-encoded trace_ids. Never throws — if the
256
+ * body is empty, malformed, or unparsable, returns an empty array. Used to
257
+ * tag error logs (plan-limit, parse failure) so a customer who reports
258
+ * "I sent trace_id X but it didn't appear" can be matched to the rejection.
259
+ *
260
+ * JSON-OTLP serialises trace_id as base64 strings; protobuf-OTLP decodes
261
+ * them as Uint8Array. `decodeBase64OpenTelemetryId` handles both — output
262
+ * is always lowercase hex, the same shape the rest of the platform uses.
263
+ */
264
+ export function peekCustomerTraceIds(
265
+ body: ArrayBuffer,
266
+ contentType: string | undefined,
267
+ max = 10,
268
+ ): string[] {
269
+ if (!body || body.byteLength === 0) return [];
270
+ // Normalise so "application/json; charset=utf-8" is recognised. The OTLP
271
+ // HTTP spec lets exporters append parameters and case isn't guaranteed.
272
+ const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase();
273
+ let req: IExportTraceServiceRequest;
274
+ try {
275
+ if (mediaType === "application/json") {
276
+ req = JSON.parse(Buffer.from(body).toString("utf-8"));
277
+ } else {
278
+ req = traceRequestType.decode(new Uint8Array(body));
279
+ }
280
+ } catch {
281
+ return [];
282
+ }
283
+ const ids = new Set<string>();
284
+ for (const rs of req.resourceSpans ?? []) {
285
+ for (const ss of rs.scopeSpans ?? []) {
286
+ for (const sp of ss.spans ?? []) {
287
+ const decoded = decodeBase64OpenTelemetryId(sp.traceId);
288
+ if (decoded) {
289
+ ids.add(decoded);
290
+ if (ids.size >= max) return Array.from(ids);
291
+ }
292
+ }
293
+ }
294
+ }
295
+ return Array.from(ids);
165
296
  }
166
297
 
167
298
  // ── POST /traces ─────────────────────────────────────────────────────
@@ -173,7 +304,9 @@ app.post("/traces", async (c) => {
173
304
  "TracesV1.handleTracesRequest",
174
305
  { kind: SpanKind.SERVER },
175
306
  async (span) => {
176
- const authResult = await authenticateAndCheckLimit(c);
307
+ // Auth first — 401s/permission failures should not pay body decompression
308
+ // cost, and body content is irrelevant when we don't know who's calling.
309
+ const authResult = await authenticate(c, loggerTraces);
177
310
 
178
311
  if ("error" in authResult) {
179
312
  span.setStatus({ code: SpanStatusCode.ERROR, message: authResult.error });
@@ -184,12 +317,54 @@ app.post("/traces", async (c) => {
184
317
  span.setAttribute("langwatch.project.id", project.id);
185
318
 
186
319
  const contentType = c.req.header("content-type");
187
- const body = await readBody(c.req.raw);
320
+
321
+ let body: ArrayBuffer;
322
+ try {
323
+ body = await readBody(c.req.raw);
324
+ } catch (error) {
325
+ loggerTraces.warn(
326
+ {
327
+ projectId: project.id,
328
+ contentEncoding: c.req.header("content-encoding") ?? null,
329
+ error: error instanceof Error ? error.message : String(error),
330
+ },
331
+ "OTel /traces: failed to read request body",
332
+ );
333
+ span.setStatus({ code: SpanStatusCode.ERROR, message: "Body read failed" });
334
+ return c.json({ error: "Unable to read body" }, 400);
335
+ }
336
+
337
+ // Best-effort. If the body can't be peeked (malformed, unsupported
338
+ // shape, etc.), customerTraceIds stays empty — the projectId is still
339
+ // logged on every subsequent failure for correlation.
340
+ const customerTraceIds = peekCustomerTraceIds(body, contentType);
341
+ if (customerTraceIds.length > 0) {
342
+ span.setAttribute(
343
+ "langwatch.otel.customer_trace_ids",
344
+ customerTraceIds.join(","),
345
+ );
346
+ }
347
+
348
+ const limitFailure = await enforcePlanLimit(
349
+ project,
350
+ customerTraceIds,
351
+ loggerTraces,
352
+ );
353
+ if (limitFailure) {
354
+ span.setStatus({
355
+ code: SpanStatusCode.ERROR,
356
+ message: limitFailure.error,
357
+ });
358
+ return c.json(
359
+ { message: limitFailure.error },
360
+ { status: limitFailure.status },
361
+ );
362
+ }
188
363
 
189
364
  const emptyPartialSuccess = { rejectedSpans: 0, errorMessage: "" };
190
365
 
191
366
  if (body.byteLength === 0) {
192
- loggerTraces.debug("Received empty trace request, ignoring");
367
+ loggerTraces.debug({ projectId: project.id }, "Received empty trace request, ignoring");
193
368
  return c.json({
194
369
  message: "No traces to process",
195
370
  partialSuccess: emptyPartialSuccess,
@@ -219,6 +394,8 @@ app.post("/traces", async (c) => {
219
394
  loggerTraces.error(
220
395
  {
221
396
  error: jsonError,
397
+ projectId: project.id,
398
+ customerTraceIds,
222
399
  traceRequest: Buffer.from(body).toString("base64"),
223
400
  },
224
401
  "error parsing traces",
@@ -226,6 +403,7 @@ app.post("/traces", async (c) => {
226
403
  captureException(error, {
227
404
  extra: {
228
405
  projectId: project.id,
406
+ customerTraceIds,
229
407
  traceRequest: Buffer.from(body).toString("base64"),
230
408
  jsonError,
231
409
  },
@@ -268,7 +446,7 @@ app.post("/logs", async (c) => {
268
446
  "[POST] /api/otel/v1/logs",
269
447
  { kind: SpanKind.SERVER },
270
448
  async (span) => {
271
- const authResult = await authenticateAndCheckLimit(c);
449
+ const authResult = await authenticate(c, loggerLogs);
272
450
 
273
451
  if ("error" in authResult) {
274
452
  span.setStatus({ code: SpanStatusCode.ERROR, message: authResult.error });
@@ -278,8 +456,36 @@ app.post("/logs", async (c) => {
278
456
  const { project, resolved } = authResult;
279
457
  span.setAttribute("langwatch.project.id", project.id);
280
458
 
459
+ const limitFailure = await enforcePlanLimit(project, [], loggerLogs);
460
+ if (limitFailure) {
461
+ span.setStatus({
462
+ code: SpanStatusCode.ERROR,
463
+ message: limitFailure.error,
464
+ });
465
+ return c.json(
466
+ { message: limitFailure.error },
467
+ { status: limitFailure.status },
468
+ );
469
+ }
470
+
281
471
  const contentType = c.req.header("content-type");
282
- const body = await readBody(c.req.raw);
472
+
473
+ let body: ArrayBuffer;
474
+ try {
475
+ body = await readBody(c.req.raw);
476
+ } catch (error) {
477
+ loggerLogs.warn(
478
+ {
479
+ projectId: project.id,
480
+ contentEncoding: c.req.header("content-encoding") ?? null,
481
+ error: error instanceof Error ? error.message : String(error),
482
+ },
483
+ "OTel /logs: failed to read request body",
484
+ );
485
+ span.setStatus({ code: SpanStatusCode.ERROR, message: "Body read failed" });
486
+ return c.json({ error: "Unable to read body" }, 400);
487
+ }
488
+
283
489
  let logRequest: IExportLogsServiceRequest;
284
490
  try {
285
491
  if (contentType === "application/json") {
@@ -302,6 +508,7 @@ app.post("/logs", async (c) => {
302
508
  loggerLogs.error(
303
509
  {
304
510
  error: jsonError,
511
+ projectId: project.id,
305
512
  logRequest: Buffer.from(body).toString("base64"),
306
513
  },
307
514
  "error parsing logs",
@@ -344,7 +551,7 @@ app.post("/metrics", async (c) => {
344
551
  "[POST] /api/otel/v1/metrics",
345
552
  { kind: SpanKind.SERVER },
346
553
  async (span) => {
347
- const authResult = await authenticateAndCheckLimit(c);
554
+ const authResult = await authenticate(c, loggerMetrics);
348
555
 
349
556
  if ("error" in authResult) {
350
557
  span.setStatus({ code: SpanStatusCode.ERROR, message: authResult.error });
@@ -354,8 +561,36 @@ app.post("/metrics", async (c) => {
354
561
  const { project, resolved } = authResult;
355
562
  span.setAttribute("langwatch.project.id", project.id);
356
563
 
564
+ const limitFailure = await enforcePlanLimit(project, [], loggerMetrics);
565
+ if (limitFailure) {
566
+ span.setStatus({
567
+ code: SpanStatusCode.ERROR,
568
+ message: limitFailure.error,
569
+ });
570
+ return c.json(
571
+ { message: limitFailure.error },
572
+ { status: limitFailure.status },
573
+ );
574
+ }
575
+
357
576
  const contentType = c.req.header("content-type");
358
- const body = await readBody(c.req.raw);
577
+
578
+ let body: ArrayBuffer;
579
+ try {
580
+ body = await readBody(c.req.raw);
581
+ } catch (error) {
582
+ loggerMetrics.warn(
583
+ {
584
+ projectId: project.id,
585
+ contentEncoding: c.req.header("content-encoding") ?? null,
586
+ error: error instanceof Error ? error.message : String(error),
587
+ },
588
+ "OTel /metrics: failed to read request body",
589
+ );
590
+ span.setStatus({ code: SpanStatusCode.ERROR, message: "Body read failed" });
591
+ return c.json({ error: "Unable to read body" }, 400);
592
+ }
593
+
359
594
  let metricsRequest: IExportMetricsServiceRequest;
360
595
  try {
361
596
  if (contentType === "application/json") {
@@ -378,6 +613,7 @@ app.post("/metrics", async (c) => {
378
613
  loggerMetrics.error(
379
614
  {
380
615
  error: jsonError,
616
+ projectId: project.id,
381
617
  metricsRequest: Buffer.from(body).toString("base64"),
382
618
  },
383
619
  "error parsing metrics",