@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
|
@@ -1334,7 +1334,7 @@ export const organizationRouter = createTRPCRouter({
|
|
|
1334
1334
|
targetId: z.string().optional(),
|
|
1335
1335
|
}),
|
|
1336
1336
|
)
|
|
1337
|
-
.use(checkOrganizationPermission("
|
|
1337
|
+
.use(checkOrganizationPermission("auditLog:view"))
|
|
1338
1338
|
.query(async ({ ctx, input }) => {
|
|
1339
1339
|
await assertEnterprisePlan({
|
|
1340
1340
|
organizationId: input.organizationId,
|
package/langwatch/src/server/app-layer/organizations/repositories/organization.prisma.repository.ts
CHANGED
|
@@ -4,7 +4,6 @@ import {
|
|
|
4
4
|
RoleBindingScopeType,
|
|
5
5
|
TeamUserRole,
|
|
6
6
|
type Currency,
|
|
7
|
-
type GatewayAuditAction,
|
|
8
7
|
type Prisma,
|
|
9
8
|
type PrismaClient,
|
|
10
9
|
} from "@prisma/client";
|
|
@@ -925,84 +924,45 @@ export class PrismaOrganizationRepository implements OrganizationRepository {
|
|
|
925
924
|
andConditions.push({ createdAt: dateFilter });
|
|
926
925
|
}
|
|
927
926
|
|
|
927
|
+
// Gateway-resource deep-link filter (`/settings/audit-log?targetKind=…
|
|
928
|
+
// &targetId=…`). Both columns live on `AuditLog` post-consolidation —
|
|
929
|
+
// see migration 20260425000000_consolidate_gateway_audit_into_audit_log.
|
|
930
|
+
// targetId is only honored when paired with targetKind so a stray
|
|
931
|
+
// `?targetId=` from a typo'd URL cannot match across kinds.
|
|
932
|
+
if (filters.targetKind) {
|
|
933
|
+
andConditions.push({ targetKind: filters.targetKind });
|
|
934
|
+
if (filters.targetId) {
|
|
935
|
+
andConditions.push({ targetId: filters.targetId });
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
928
939
|
if (andConditions.length > 1) {
|
|
929
940
|
where.AND = andConditions;
|
|
930
941
|
} else {
|
|
931
942
|
Object.assign(where, andConditions[0]);
|
|
932
943
|
}
|
|
933
944
|
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
945
|
+
const [totalCount, rows] = await Promise.all([
|
|
946
|
+
this.prisma.auditLog.count({ where }),
|
|
947
|
+
this.prisma.auditLog.findMany({
|
|
948
|
+
where,
|
|
949
|
+
skip: pageOffset,
|
|
950
|
+
take: pageSize,
|
|
951
|
+
orderBy: { createdAt: "desc" },
|
|
952
|
+
}),
|
|
953
|
+
]);
|
|
942
954
|
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
...(userId ? { actorUserId: userId } : {}),
|
|
947
|
-
...(targetKind ? { targetKind } : {}),
|
|
948
|
-
...(targetId ? { targetId } : {}),
|
|
949
|
-
...(action
|
|
950
|
-
? {
|
|
951
|
-
action: {
|
|
952
|
-
// Prisma enum filter needs exact-match list; fall through to
|
|
953
|
-
// a client-side filter if the caller sent a partial action
|
|
954
|
-
// substring. Platform-side uses `contains`; gateway-side
|
|
955
|
-
// enums are strict, so accept only a full-enum match here.
|
|
956
|
-
equals: action as GatewayAuditAction,
|
|
957
|
-
},
|
|
958
|
-
}
|
|
959
|
-
: {}),
|
|
960
|
-
...(startDate !== undefined || endDate !== undefined
|
|
961
|
-
? {
|
|
962
|
-
createdAt: {
|
|
963
|
-
...(startDate !== undefined ? { gte: new Date(startDate) } : {}),
|
|
964
|
-
...(endDate !== undefined ? { lte: new Date(endDate) } : {}),
|
|
965
|
-
},
|
|
966
|
-
}
|
|
967
|
-
: {}),
|
|
968
|
-
};
|
|
969
|
-
|
|
970
|
-
const [platformTotal, gatewayTotal, platformRows, gatewayRows] =
|
|
971
|
-
await Promise.all([
|
|
972
|
-
skipPlatform
|
|
973
|
-
? Promise.resolve(0)
|
|
974
|
-
: this.prisma.auditLog.count({ where }),
|
|
975
|
-
this.prisma.gatewayAuditLog.count({ where: gatewayWhere }),
|
|
976
|
-
skipPlatform
|
|
977
|
-
? Promise.resolve([])
|
|
978
|
-
: this.prisma.auditLog.findMany({
|
|
979
|
-
where,
|
|
980
|
-
// Over-fetch from each source so the post-merge slice is
|
|
981
|
-
// stable at small page sizes. Cap the over-fetch to 2×
|
|
982
|
-
// pageSize per source to bound the memory cost.
|
|
983
|
-
take: pageSize + pageOffset,
|
|
984
|
-
orderBy: { createdAt: "desc" },
|
|
985
|
-
}),
|
|
986
|
-
this.prisma.gatewayAuditLog.findMany({
|
|
987
|
-
where: gatewayWhere,
|
|
988
|
-
take: pageSize + pageOffset,
|
|
989
|
-
orderBy: { createdAt: "desc" },
|
|
990
|
-
}),
|
|
991
|
-
]);
|
|
992
|
-
|
|
993
|
-
// Gather resolver inputs from both sources before the batched fetch.
|
|
955
|
+
// userId is nullable post-consolidation (system-actor writes) — filter
|
|
956
|
+
// null out before passing to the Prisma `IN` predicate, which rejects
|
|
957
|
+
// null array members at runtime.
|
|
994
958
|
const userIds = [
|
|
995
|
-
...new Set(
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
]),
|
|
959
|
+
...new Set(
|
|
960
|
+
rows.map((r) => r.userId).filter((id): id is string => !!id),
|
|
961
|
+
),
|
|
999
962
|
];
|
|
1000
963
|
const projectIds = [
|
|
1001
964
|
...new Set(
|
|
1002
|
-
|
|
1003
|
-
...platformRows.map((r) => r.projectId),
|
|
1004
|
-
...gatewayRows.map((r) => r.projectId),
|
|
1005
|
-
].filter((id): id is string => !!id),
|
|
965
|
+
rows.map((r) => r.projectId).filter((id): id is string => !!id),
|
|
1006
966
|
),
|
|
1007
967
|
];
|
|
1008
968
|
|
|
@@ -1019,57 +979,35 @@ export class PrismaOrganizationRepository implements OrganizationRepository {
|
|
|
1019
979
|
const userMap = new Map(users.map((u) => [u.id, u]));
|
|
1020
980
|
const projectMap = new Map(projects.map((p) => [p.id, p]));
|
|
1021
981
|
|
|
1022
|
-
const
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
userAgent: null,
|
|
1053
|
-
error: null,
|
|
1054
|
-
args: { before: log.before, after: log.after },
|
|
1055
|
-
user: log.actorUserId ? (userMap.get(log.actorUserId) ?? null) : null,
|
|
1056
|
-
project: log.projectId ? (projectMap.get(log.projectId) ?? null) : null,
|
|
1057
|
-
source: "gateway" as const,
|
|
1058
|
-
targetKind: log.targetKind,
|
|
1059
|
-
targetId: log.targetId,
|
|
1060
|
-
before: log.before,
|
|
1061
|
-
after: log.after,
|
|
1062
|
-
}));
|
|
1063
|
-
|
|
1064
|
-
// Merge + sort by createdAt DESC, then apply the requested page slice.
|
|
1065
|
-
const merged = [...platformEnriched, ...gatewayEnriched].sort(
|
|
1066
|
-
(a, b) => b.createdAt.getTime() - a.createdAt.getTime(),
|
|
1067
|
-
);
|
|
1068
|
-
const paginated = merged.slice(pageOffset, pageOffset + pageSize);
|
|
1069
|
-
|
|
1070
|
-
return {
|
|
1071
|
-
auditLogs: paginated,
|
|
1072
|
-
totalCount: platformTotal + gatewayTotal,
|
|
1073
|
-
};
|
|
982
|
+
const auditLogs: EnrichedAuditLog[] = rows.map((log) => {
|
|
983
|
+
// Gateway-shape rows are emitted under the `gateway.<resource>.<verb>`
|
|
984
|
+
// dotted naming convention; the `gateway.` prefix is the load-bearing
|
|
985
|
+
// discriminator (also documented for SIEM scoping via LIKE 'gateway.%').
|
|
986
|
+
// Presence of targetKind alone is not a safe signal — platform features
|
|
987
|
+
// could in principle add their own target tracking later.
|
|
988
|
+
const isGateway = log.action.startsWith("gateway.");
|
|
989
|
+
return {
|
|
990
|
+
id: log.id,
|
|
991
|
+
createdAt: log.createdAt,
|
|
992
|
+
userId: log.userId,
|
|
993
|
+
organizationId: log.organizationId,
|
|
994
|
+
projectId: log.projectId,
|
|
995
|
+
action: log.action,
|
|
996
|
+
payload: isGateway ? (log.after ?? log.before ?? null) : log.args,
|
|
997
|
+
ipAddress: log.ipAddress,
|
|
998
|
+
userAgent: log.userAgent,
|
|
999
|
+
error: log.error,
|
|
1000
|
+
args: isGateway ? { before: log.before, after: log.after } : log.args,
|
|
1001
|
+
user: log.userId ? (userMap.get(log.userId) ?? null) : null,
|
|
1002
|
+
project: log.projectId ? (projectMap.get(log.projectId) ?? null) : null,
|
|
1003
|
+
source: isGateway ? "gateway" : "platform",
|
|
1004
|
+
targetKind: log.targetKind,
|
|
1005
|
+
targetId: log.targetId,
|
|
1006
|
+
before: log.before,
|
|
1007
|
+
after: log.after,
|
|
1008
|
+
};
|
|
1009
|
+
});
|
|
1010
|
+
|
|
1011
|
+
return { auditLogs, totalCount };
|
|
1074
1012
|
}
|
|
1075
1013
|
}
|
package/langwatch/src/server/app-layer/organizations/repositories/organization.repository.ts
CHANGED
|
@@ -130,8 +130,8 @@ export interface AuditLogFilters {
|
|
|
130
130
|
endDate?: number;
|
|
131
131
|
/**
|
|
132
132
|
* Filter by gateway-resource kind, e.g. "virtual_key" / "budget" /
|
|
133
|
-
* "provider_binding" / "cache_rule". Only matches rows
|
|
134
|
-
*
|
|
133
|
+
* "provider_binding" / "cache_rule". Only matches rows where the gateway
|
|
134
|
+
* services populated `targetKind` — platform-shape rows have null here.
|
|
135
135
|
*/
|
|
136
136
|
targetKind?: string;
|
|
137
137
|
/**
|
|
@@ -143,13 +143,15 @@ export interface AuditLogFilters {
|
|
|
143
143
|
|
|
144
144
|
/**
|
|
145
145
|
* Enriched audit log entry with resolved user and project data.
|
|
146
|
-
*
|
|
147
|
-
*
|
|
146
|
+
* Backed by a single `AuditLog` table that stores both gateway-shape
|
|
147
|
+
* (targetKind + before/after diff) and platform-shape (args + metadata)
|
|
148
|
+
* rows. The `source` field is computed from the presence of `targetKind`.
|
|
148
149
|
*/
|
|
149
150
|
export interface EnrichedAuditLog {
|
|
150
151
|
id: string;
|
|
151
152
|
createdAt: Date;
|
|
152
|
-
|
|
153
|
+
/** Nullable to support system-actor writes (background jobs, migrations). */
|
|
154
|
+
userId: string | null;
|
|
153
155
|
organizationId: string | null;
|
|
154
156
|
projectId: string | null;
|
|
155
157
|
action: string;
|
|
@@ -160,12 +162,7 @@ export interface EnrichedAuditLog {
|
|
|
160
162
|
args: unknown;
|
|
161
163
|
user: { id: string; name: string | null; email: string | null } | null;
|
|
162
164
|
project: { id: string; name: string } | null;
|
|
163
|
-
/**
|
|
164
|
-
* Which system wrote this audit row. Platform rows come from
|
|
165
|
-
* `AuditLog` (org-level actions, evaluator runs, etc); gateway rows
|
|
166
|
-
* come from `GatewayAuditLog` (VK / budget / provider / cache-rule
|
|
167
|
-
* mutations).
|
|
168
|
-
*/
|
|
165
|
+
/** Computed: gateway = `targetKind` populated, platform = otherwise. */
|
|
169
166
|
source: "platform" | "gateway";
|
|
170
167
|
/** Gateway resource kind — only set when source="gateway". */
|
|
171
168
|
targetKind: string | null;
|
|
@@ -323,7 +323,11 @@ export class EvaluatorService {
|
|
|
323
323
|
limit: 100,
|
|
324
324
|
});
|
|
325
325
|
|
|
326
|
-
const userIds = [
|
|
326
|
+
const userIds = [
|
|
327
|
+
...new Set(
|
|
328
|
+
logs.map((l) => l.userId).filter((id): id is string => !!id),
|
|
329
|
+
),
|
|
330
|
+
];
|
|
327
331
|
const users = await this.repository.findUsersByIds(userIds);
|
|
328
332
|
const usersById = Object.fromEntries(users.map((u) => [u.id, u]));
|
|
329
333
|
|
|
@@ -332,7 +336,7 @@ export class EvaluatorService {
|
|
|
332
336
|
action: log.action,
|
|
333
337
|
createdAt: log.createdAt,
|
|
334
338
|
args: log.args,
|
|
335
|
-
user: usersById[log.userId] ?? null,
|
|
339
|
+
user: log.userId ? (usersById[log.userId] ?? null) : null,
|
|
336
340
|
}));
|
|
337
341
|
}
|
|
338
342
|
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment node
|
|
3
|
+
*
|
|
4
|
+
* Integration coverage for the GatewayAuditLog → AuditLog consolidation.
|
|
5
|
+
*
|
|
6
|
+
* Hits real PG (testcontainers) — NO MOCKS. Validates that:
|
|
7
|
+
* 1. `GatewayAuditAdapter.append` writes rows to the platform
|
|
8
|
+
* `AuditLog` table with the gateway shape (targetKind / targetId /
|
|
9
|
+
* before / after) — the adapter's whole purpose.
|
|
10
|
+
* 2. The unified `getAuditLogs` query returns those rows with
|
|
11
|
+
* `source = "gateway"`.
|
|
12
|
+
* 3. Filtering by `targetKind` / `targetId` returns only rows for that
|
|
13
|
+
* resource (deep-link path from VK / Budget detail pages).
|
|
14
|
+
* 4. The `GatewayAuditLog` table no longer exists post-migration —
|
|
15
|
+
* `prisma.gatewayAuditLog` is undefined at runtime. (Live PG probe
|
|
16
|
+
* via `$queryRaw` is blocked by multitenancy middleware; client-
|
|
17
|
+
* shape check is the practical regression guard since the client
|
|
18
|
+
* is generated from the same schema.prisma that gates the migration.)
|
|
19
|
+
*
|
|
20
|
+
* The adapter is exercised directly rather than through VirtualKeyService —
|
|
21
|
+
* the service has its own unit tests for the upstream `auditLog.append` call;
|
|
22
|
+
* this suite is about proving the *table* under it changed.
|
|
23
|
+
*
|
|
24
|
+
* Spec: specs/audit-log/audit-log.feature
|
|
25
|
+
* Migration: prisma/migrations/20260425000000_consolidate_gateway_audit_into_audit_log
|
|
26
|
+
*/
|
|
27
|
+
import { nanoid } from "nanoid";
|
|
28
|
+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
29
|
+
|
|
30
|
+
import { prisma } from "~/server/db";
|
|
31
|
+
import { PrismaOrganizationRepository } from "~/server/app-layer/organizations/repositories/organization.prisma.repository";
|
|
32
|
+
import {
|
|
33
|
+
startTestContainers,
|
|
34
|
+
stopTestContainers,
|
|
35
|
+
} from "~/server/event-sourcing/__tests__/integration/testContainers";
|
|
36
|
+
import { GatewayAuditAdapter } from "../auditLog.repository";
|
|
37
|
+
|
|
38
|
+
const suffix = nanoid(8);
|
|
39
|
+
const ORG_ID = `org-audit-${suffix}`;
|
|
40
|
+
const TEAM_ID = `team-audit-${suffix}`;
|
|
41
|
+
const PROJECT_ID = `proj-audit-${suffix}`;
|
|
42
|
+
const ACTOR_USER_ID = `usr-audit-${suffix}`;
|
|
43
|
+
const VK_ID = `vk-audit-${suffix}`;
|
|
44
|
+
const BUDGET_ID = `bdg-audit-${suffix}`;
|
|
45
|
+
|
|
46
|
+
describe("AuditLog consolidation — gateway writes land in platform AuditLog", () => {
|
|
47
|
+
const organizations = new PrismaOrganizationRepository(prisma);
|
|
48
|
+
const auditLog = new GatewayAuditAdapter(prisma);
|
|
49
|
+
|
|
50
|
+
beforeAll(async () => {
|
|
51
|
+
await startTestContainers();
|
|
52
|
+
|
|
53
|
+
await prisma.organization.create({
|
|
54
|
+
data: { id: ORG_ID, name: `Audit Org ${suffix}`, slug: `audit-${suffix}` },
|
|
55
|
+
});
|
|
56
|
+
await prisma.team.create({
|
|
57
|
+
data: {
|
|
58
|
+
id: TEAM_ID,
|
|
59
|
+
name: `Audit Team ${suffix}`,
|
|
60
|
+
slug: `audit-team-${suffix}`,
|
|
61
|
+
organizationId: ORG_ID,
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
await prisma.project.create({
|
|
65
|
+
data: {
|
|
66
|
+
id: PROJECT_ID,
|
|
67
|
+
name: `Audit Project ${suffix}`,
|
|
68
|
+
slug: `audit-proj-${suffix}`,
|
|
69
|
+
teamId: TEAM_ID,
|
|
70
|
+
language: "en",
|
|
71
|
+
framework: "openai",
|
|
72
|
+
apiKey: `key-${suffix}`,
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
await prisma.user.create({
|
|
76
|
+
data: {
|
|
77
|
+
id: ACTOR_USER_ID,
|
|
78
|
+
email: `${suffix}@audit.local`,
|
|
79
|
+
name: "Audit Actor",
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
await prisma.organizationUser.create({
|
|
83
|
+
data: { organizationId: ORG_ID, userId: ACTOR_USER_ID, role: "ADMIN" },
|
|
84
|
+
});
|
|
85
|
+
}, 60_000);
|
|
86
|
+
|
|
87
|
+
afterAll(async () => {
|
|
88
|
+
await prisma.auditLog.deleteMany({ where: { organizationId: ORG_ID } });
|
|
89
|
+
await prisma.organizationUser.deleteMany({
|
|
90
|
+
where: { organizationId: ORG_ID, userId: ACTOR_USER_ID },
|
|
91
|
+
});
|
|
92
|
+
await prisma.user.deleteMany({ where: { id: ACTOR_USER_ID } });
|
|
93
|
+
await prisma.project.deleteMany({ where: { id: PROJECT_ID } });
|
|
94
|
+
await prisma.team.deleteMany({ where: { id: TEAM_ID } });
|
|
95
|
+
await prisma.organization.deleteMany({ where: { id: ORG_ID } });
|
|
96
|
+
await stopTestContainers();
|
|
97
|
+
}, 60_000);
|
|
98
|
+
|
|
99
|
+
describe("when GatewayAuditLog table is dropped", () => {
|
|
100
|
+
it("drops gatewayAuditLog from the prisma client", () => {
|
|
101
|
+
// Post-consolidation `prisma.gatewayAuditLog` is undefined — would
|
|
102
|
+
// throw at runtime. Since the Prisma client is generated from
|
|
103
|
+
// schema.prisma at build time, this also confirms the model was
|
|
104
|
+
// removed from the schema definition (which is what gates the
|
|
105
|
+
// SQL migration that drops the table). A live PG `to_regclass`
|
|
106
|
+
// probe would be stronger but is blocked by our multitenancy
|
|
107
|
+
// middleware which rejects `$queryRaw` calls — see
|
|
108
|
+
// `src/utils/dbMultiTenancyProtection.ts`.
|
|
109
|
+
expect((prisma as unknown as Record<string, unknown>).gatewayAuditLog)
|
|
110
|
+
.toBeUndefined();
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
describe("when the gateway audit adapter writes a VK row", () => {
|
|
115
|
+
it("creates an AuditLog row in gateway shape (targetKind + before/after)", async () => {
|
|
116
|
+
const before = await prisma.auditLog.count({
|
|
117
|
+
where: { organizationId: ORG_ID, action: "gateway.virtual_key.created" },
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
await auditLog.append({
|
|
121
|
+
organizationId: ORG_ID,
|
|
122
|
+
projectId: PROJECT_ID,
|
|
123
|
+
actorUserId: ACTOR_USER_ID,
|
|
124
|
+
action: "gateway.virtual_key.created",
|
|
125
|
+
targetKind: "virtual_key",
|
|
126
|
+
targetId: VK_ID,
|
|
127
|
+
before: null,
|
|
128
|
+
after: { name: `audit-vk-${suffix}`, status: "active" },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const rows = await prisma.auditLog.findMany({
|
|
132
|
+
where: {
|
|
133
|
+
organizationId: ORG_ID,
|
|
134
|
+
targetKind: "virtual_key",
|
|
135
|
+
targetId: VK_ID,
|
|
136
|
+
action: "gateway.virtual_key.created",
|
|
137
|
+
},
|
|
138
|
+
orderBy: { createdAt: "desc" },
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
expect(rows).toHaveLength(1);
|
|
142
|
+
const row = rows[0]!;
|
|
143
|
+
expect(row.userId).toBe(ACTOR_USER_ID);
|
|
144
|
+
expect(row.organizationId).toBe(ORG_ID);
|
|
145
|
+
expect(row.projectId).toBe(PROJECT_ID);
|
|
146
|
+
expect(row.targetKind).toBe("virtual_key");
|
|
147
|
+
expect(row.targetId).toBe(VK_ID);
|
|
148
|
+
expect(row.before).toBeNull();
|
|
149
|
+
expect(row.after).not.toBeNull();
|
|
150
|
+
expect(row.after).toMatchObject({ status: "active" });
|
|
151
|
+
|
|
152
|
+
// Sanity: total gateway.virtual_key.created rows for this org went up by 1.
|
|
153
|
+
const after = await prisma.auditLog.count({
|
|
154
|
+
where: { organizationId: ORG_ID, action: "gateway.virtual_key.created" },
|
|
155
|
+
});
|
|
156
|
+
expect(after).toBe(before + 1);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("captures before/after diff on update events", async () => {
|
|
160
|
+
await auditLog.append({
|
|
161
|
+
organizationId: ORG_ID,
|
|
162
|
+
projectId: PROJECT_ID,
|
|
163
|
+
actorUserId: ACTOR_USER_ID,
|
|
164
|
+
action: "gateway.budget.updated",
|
|
165
|
+
targetKind: "budget",
|
|
166
|
+
targetId: BUDGET_ID,
|
|
167
|
+
before: { limitUsd: "500" },
|
|
168
|
+
after: { limitUsd: "1000" },
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const row = await prisma.auditLog.findFirst({
|
|
172
|
+
where: {
|
|
173
|
+
organizationId: ORG_ID,
|
|
174
|
+
targetKind: "budget",
|
|
175
|
+
targetId: BUDGET_ID,
|
|
176
|
+
action: "gateway.budget.updated",
|
|
177
|
+
},
|
|
178
|
+
orderBy: { createdAt: "desc" },
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
expect(row).not.toBeNull();
|
|
182
|
+
expect(row!.before).toMatchObject({ limitUsd: "500" });
|
|
183
|
+
expect(row!.after).toMatchObject({ limitUsd: "1000" });
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
describe("when getAuditLogs is queried for the org", () => {
|
|
188
|
+
it("returns gateway rows with source='gateway'", async () => {
|
|
189
|
+
const result = await organizations.getAuditLogs({
|
|
190
|
+
organizationId: ORG_ID,
|
|
191
|
+
pageOffset: 0,
|
|
192
|
+
pageSize: 25,
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
const gatewayRows = result.auditLogs.filter((r) => r.source === "gateway");
|
|
196
|
+
expect(gatewayRows.length).toBeGreaterThan(0);
|
|
197
|
+
|
|
198
|
+
const sample = gatewayRows[0]!;
|
|
199
|
+
expect(sample.targetKind).not.toBeNull();
|
|
200
|
+
expect(sample.targetId).not.toBeNull();
|
|
201
|
+
expect(sample.user).not.toBeNull();
|
|
202
|
+
expect(sample.user?.id).toBe(ACTOR_USER_ID);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("filters to gateway-only when targetKind is set (deep-link path)", async () => {
|
|
206
|
+
const result = await organizations.getAuditLogs({
|
|
207
|
+
organizationId: ORG_ID,
|
|
208
|
+
pageOffset: 0,
|
|
209
|
+
pageSize: 25,
|
|
210
|
+
targetKind: "virtual_key",
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
expect(result.auditLogs.length).toBeGreaterThan(0);
|
|
214
|
+
// Every returned row must be gateway-source — platform rows have null
|
|
215
|
+
// targetKind so they cannot match.
|
|
216
|
+
for (const row of result.auditLogs) {
|
|
217
|
+
expect(row.source).toBe("gateway");
|
|
218
|
+
expect(row.targetKind).toBe("virtual_key");
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it("filters to a specific resource when targetId is set", async () => {
|
|
223
|
+
const result = await organizations.getAuditLogs({
|
|
224
|
+
organizationId: ORG_ID,
|
|
225
|
+
pageOffset: 0,
|
|
226
|
+
pageSize: 25,
|
|
227
|
+
targetKind: "virtual_key",
|
|
228
|
+
targetId: VK_ID,
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
expect(result.auditLogs.length).toBeGreaterThan(0);
|
|
232
|
+
for (const row of result.auditLogs) {
|
|
233
|
+
expect(row.targetId).toBe(VK_ID);
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
});
|
|
@@ -6,12 +6,12 @@ function mockPrisma(gatewayCacheRule: Record<string, any>): any {
|
|
|
6
6
|
return {
|
|
7
7
|
gatewayCacheRule,
|
|
8
8
|
gatewayChangeEvent: { create: vi.fn(async () => ({ revision: 1n })) },
|
|
9
|
-
|
|
9
|
+
auditLog: { create: vi.fn(async () => undefined) },
|
|
10
10
|
$transaction: async (cb: (tx: any) => any) =>
|
|
11
11
|
cb({
|
|
12
12
|
gatewayCacheRule,
|
|
13
13
|
gatewayChangeEvent: { create: vi.fn(async () => ({ revision: 1n })) },
|
|
14
|
-
|
|
14
|
+
auditLog: { create: vi.fn(async () => undefined) },
|
|
15
15
|
}),
|
|
16
16
|
};
|
|
17
17
|
}
|
|
@@ -89,12 +89,12 @@ function mockPrisma(args: {
|
|
|
89
89
|
},
|
|
90
90
|
gatewayProviderCredential,
|
|
91
91
|
gatewayChangeEvent: { create: changeEventCreate },
|
|
92
|
-
|
|
92
|
+
auditLog: { create: auditCreate },
|
|
93
93
|
$transaction: async (fn: (tx: unknown) => Promise<unknown>) =>
|
|
94
94
|
fn({
|
|
95
95
|
gatewayProviderCredential,
|
|
96
96
|
gatewayChangeEvent: { create: changeEventCreate },
|
|
97
|
-
|
|
97
|
+
auditLog: { create: auditCreate },
|
|
98
98
|
}),
|
|
99
99
|
} as unknown as PrismaClient;
|
|
100
100
|
|
|
@@ -148,7 +148,7 @@ describe("GatewayProviderCredentialService.create", () => {
|
|
|
148
148
|
expect(data.rotationPolicy).toBe("MANUAL");
|
|
149
149
|
});
|
|
150
150
|
|
|
151
|
-
it("emits a PROVIDER_BINDING_UPDATED change-event +
|
|
151
|
+
it("emits a PROVIDER_BINDING_UPDATED change-event + gateway.provider_binding.created audit entry", async () => {
|
|
152
152
|
const { prisma, changeEventCreate, auditCreate } = mockPrisma({
|
|
153
153
|
modelProvider: stubModelProvider(),
|
|
154
154
|
});
|
|
@@ -159,7 +159,7 @@ describe("GatewayProviderCredentialService.create", () => {
|
|
|
159
159
|
expect(changeEventCreate).toHaveBeenCalledOnce();
|
|
160
160
|
expect(auditCreate).toHaveBeenCalledOnce();
|
|
161
161
|
expect(auditCreate.mock.calls[0]?.[0].data.action).toBe(
|
|
162
|
-
"
|
|
162
|
+
"gateway.provider_binding.created",
|
|
163
163
|
);
|
|
164
164
|
});
|
|
165
165
|
});
|
|
@@ -229,7 +229,7 @@ describe("GatewayProviderCredentialService.update", () => {
|
|
|
229
229
|
|
|
230
230
|
describe("GatewayProviderCredentialService.disable", () => {
|
|
231
231
|
describe("when the binding exists", () => {
|
|
232
|
-
it("sets disabledAt + emits audit with
|
|
232
|
+
it("sets disabledAt + emits audit with gateway.provider_binding.updated action", async () => {
|
|
233
233
|
const existing = stubRow({ disabledAt: null });
|
|
234
234
|
const { prisma, updateArgs, auditCreate } = mockPrisma({ existing });
|
|
235
235
|
const sut = GatewayProviderCredentialService.create(prisma);
|
|
@@ -245,7 +245,7 @@ describe("GatewayProviderCredentialService.disable", () => {
|
|
|
245
245
|
Date,
|
|
246
246
|
);
|
|
247
247
|
expect(auditCreate.mock.calls[0]?.[0].data.action).toBe(
|
|
248
|
-
"
|
|
248
|
+
"gateway.provider_binding.updated",
|
|
249
249
|
);
|
|
250
250
|
});
|
|
251
251
|
});
|
|
@@ -9,7 +9,7 @@ beforeAll(() => {
|
|
|
9
9
|
process.env.LW_VIRTUAL_KEY_PEPPER ?? "unit-test-pepper-32-bytes-exactly!";
|
|
10
10
|
});
|
|
11
11
|
|
|
12
|
-
import {
|
|
12
|
+
import { GatewayAuditAdapter } from "../auditLog.repository";
|
|
13
13
|
import { ChangeEventRepository } from "../changeEvent.repository";
|
|
14
14
|
import { VirtualKeyService } from "../virtualKey.service";
|
|
15
15
|
import {
|
|
@@ -60,7 +60,7 @@ type Mocks = {
|
|
|
60
60
|
prisma: PrismaClient;
|
|
61
61
|
repository: VirtualKeyRepository;
|
|
62
62
|
changeEvents: ChangeEventRepository;
|
|
63
|
-
auditLog:
|
|
63
|
+
auditLog: GatewayAuditAdapter;
|
|
64
64
|
service: VirtualKeyService;
|
|
65
65
|
findByIdMock: ReturnType<typeof vi.fn>;
|
|
66
66
|
createMock: ReturnType<typeof vi.fn>;
|
|
@@ -110,7 +110,7 @@ function makeService(opts: {
|
|
|
110
110
|
} as unknown as VirtualKeyRepository;
|
|
111
111
|
|
|
112
112
|
const changeEvents = { append: changeAppend } as unknown as ChangeEventRepository;
|
|
113
|
-
const auditLog = { append: auditAppend } as unknown as
|
|
113
|
+
const auditLog = { append: auditAppend } as unknown as GatewayAuditAdapter;
|
|
114
114
|
|
|
115
115
|
const prisma = {
|
|
116
116
|
gatewayProviderCredential: { count: providerCount },
|
|
@@ -188,7 +188,7 @@ describe("VirtualKeyService.create", () => {
|
|
|
188
188
|
expect(created.hashedSecret).not.toBe(result.secret);
|
|
189
189
|
});
|
|
190
190
|
|
|
191
|
-
it("emits VK_CREATED change-event +
|
|
191
|
+
it("emits VK_CREATED change-event + gateway.virtual_key.created audit in same tx", async () => {
|
|
192
192
|
const mocks = makeService();
|
|
193
193
|
|
|
194
194
|
await mocks.service.create({ ...baseCreate });
|
|
@@ -197,7 +197,7 @@ describe("VirtualKeyService.create", () => {
|
|
|
197
197
|
expect(mocks.changeAppend.mock.calls[0]?.[0].kind).toBe("VK_CREATED");
|
|
198
198
|
expect(mocks.auditAppend).toHaveBeenCalledOnce();
|
|
199
199
|
expect(mocks.auditAppend.mock.calls[0]?.[0].action).toBe(
|
|
200
|
-
"
|
|
200
|
+
"gateway.virtual_key.created",
|
|
201
201
|
);
|
|
202
202
|
});
|
|
203
203
|
|
|
@@ -348,7 +348,7 @@ describe("VirtualKeyService.revoke", () => {
|
|
|
348
348
|
expect(mocks.revokeMock).toHaveBeenCalledOnce();
|
|
349
349
|
expect(mocks.changeAppend.mock.calls[0]?.[0].kind).toBe("VK_REVOKED");
|
|
350
350
|
expect(mocks.auditAppend.mock.calls[0]?.[0].action).toBe(
|
|
351
|
-
"
|
|
351
|
+
"gateway.virtual_key.revoked",
|
|
352
352
|
);
|
|
353
353
|
});
|
|
354
354
|
});
|