@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.
- package/langwatch/prisma/migrations/20260425000000_consolidate_gateway_audit_into_audit_log/migration.sql +44 -0
- package/langwatch/prisma/migrations/20260426150000_drop_redundant_audit_log_org_index/migration.sql +25 -0
- package/langwatch/prisma/schema.prisma +34 -41
- package/langwatch/scripts/seed-gateway-dogfood.ts +26 -26
- package/langwatch/src/app/api/gateway-platform/[[...route]]/app.ts +8 -4
- package/langwatch/src/app/api/middleware/trace-limit.ts +10 -0
- package/langwatch/src/components/MainMenu.tsx +4 -15
- package/langwatch/src/components/SettingsLayout.tsx +1 -1
- package/langwatch/src/components/llmPromptConfigs/__tests__/LLMConfigPopover.test.tsx +45 -0
- package/langwatch/src/components/llmPromptConfigs/parameterRegistry.ts +22 -13
- package/langwatch/src/components/prompts/PromptEditorDrawer.tsx +5 -3
- package/langwatch/src/components/settings/AddCustomModelDialog.tsx +7 -6
- package/langwatch/src/evaluations-v3/__tests__/TableDisplay.integration.test.tsx +90 -5
- package/langwatch/src/evaluations-v3/__tests__/TableSettingsMenu.integration.test.tsx +26 -26
- package/langwatch/src/evaluations-v3/components/DatasetSection/TableCell.tsx +2 -10
- package/langwatch/src/evaluations-v3/components/EvaluationsV3Table.tsx +10 -4
- package/langwatch/src/evaluations-v3/components/TableSettingsMenu.tsx +6 -6
- package/langwatch/src/evaluations-v3/components/TargetSection/EvaluatorChip.tsx +19 -11
- package/langwatch/src/evaluations-v3/components/TargetSection/TargetCell.tsx +55 -42
- package/langwatch/src/evaluations-v3/components/TargetSection/TargetHeader.tsx +2 -1
- package/langwatch/src/evaluations-v3/components/TargetSection/__tests__/EvaluatorChip.test.tsx +57 -0
- package/langwatch/src/evaluations-v3/components/TargetSection/__tests__/TargetCell.test.tsx +199 -11
- package/langwatch/src/evaluations-v3/components/VirtualizedTableBody.tsx +1 -1
- package/langwatch/src/evaluations-v3/constants.ts +9 -0
- package/langwatch/src/evaluations-v3/types/__tests__/persistence.test.ts +1 -1
- package/langwatch/src/evaluations-v3/types.ts +13 -1
- package/langwatch/src/evaluations-v3/utils/__tests__/evaluatorEditorCallbacks.test.ts +32 -0
- package/langwatch/src/evaluations-v3/utils/evaluatorEditorCallbacks.ts +36 -5
- package/langwatch/src/optimization_studio/components/datasets/DatasetSelection.tsx +1 -6
- package/langwatch/src/optimization_studio/components/datasets/__tests__/DatasetSelection.integration.test.tsx +194 -0
- package/langwatch/src/optimization_studio/components/drawers/SignaturePromptEditorBridge.tsx +6 -6
- package/langwatch/src/optimization_studio/components/drawers/__tests__/SignaturePromptEditorBridge.integration.test.tsx +36 -11
- package/langwatch/src/pages/[project]/gateway/budgets/[id].tsx +1 -1
- package/langwatch/src/pages/[project]/gateway/virtual-keys/[id].tsx +1 -1
- package/langwatch/src/pages/settings/audit-log.tsx +82 -59
- package/langwatch/src/routes.tsx +0 -4
- package/langwatch/src/server/agents/agent.service.ts +6 -2
- package/langwatch/src/server/api/__tests__/rbac-integration.test.ts +53 -0
- package/langwatch/src/server/api/__tests__/rbac.auditLog.test.ts +100 -0
- package/langwatch/src/server/api/rbac.ts +12 -0
- package/langwatch/src/server/api/root.ts +0 -2
- package/langwatch/src/server/api/routers/organization.ts +1 -1
- package/langwatch/src/server/app-layer/organizations/repositories/organization.prisma.repository.ts +58 -120
- package/langwatch/src/server/app-layer/organizations/repositories/organization.repository.ts +8 -11
- package/langwatch/src/server/evaluators/evaluator.service.ts +6 -2
- package/langwatch/src/server/gateway/__tests__/auditLog.consolidation.integration.test.ts +237 -0
- package/langwatch/src/server/gateway/__tests__/cacheRule.service.unit.test.ts +2 -2
- package/langwatch/src/server/gateway/__tests__/providerCredential.service.unit.test.ts +6 -6
- package/langwatch/src/server/gateway/__tests__/virtualKey.service.unit.test.ts +6 -6
- package/langwatch/src/server/gateway/auditLog.repository.ts +46 -8
- package/langwatch/src/server/gateway/auditSerializer.ts +2 -2
- package/langwatch/src/server/gateway/budget.service.ts +6 -6
- package/langwatch/src/server/gateway/cacheRule.service.ts +5 -5
- package/langwatch/src/server/gateway/providerCredential.service.ts +5 -5
- package/langwatch/src/server/gateway/virtualKey.service.ts +9 -9
- package/langwatch/src/server/pat/__tests__/auth-middleware.unit.test.ts +138 -3
- package/langwatch/src/server/pat/auth-middleware.ts +68 -13
- package/langwatch/src/server/routes/__tests__/otel.unit.test.ts +241 -0
- package/langwatch/src/server/routes/otel.ts +281 -45
- package/langwatch/src/server/scenarios/adapters/__tests__/http-agent.adapter.test.ts +271 -6
- package/langwatch/src/server/scenarios/adapters/http-agent.adapter.ts +43 -35
- package/langwatch/src/server/scenarios/execution/http-template-engine.ts +124 -0
- package/langwatch/src/server/scenarios/execution/serialized-adapters/__tests__/http-agent.adapter.unit.test.ts +180 -0
- package/langwatch/src/server/scenarios/execution/serialized-adapters/http-agent.adapter.ts +26 -30
- package/langwatch/src/tasks/__tests__/migrateCustomModels.unit.test.ts +0 -2
- package/langwatch/src/tasks/migrateCustomModels.ts +1 -1
- package/langwatch/src/utils/__tests__/dbMultiTenancyProtection.unit.test.ts +0 -17
- package/langwatch/src/utils/permissionsConfig.ts +6 -0
- package/langwatch/src/utils/routes.ts +0 -5
- package/package.json +1 -1
- package/packages/server/dist/cli.cjs +39 -70
- package/langwatch/src/pages/[project]/gateway/audit.tsx +0 -606
- package/langwatch/src/server/api/routers/gatewayAudit.ts +0 -109
- package/langwatch/src/server/gateway/__tests__/audit.service.unit.test.ts +0 -156
- package/langwatch/src/server/gateway/audit.service.ts +0 -104
|
@@ -1,21 +1,59 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
2
|
+
* Thin adapter that lets gateway services write governance rows to the
|
|
3
|
+
* shared `AuditLog` table using the gateway-shape (action enum,
|
|
4
|
+
* targetKind, before/after diff). Same call sites as before; the table
|
|
5
|
+
* underneath is now the unified one — see migration
|
|
6
|
+
* `20260425000000_consolidate_gateway_audit_into_audit_log`.
|
|
7
|
+
*
|
|
8
|
+
* Gateway services pass an `actorUserId` through to keep attribution
|
|
9
|
+
* consistent with the platform `auditLog()` helper.
|
|
4
10
|
*/
|
|
5
|
-
import { Prisma, type
|
|
11
|
+
import { Prisma, type PrismaClient } from "@prisma/client";
|
|
12
|
+
|
|
13
|
+
// Dotted-lowercase past-tense convention (Stripe / GitHub / Vercel / Datadog).
|
|
14
|
+
// Namespaced under `gateway.` so a single `LIKE 'gateway.%'` filter scopes
|
|
15
|
+
// SIEM exports to the entire gateway surface. See docs/ai-gateway/audit.mdx
|
|
16
|
+
// for the full code table + rationale.
|
|
17
|
+
export const GATEWAY_AUDIT_ACTIONS = [
|
|
18
|
+
"gateway.virtual_key.created",
|
|
19
|
+
"gateway.virtual_key.updated",
|
|
20
|
+
"gateway.virtual_key.rotated",
|
|
21
|
+
"gateway.virtual_key.revoked",
|
|
22
|
+
"gateway.virtual_key.deleted",
|
|
23
|
+
"gateway.budget.created",
|
|
24
|
+
"gateway.budget.updated",
|
|
25
|
+
"gateway.budget.deleted",
|
|
26
|
+
"gateway.provider_binding.created",
|
|
27
|
+
"gateway.provider_binding.updated",
|
|
28
|
+
"gateway.provider_binding.deleted",
|
|
29
|
+
"gateway.cache_rule.created",
|
|
30
|
+
"gateway.cache_rule.updated",
|
|
31
|
+
"gateway.cache_rule.deleted",
|
|
32
|
+
] as const;
|
|
33
|
+
|
|
34
|
+
export type GatewayAuditAction = (typeof GATEWAY_AUDIT_ACTIONS)[number];
|
|
35
|
+
|
|
36
|
+
export const GATEWAY_AUDIT_TARGET_KINDS = [
|
|
37
|
+
"virtual_key",
|
|
38
|
+
"budget",
|
|
39
|
+
"provider_binding",
|
|
40
|
+
"cache_rule",
|
|
41
|
+
] as const;
|
|
42
|
+
|
|
43
|
+
export type GatewayAuditTargetKind = (typeof GATEWAY_AUDIT_TARGET_KINDS)[number];
|
|
6
44
|
|
|
7
45
|
export type AppendAuditInput = {
|
|
8
46
|
organizationId: string;
|
|
9
47
|
projectId?: string | null;
|
|
10
|
-
actorUserId
|
|
48
|
+
actorUserId: string;
|
|
11
49
|
action: GatewayAuditAction;
|
|
12
|
-
targetKind:
|
|
50
|
+
targetKind: GatewayAuditTargetKind;
|
|
13
51
|
targetId: string;
|
|
14
52
|
before?: Prisma.InputJsonValue | null;
|
|
15
53
|
after?: Prisma.InputJsonValue | null;
|
|
16
54
|
};
|
|
17
55
|
|
|
18
|
-
export class
|
|
56
|
+
export class GatewayAuditAdapter {
|
|
19
57
|
constructor(private readonly prisma: PrismaClient) {}
|
|
20
58
|
|
|
21
59
|
async append(
|
|
@@ -23,11 +61,11 @@ export class GatewayAuditLogRepository {
|
|
|
23
61
|
tx?: Prisma.TransactionClient,
|
|
24
62
|
): Promise<void> {
|
|
25
63
|
const client = tx ?? this.prisma;
|
|
26
|
-
await client.
|
|
64
|
+
await client.auditLog.create({
|
|
27
65
|
data: {
|
|
66
|
+
userId: input.actorUserId,
|
|
28
67
|
organizationId: input.organizationId,
|
|
29
68
|
projectId: input.projectId ?? null,
|
|
30
|
-
actorUserId: input.actorUserId ?? null,
|
|
31
69
|
action: input.action,
|
|
32
70
|
targetKind: input.targetKind,
|
|
33
71
|
targetId: input.targetId,
|
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* carrying a BigInt column (VK.revision, GatewayChangeEvent.revision).
|
|
7
7
|
* Caught via unit test — see virtualKey.service.unit.test.ts.
|
|
8
8
|
*
|
|
9
|
-
* All gateway services that write to `
|
|
10
|
-
* `
|
|
9
|
+
* All gateway services that write to `AuditLog.before` /
|
|
10
|
+
* `AuditLog.after` should go through this helper instead of reaching
|
|
11
11
|
* for JSON.parse(JSON.stringify(row)) directly — it also keeps the
|
|
12
12
|
* over-the-wire representation (decimal string for BigInt) consistent with
|
|
13
13
|
* `GatewayConfigPayload.revision` so operators see the same shape whether
|
|
@@ -21,7 +21,7 @@ import type {
|
|
|
21
21
|
import { Prisma } from "@prisma/client";
|
|
22
22
|
import { TRPCError } from "@trpc/server";
|
|
23
23
|
|
|
24
|
-
import {
|
|
24
|
+
import { GatewayAuditAdapter } from "./auditLog.repository";
|
|
25
25
|
import { serializeRowForAudit } from "./auditSerializer";
|
|
26
26
|
import { GatewayBudgetClickHouseRepository } from "./budget.clickhouse.repository";
|
|
27
27
|
import { nextResetAt, shouldResetBudget } from "./budgetWindow";
|
|
@@ -147,7 +147,7 @@ export class GatewayBudgetService {
|
|
|
147
147
|
constructor(
|
|
148
148
|
private readonly prisma: PrismaClient,
|
|
149
149
|
private readonly changeEvents = new ChangeEventRepository(prisma),
|
|
150
|
-
private readonly auditLog = new
|
|
150
|
+
private readonly auditLog = new GatewayAuditAdapter(prisma),
|
|
151
151
|
private readonly chRepo?: GatewayBudgetClickHouseRepository,
|
|
152
152
|
) {}
|
|
153
153
|
|
|
@@ -158,7 +158,7 @@ export class GatewayBudgetService {
|
|
|
158
158
|
return new GatewayBudgetService(
|
|
159
159
|
prisma,
|
|
160
160
|
new ChangeEventRepository(prisma),
|
|
161
|
-
new
|
|
161
|
+
new GatewayAuditAdapter(prisma),
|
|
162
162
|
chRepo,
|
|
163
163
|
);
|
|
164
164
|
}
|
|
@@ -393,7 +393,7 @@ export class GatewayBudgetService {
|
|
|
393
393
|
organizationId: input.organizationId,
|
|
394
394
|
projectId,
|
|
395
395
|
actorUserId: input.actorUserId,
|
|
396
|
-
action: "
|
|
396
|
+
action: "gateway.budget.created",
|
|
397
397
|
targetKind: "budget",
|
|
398
398
|
targetId: row.id,
|
|
399
399
|
after: serializeRowForAudit(row),
|
|
@@ -441,7 +441,7 @@ export class GatewayBudgetService {
|
|
|
441
441
|
{
|
|
442
442
|
organizationId: input.organizationId,
|
|
443
443
|
actorUserId: input.actorUserId,
|
|
444
|
-
action: "
|
|
444
|
+
action: "gateway.budget.updated",
|
|
445
445
|
targetKind: "budget",
|
|
446
446
|
targetId: updated.id,
|
|
447
447
|
before,
|
|
@@ -475,7 +475,7 @@ export class GatewayBudgetService {
|
|
|
475
475
|
{
|
|
476
476
|
organizationId: input.organizationId,
|
|
477
477
|
actorUserId: input.actorUserId,
|
|
478
|
-
action: "
|
|
478
|
+
action: "gateway.budget.deleted",
|
|
479
479
|
targetKind: "budget",
|
|
480
480
|
targetId: updated.id,
|
|
481
481
|
before,
|
|
@@ -40,7 +40,7 @@ import type {
|
|
|
40
40
|
import { Prisma } from "@prisma/client";
|
|
41
41
|
import { TRPCError } from "@trpc/server";
|
|
42
42
|
|
|
43
|
-
import {
|
|
43
|
+
import { GatewayAuditAdapter } from "./auditLog.repository";
|
|
44
44
|
import { serializeRowForAudit } from "./auditSerializer";
|
|
45
45
|
import { ChangeEventRepository } from "./changeEvent.repository";
|
|
46
46
|
|
|
@@ -145,7 +145,7 @@ export class GatewayCacheRuleService {
|
|
|
145
145
|
constructor(
|
|
146
146
|
private readonly prisma: PrismaClient,
|
|
147
147
|
private readonly changeEvents = new ChangeEventRepository(prisma),
|
|
148
|
-
private readonly auditLog = new
|
|
148
|
+
private readonly auditLog = new GatewayAuditAdapter(prisma),
|
|
149
149
|
) {}
|
|
150
150
|
|
|
151
151
|
static create(prisma: PrismaClient): GatewayCacheRuleService {
|
|
@@ -198,7 +198,7 @@ export class GatewayCacheRuleService {
|
|
|
198
198
|
{
|
|
199
199
|
organizationId: input.organizationId,
|
|
200
200
|
actorUserId: input.actorUserId,
|
|
201
|
-
action: "
|
|
201
|
+
action: "gateway.cache_rule.created",
|
|
202
202
|
targetKind: "cache_rule",
|
|
203
203
|
targetId: row.id,
|
|
204
204
|
after: serializeRowForAudit(row),
|
|
@@ -253,7 +253,7 @@ export class GatewayCacheRuleService {
|
|
|
253
253
|
{
|
|
254
254
|
organizationId: input.organizationId,
|
|
255
255
|
actorUserId: input.actorUserId,
|
|
256
|
-
action: "
|
|
256
|
+
action: "gateway.cache_rule.updated",
|
|
257
257
|
targetKind: "cache_rule",
|
|
258
258
|
targetId: updated.id,
|
|
259
259
|
before,
|
|
@@ -287,7 +287,7 @@ export class GatewayCacheRuleService {
|
|
|
287
287
|
{
|
|
288
288
|
organizationId: input.organizationId,
|
|
289
289
|
actorUserId: input.actorUserId,
|
|
290
|
-
action: "
|
|
290
|
+
action: "gateway.cache_rule.deleted",
|
|
291
291
|
targetKind: "cache_rule",
|
|
292
292
|
targetId: updated.id,
|
|
293
293
|
before,
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
} from "@prisma/client";
|
|
13
13
|
import { TRPCError } from "@trpc/server";
|
|
14
14
|
|
|
15
|
-
import {
|
|
15
|
+
import { GatewayAuditAdapter } from "./auditLog.repository";
|
|
16
16
|
import { serializeRowForAudit } from "./auditSerializer";
|
|
17
17
|
import { ChangeEventRepository } from "./changeEvent.repository";
|
|
18
18
|
|
|
@@ -49,7 +49,7 @@ export class GatewayProviderCredentialService {
|
|
|
49
49
|
constructor(
|
|
50
50
|
private readonly prisma: PrismaClient,
|
|
51
51
|
private readonly changeEvents = new ChangeEventRepository(prisma),
|
|
52
|
-
private readonly auditLog = new
|
|
52
|
+
private readonly auditLog = new GatewayAuditAdapter(prisma),
|
|
53
53
|
) {}
|
|
54
54
|
|
|
55
55
|
static create(prisma: PrismaClient): GatewayProviderCredentialService {
|
|
@@ -124,7 +124,7 @@ export class GatewayProviderCredentialService {
|
|
|
124
124
|
organizationId: input.organizationId,
|
|
125
125
|
projectId: input.projectId,
|
|
126
126
|
actorUserId: input.actorUserId,
|
|
127
|
-
action: "
|
|
127
|
+
action: "gateway.provider_binding.created",
|
|
128
128
|
targetKind: "provider_binding",
|
|
129
129
|
targetId: row.id,
|
|
130
130
|
after: serializeRowForAudit(row),
|
|
@@ -193,7 +193,7 @@ export class GatewayProviderCredentialService {
|
|
|
193
193
|
organizationId: input.organizationId,
|
|
194
194
|
projectId: input.projectId,
|
|
195
195
|
actorUserId: input.actorUserId,
|
|
196
|
-
action: "
|
|
196
|
+
action: "gateway.provider_binding.updated",
|
|
197
197
|
targetKind: "provider_binding",
|
|
198
198
|
targetId: updated.id,
|
|
199
199
|
before,
|
|
@@ -235,7 +235,7 @@ export class GatewayProviderCredentialService {
|
|
|
235
235
|
organizationId: args.organizationId,
|
|
236
236
|
projectId: args.projectId,
|
|
237
237
|
actorUserId: args.actorUserId,
|
|
238
|
-
action: "
|
|
238
|
+
action: "gateway.provider_binding.updated",
|
|
239
239
|
targetKind: "provider_binding",
|
|
240
240
|
targetId: updated.id,
|
|
241
241
|
before,
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Business logic for virtual keys. Framework-agnostic (no tRPC / Hono imports).
|
|
3
3
|
* Every mutation method runs inside a Prisma transaction that also appends a
|
|
4
|
-
* GatewayChangeEvent (for the gateway's long-poll feed) and
|
|
5
|
-
*
|
|
4
|
+
* GatewayChangeEvent (for the gateway's long-poll feed) and an
|
|
5
|
+
* AuditLog row in gateway shape (for humans).
|
|
6
6
|
*/
|
|
7
7
|
import { randomBytes } from "crypto";
|
|
8
8
|
|
|
@@ -10,7 +10,7 @@ import type { PrismaClient, VirtualKey } from "@prisma/client";
|
|
|
10
10
|
import type { Prisma } from "@prisma/client";
|
|
11
11
|
import { TRPCError } from "@trpc/server";
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import { GatewayAuditAdapter } from "./auditLog.repository";
|
|
14
14
|
import { serializeRowForAudit } from "./auditSerializer";
|
|
15
15
|
import { ChangeEventRepository } from "./changeEvent.repository";
|
|
16
16
|
import {
|
|
@@ -89,7 +89,7 @@ export class VirtualKeyService {
|
|
|
89
89
|
private readonly prisma: PrismaClient,
|
|
90
90
|
private readonly repository: VirtualKeyRepository,
|
|
91
91
|
private readonly changeEvents: ChangeEventRepository,
|
|
92
|
-
private readonly auditLog:
|
|
92
|
+
private readonly auditLog: GatewayAuditAdapter,
|
|
93
93
|
) {}
|
|
94
94
|
|
|
95
95
|
static create(prisma: PrismaClient): VirtualKeyService {
|
|
@@ -97,7 +97,7 @@ export class VirtualKeyService {
|
|
|
97
97
|
prisma,
|
|
98
98
|
new VirtualKeyRepository(prisma),
|
|
99
99
|
new ChangeEventRepository(prisma),
|
|
100
|
-
new
|
|
100
|
+
new GatewayAuditAdapter(prisma),
|
|
101
101
|
);
|
|
102
102
|
}
|
|
103
103
|
|
|
@@ -171,7 +171,7 @@ export class VirtualKeyService {
|
|
|
171
171
|
organizationId: input.organizationId,
|
|
172
172
|
projectId: input.projectId,
|
|
173
173
|
actorUserId: input.actorUserId,
|
|
174
|
-
action: "
|
|
174
|
+
action: "gateway.virtual_key.created",
|
|
175
175
|
targetKind: "virtual_key",
|
|
176
176
|
targetId: vk.id,
|
|
177
177
|
after: serialiseForAudit(vk),
|
|
@@ -242,7 +242,7 @@ export class VirtualKeyService {
|
|
|
242
242
|
organizationId: input.organizationId,
|
|
243
243
|
projectId: input.projectId,
|
|
244
244
|
actorUserId: input.actorUserId,
|
|
245
|
-
action: "
|
|
245
|
+
action: "gateway.virtual_key.updated",
|
|
246
246
|
targetKind: "virtual_key",
|
|
247
247
|
targetId: vk.id,
|
|
248
248
|
before,
|
|
@@ -296,7 +296,7 @@ export class VirtualKeyService {
|
|
|
296
296
|
organizationId: input.organizationId,
|
|
297
297
|
projectId: input.projectId,
|
|
298
298
|
actorUserId: input.actorUserId,
|
|
299
|
-
action: "
|
|
299
|
+
action: "gateway.virtual_key.rotated",
|
|
300
300
|
targetKind: "virtual_key",
|
|
301
301
|
targetId: vk.id,
|
|
302
302
|
before,
|
|
@@ -336,7 +336,7 @@ export class VirtualKeyService {
|
|
|
336
336
|
organizationId: input.organizationId,
|
|
337
337
|
projectId: input.projectId,
|
|
338
338
|
actorUserId: input.actorUserId,
|
|
339
|
-
action: "
|
|
339
|
+
action: "gateway.virtual_key.revoked",
|
|
340
340
|
targetKind: "virtual_key",
|
|
341
341
|
targetId: vk.id,
|
|
342
342
|
before,
|
|
@@ -1,10 +1,24 @@
|
|
|
1
1
|
import { describe, it, expect } from "vitest";
|
|
2
|
-
import { extractCredentials } from "../auth-middleware";
|
|
2
|
+
import { extractCredentials, collectAuthDiagnostics } from "../auth-middleware";
|
|
3
3
|
|
|
4
4
|
function mockGetHeader(headers: Record<string, string>) {
|
|
5
5
|
return (name: string) => headers[name.toLowerCase()] ?? headers[name];
|
|
6
6
|
}
|
|
7
7
|
|
|
8
|
+
function mockHonoCtx(opts: {
|
|
9
|
+
path?: string;
|
|
10
|
+
method?: string;
|
|
11
|
+
headers?: Record<string, string>;
|
|
12
|
+
}) {
|
|
13
|
+
return {
|
|
14
|
+
req: {
|
|
15
|
+
path: opts.path ?? "/api/scenario-events",
|
|
16
|
+
method: opts.method ?? "POST",
|
|
17
|
+
header: mockGetHeader(opts.headers ?? {}),
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
8
22
|
describe("extractCredentials", () => {
|
|
9
23
|
describe("when using Basic Auth", () => {
|
|
10
24
|
it("extracts projectId and token from base64-encoded header", () => {
|
|
@@ -31,13 +45,13 @@ describe("extractCredentials", () => {
|
|
|
31
45
|
});
|
|
32
46
|
});
|
|
33
47
|
|
|
34
|
-
it("returns null for missing colon in decoded value", () => {
|
|
48
|
+
it("returns null for missing colon in decoded value (no fallback)", () => {
|
|
35
49
|
const encoded = Buffer.from("no-colon-here").toString("base64");
|
|
36
50
|
const c = mockGetHeader({ authorization: `Basic ${encoded}` });
|
|
37
51
|
expect(extractCredentials(c)).toBeNull();
|
|
38
52
|
});
|
|
39
53
|
|
|
40
|
-
it("returns null for empty projectId or token", () => {
|
|
54
|
+
it("returns null for empty projectId or token (no fallback)", () => {
|
|
41
55
|
const encoded1 = Buffer.from(":token").toString("base64");
|
|
42
56
|
const c1 = mockGetHeader({ authorization: `Basic ${encoded1}` });
|
|
43
57
|
expect(extractCredentials(c1)).toBeNull();
|
|
@@ -46,6 +60,44 @@ describe("extractCredentials", () => {
|
|
|
46
60
|
const c2 = mockGetHeader({ authorization: `Basic ${encoded2}` });
|
|
47
61
|
expect(extractCredentials(c2)).toBeNull();
|
|
48
62
|
});
|
|
63
|
+
|
|
64
|
+
it("falls back to X-Auth-Token when Basic auth is malformed (no colon)", () => {
|
|
65
|
+
// A corporate proxy may add Authorization: Basic <some-base64> for its
|
|
66
|
+
// own upstream auth. That MUST NOT poison the customer's legitimate
|
|
67
|
+
// X-Auth-Token credential — fall through, not return null.
|
|
68
|
+
const badBasic = Buffer.from("internal-proxy-token").toString("base64");
|
|
69
|
+
const c = mockGetHeader({
|
|
70
|
+
authorization: `Basic ${badBasic}`,
|
|
71
|
+
"x-auth-token": "sk-lw-customer-key",
|
|
72
|
+
});
|
|
73
|
+
expect(extractCredentials(c)).toEqual({
|
|
74
|
+
token: "sk-lw-customer-key",
|
|
75
|
+
projectId: null,
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("falls back to X-Auth-Token when Basic auth has empty token", () => {
|
|
80
|
+
const emptyToken = Buffer.from("projectId:").toString("base64");
|
|
81
|
+
const c = mockGetHeader({
|
|
82
|
+
authorization: `Basic ${emptyToken}`,
|
|
83
|
+
"x-auth-token": "sk-lw-customer-key",
|
|
84
|
+
});
|
|
85
|
+
expect(extractCredentials(c)).toEqual({
|
|
86
|
+
token: "sk-lw-customer-key",
|
|
87
|
+
projectId: null,
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("falls back to X-Auth-Token when Basic auth is undecodable base64", () => {
|
|
92
|
+
const c = mockGetHeader({
|
|
93
|
+
authorization: "Basic !@#$%^",
|
|
94
|
+
"x-auth-token": "sk-lw-customer-key",
|
|
95
|
+
});
|
|
96
|
+
expect(extractCredentials(c)).toEqual({
|
|
97
|
+
token: "sk-lw-customer-key",
|
|
98
|
+
projectId: null,
|
|
99
|
+
});
|
|
100
|
+
});
|
|
49
101
|
});
|
|
50
102
|
|
|
51
103
|
describe("when using Bearer token", () => {
|
|
@@ -81,6 +133,28 @@ describe("extractCredentials", () => {
|
|
|
81
133
|
projectId: null,
|
|
82
134
|
});
|
|
83
135
|
});
|
|
136
|
+
|
|
137
|
+
it("falls back to X-Auth-Token when Bearer is empty", () => {
|
|
138
|
+
const c = mockGetHeader({
|
|
139
|
+
authorization: "Bearer ",
|
|
140
|
+
"x-auth-token": "sk-lw-customer-key",
|
|
141
|
+
});
|
|
142
|
+
expect(extractCredentials(c)).toEqual({
|
|
143
|
+
token: "sk-lw-customer-key",
|
|
144
|
+
projectId: null,
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("falls back to X-Auth-Token when Bearer is whitespace-only", () => {
|
|
149
|
+
const c = mockGetHeader({
|
|
150
|
+
authorization: "Bearer ",
|
|
151
|
+
"x-auth-token": "sk-lw-customer-key",
|
|
152
|
+
});
|
|
153
|
+
expect(extractCredentials(c)).toEqual({
|
|
154
|
+
token: "sk-lw-customer-key",
|
|
155
|
+
projectId: null,
|
|
156
|
+
});
|
|
157
|
+
});
|
|
84
158
|
});
|
|
85
159
|
|
|
86
160
|
describe("when using X-Auth-Token header", () => {
|
|
@@ -129,3 +203,64 @@ describe("extractCredentials", () => {
|
|
|
129
203
|
});
|
|
130
204
|
});
|
|
131
205
|
});
|
|
206
|
+
|
|
207
|
+
describe("collectAuthDiagnostics", () => {
|
|
208
|
+
it("captures the userAgent, traceparent, X-Forwarded-For and request path", () => {
|
|
209
|
+
const c = mockHonoCtx({
|
|
210
|
+
path: "/api/scenario-events",
|
|
211
|
+
method: "POST",
|
|
212
|
+
headers: {
|
|
213
|
+
"user-agent": "python-httpx/0.28.1",
|
|
214
|
+
traceparent: "00-1234abcd-5678efgh-01",
|
|
215
|
+
"x-forwarded-for": "203.0.113.42, 10.0.0.1",
|
|
216
|
+
"x-auth-token": "sk-lw-abc",
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
expect(collectAuthDiagnostics(c)).toEqual({
|
|
220
|
+
path: "/api/scenario-events",
|
|
221
|
+
method: "POST",
|
|
222
|
+
userAgent: "python-httpx/0.28.1",
|
|
223
|
+
traceparent: "00-1234abcd-5678efgh-01",
|
|
224
|
+
forwardedFor: "203.0.113.42, 10.0.0.1",
|
|
225
|
+
hasEmptyAuthToken: false,
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("falls back to X-Real-IP when X-Forwarded-For is absent", () => {
|
|
230
|
+
const c = mockHonoCtx({ headers: { "x-real-ip": "192.0.2.5" } });
|
|
231
|
+
expect(collectAuthDiagnostics(c).forwardedFor).toBe("192.0.2.5");
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("flags hasEmptyAuthToken when the header was sent but empty", () => {
|
|
235
|
+
const c = mockHonoCtx({ headers: { "x-auth-token": "" } });
|
|
236
|
+
const diag = collectAuthDiagnostics(c);
|
|
237
|
+
expect(diag.hasEmptyAuthToken).toBe(true);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("does NOT flag hasEmptyAuthToken when the header is absent entirely", () => {
|
|
241
|
+
const c = mockHonoCtx({ headers: {} });
|
|
242
|
+
const diag = collectAuthDiagnostics(c);
|
|
243
|
+
expect(diag.hasEmptyAuthToken).toBe(false);
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it("returns null for missing optional headers (no exceptions)", () => {
|
|
247
|
+
const c = mockHonoCtx({ headers: {} });
|
|
248
|
+
const diag = collectAuthDiagnostics(c);
|
|
249
|
+
expect(diag.userAgent).toBeNull();
|
|
250
|
+
expect(diag.traceparent).toBeNull();
|
|
251
|
+
expect(diag.forwardedFor).toBeNull();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("never includes a raw token value", () => {
|
|
255
|
+
const c = mockHonoCtx({
|
|
256
|
+
headers: {
|
|
257
|
+
"x-auth-token": "sk-lw-SUPER-SECRET-VALUE",
|
|
258
|
+
authorization: "Bearer pat-lw-ANOTHER-SECRET",
|
|
259
|
+
},
|
|
260
|
+
});
|
|
261
|
+
const diag = collectAuthDiagnostics(c);
|
|
262
|
+
const serialized = JSON.stringify(diag);
|
|
263
|
+
expect(serialized).not.toContain("SUPER-SECRET-VALUE");
|
|
264
|
+
expect(serialized).not.toContain("ANOTHER-SECRET");
|
|
265
|
+
});
|
|
266
|
+
});
|
|
@@ -47,23 +47,29 @@ function extractCredentials(
|
|
|
47
47
|
try {
|
|
48
48
|
const decoded = Buffer.from(encoded, "base64").toString("utf-8");
|
|
49
49
|
const colonIndex = decoded.indexOf(":");
|
|
50
|
-
if (colonIndex
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
50
|
+
if (colonIndex !== -1) {
|
|
51
|
+
const projectId = decoded.slice(0, colonIndex);
|
|
52
|
+
const token = decoded.slice(colonIndex + 1);
|
|
53
|
+
if (projectId && token) {
|
|
54
|
+
return { token, projectId };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// Fall through to X-Auth-Token below: a malformed Basic header (e.g.
|
|
58
|
+
// injected by a corporate proxy for upstream auth) must not poison
|
|
59
|
+
// the customer's legitimate X-Auth-Token credential.
|
|
57
60
|
} catch {
|
|
58
|
-
|
|
61
|
+
// Same fallthrough on undecodable base64.
|
|
59
62
|
}
|
|
60
63
|
}
|
|
61
64
|
|
|
62
65
|
// Priority 2: Bearer token
|
|
63
66
|
if (authHeader?.toLowerCase().startsWith("bearer ")) {
|
|
64
|
-
const token = authHeader.slice(7);
|
|
65
|
-
if (
|
|
66
|
-
|
|
67
|
+
const token = authHeader.slice(7).trim();
|
|
68
|
+
if (token) {
|
|
69
|
+
return { token, projectId: xProjectId ?? null };
|
|
70
|
+
}
|
|
71
|
+
// Empty Bearer also falls through to X-Auth-Token — same proxy-injection
|
|
72
|
+
// hardening as Basic above.
|
|
67
73
|
}
|
|
68
74
|
|
|
69
75
|
// Priority 3: X-Auth-Token header (legacy)
|
|
@@ -100,8 +106,19 @@ export function createUnifiedAuthMiddleware({
|
|
|
100
106
|
|
|
101
107
|
return async (c, next) => {
|
|
102
108
|
const credentials = extractCredentials((name) => c.req.header(name));
|
|
109
|
+
// Diagnostic context for auth failures — lets on-call attribute a 401 to
|
|
110
|
+
// a specific customer/SDK without needing the customer to reproduce with
|
|
111
|
+
// debug logs. Read once and reuse across both failure paths so values
|
|
112
|
+
// are consistent. No raw token / body content is included.
|
|
113
|
+
const diag = collectAuthDiagnostics(c);
|
|
103
114
|
|
|
104
115
|
if (!credentials) {
|
|
116
|
+
logger.warn(
|
|
117
|
+
diag,
|
|
118
|
+
diag.hasEmptyAuthToken
|
|
119
|
+
? "Authentication failed: X-Auth-Token sent but empty"
|
|
120
|
+
: "Authentication failed: no auth header present",
|
|
121
|
+
);
|
|
105
122
|
return c.json(
|
|
106
123
|
{
|
|
107
124
|
error: "Unauthorized",
|
|
@@ -121,9 +138,8 @@ export function createUnifiedAuthMiddleware({
|
|
|
121
138
|
} catch (error) {
|
|
122
139
|
logger.error(
|
|
123
140
|
{
|
|
141
|
+
...diag,
|
|
124
142
|
error,
|
|
125
|
-
path: c.req.path,
|
|
126
|
-
method: c.req.method,
|
|
127
143
|
},
|
|
128
144
|
"Database error during authentication",
|
|
129
145
|
);
|
|
@@ -140,6 +156,7 @@ export function createUnifiedAuthMiddleware({
|
|
|
140
156
|
if (!resolved) {
|
|
141
157
|
logger.warn(
|
|
142
158
|
{
|
|
159
|
+
...diag,
|
|
143
160
|
hasToken: true,
|
|
144
161
|
tokenType: credentials.token.startsWith("pat-lw-")
|
|
145
162
|
? "pat"
|
|
@@ -181,6 +198,44 @@ export function createUnifiedAuthMiddleware({
|
|
|
181
198
|
|
|
182
199
|
export { extractCredentials };
|
|
183
200
|
|
|
201
|
+
/**
|
|
202
|
+
* Diagnostic fields safe to emit on auth failure. Captures enough request
|
|
203
|
+
* fingerprint to attribute 401s to a specific customer/SDK in CloudWatch
|
|
204
|
+
* without leaking credentials or request bodies. `traceparent` lets us join
|
|
205
|
+
* the failed POST to the customer's downstream OTel trace, which usually
|
|
206
|
+
* carries identifying metadata even when the auth header path doesn't.
|
|
207
|
+
*
|
|
208
|
+
* `hasEmptyAuthToken` distinguishes "X-Auth-Token sent as an empty string"
|
|
209
|
+
* (typically a customer-side env-var misconfig) from "no auth header at all"
|
|
210
|
+
* (typically a misconfigured SDK or unauthenticated probe). Both produce the
|
|
211
|
+
* same 401 today — the log line tells them apart.
|
|
212
|
+
*/
|
|
213
|
+
export type AuthDiagnostics = {
|
|
214
|
+
path: string;
|
|
215
|
+
method: string;
|
|
216
|
+
userAgent: string | null;
|
|
217
|
+
traceparent: string | null;
|
|
218
|
+
forwardedFor: string | null;
|
|
219
|
+
hasEmptyAuthToken: boolean;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
export function collectAuthDiagnostics(c: {
|
|
223
|
+
req: { path: string; method: string; header: (name: string) => string | undefined };
|
|
224
|
+
}): AuthDiagnostics {
|
|
225
|
+
const get = (name: string) => c.req.header(name) ?? null;
|
|
226
|
+
const xAuthToken = c.req.header("x-auth-token");
|
|
227
|
+
return {
|
|
228
|
+
path: c.req.path,
|
|
229
|
+
method: c.req.method,
|
|
230
|
+
userAgent: get("user-agent"),
|
|
231
|
+
traceparent: get("traceparent"),
|
|
232
|
+
forwardedFor: get("x-forwarded-for") ?? get("x-real-ip"),
|
|
233
|
+
// Sent-but-empty is distinct from absent (SDK with a misconfigured
|
|
234
|
+
// empty api_key still serializes the header).
|
|
235
|
+
hasEmptyAuthToken: xAuthToken !== undefined && xAuthToken === "",
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
184
239
|
/**
|
|
185
240
|
* Enforces the PAT permission ceiling for an already-resolved token.
|
|
186
241
|
*
|