mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat(enterprise): add audit log export endpoint (CSV/JSON)
This commit is contained in:
@@ -50,6 +50,7 @@ import { settingsRoutes } from "./routes/settings.js";
|
|||||||
import { teamsRoutes } from "./routes/teams.js";
|
import { teamsRoutes } from "./routes/teams.js";
|
||||||
import { registerToolRoutes } from "./routes/tools/index.js";
|
import { registerToolRoutes } from "./routes/tools/index.js";
|
||||||
import { userFileRoutes } from "./routes/user-files.js";
|
import { userFileRoutes } from "./routes/user-files.js";
|
||||||
|
import { registerEnterpriseRoutes } from "./routes/enterprise/index.js";
|
||||||
|
|
||||||
// Run before anything else
|
// Run before anything else
|
||||||
try {
|
try {
|
||||||
@@ -347,6 +348,9 @@ await rolesRoutes(app);
|
|||||||
// Admin ops routes (runtime log level, Prometheus metrics)
|
// Admin ops routes (runtime log level, Prometheus metrics)
|
||||||
await adminOpsRoutes(app);
|
await adminOpsRoutes(app);
|
||||||
|
|
||||||
|
// Enterprise routes (license-gated features)
|
||||||
|
await registerEnterpriseRoutes(app);
|
||||||
|
|
||||||
// API docs (Scalar)
|
// API docs (Scalar)
|
||||||
await docsRoutes(app);
|
await docsRoutes(app);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { and, desc, eq, gte, lte } from "drizzle-orm";
|
||||||
|
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { db, schema } from "../../db/index.js";
|
||||||
|
import { requirePermission } from "../../permissions.js";
|
||||||
|
|
||||||
|
const querySchema = z.object({
|
||||||
|
format: z.enum(["csv", "json"]).default("json"),
|
||||||
|
from: z.string().datetime({ offset: true }).optional(),
|
||||||
|
to: z.string().datetime({ offset: true }).optional(),
|
||||||
|
action: z.string().optional(),
|
||||||
|
actorId: z.string().optional(),
|
||||||
|
targetType: z.string().optional(),
|
||||||
|
targetId: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
function escapeCsvField(value: string): string {
|
||||||
|
if (value.includes(",") || value.includes('"') || value.includes("\n")) {
|
||||||
|
return `"${value.replace(/"/g, '""')}"`;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function registerAuditExport(app: FastifyInstance): Promise<void> {
|
||||||
|
app.get(
|
||||||
|
"/api/v1/enterprise/audit/export",
|
||||||
|
async (
|
||||||
|
request: FastifyRequest<{
|
||||||
|
Querystring: {
|
||||||
|
format?: string;
|
||||||
|
from?: string;
|
||||||
|
to?: string;
|
||||||
|
action?: string;
|
||||||
|
actorId?: string;
|
||||||
|
targetType?: string;
|
||||||
|
targetId?: string;
|
||||||
|
};
|
||||||
|
}>,
|
||||||
|
reply: FastifyReply,
|
||||||
|
) => {
|
||||||
|
const user = await requirePermission("audit:read")(request, reply);
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
// Check enterprise feature gate
|
||||||
|
let featureEnabled = false;
|
||||||
|
try {
|
||||||
|
const { isFeatureEnabled } = await import("@snapotter/enterprise");
|
||||||
|
featureEnabled = isFeatureEnabled("audit_export");
|
||||||
|
} catch {
|
||||||
|
// Enterprise package not available
|
||||||
|
}
|
||||||
|
if (!featureEnabled) {
|
||||||
|
return reply
|
||||||
|
.status(403)
|
||||||
|
.send({ error: "Audit export requires an enterprise license with the audit_export feature" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = querySchema.safeParse(request.query);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: "Invalid query parameters", details: parsed.error.issues });
|
||||||
|
}
|
||||||
|
const { format, from, to, action, actorId, targetType, targetId } = parsed.data;
|
||||||
|
|
||||||
|
// Build filter conditions
|
||||||
|
const conditions = [];
|
||||||
|
if (from) {
|
||||||
|
conditions.push(gte(schema.auditLog.createdAt, new Date(from)));
|
||||||
|
}
|
||||||
|
if (to) {
|
||||||
|
conditions.push(lte(schema.auditLog.createdAt, new Date(to)));
|
||||||
|
}
|
||||||
|
if (action) {
|
||||||
|
conditions.push(eq(schema.auditLog.action, action));
|
||||||
|
}
|
||||||
|
if (actorId) {
|
||||||
|
conditions.push(eq(schema.auditLog.actorId, actorId));
|
||||||
|
}
|
||||||
|
if (targetType) {
|
||||||
|
conditions.push(eq(schema.auditLog.targetType, targetType));
|
||||||
|
}
|
||||||
|
if (targetId) {
|
||||||
|
conditions.push(eq(schema.auditLog.targetId, targetId));
|
||||||
|
}
|
||||||
|
|
||||||
|
const where = conditions.length > 0 ? and(...conditions) : undefined;
|
||||||
|
|
||||||
|
const entries = await db
|
||||||
|
.select()
|
||||||
|
.from(schema.auditLog)
|
||||||
|
.where(where)
|
||||||
|
.orderBy(desc(schema.auditLog.createdAt));
|
||||||
|
|
||||||
|
const rows = entries.map((e) => ({
|
||||||
|
id: e.id,
|
||||||
|
actorId: e.actorId ?? "",
|
||||||
|
actorUsername: e.actorUsername,
|
||||||
|
action: e.action,
|
||||||
|
targetType: e.targetType ?? "",
|
||||||
|
targetId: e.targetId ?? "",
|
||||||
|
details: e.details ? JSON.stringify(e.details) : "",
|
||||||
|
ipAddress: e.ipAddress ?? "",
|
||||||
|
requestId: e.requestId ?? "",
|
||||||
|
createdAt: e.createdAt.toISOString(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (format === "csv") {
|
||||||
|
const headers = [
|
||||||
|
"id",
|
||||||
|
"actorId",
|
||||||
|
"actorUsername",
|
||||||
|
"action",
|
||||||
|
"targetType",
|
||||||
|
"targetId",
|
||||||
|
"details",
|
||||||
|
"ipAddress",
|
||||||
|
"requestId",
|
||||||
|
"createdAt",
|
||||||
|
];
|
||||||
|
const csvLines = [headers.join(",")];
|
||||||
|
for (const row of rows) {
|
||||||
|
csvLines.push(
|
||||||
|
headers.map((h) => escapeCsvField(String(row[h as keyof typeof row]))).join(","),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return reply
|
||||||
|
.header("Content-Type", "text/csv")
|
||||||
|
.header("Content-Disposition", 'attachment; filename="audit-export.csv"')
|
||||||
|
.send(csvLines.join("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSON format
|
||||||
|
return reply
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.header("Content-Disposition", 'attachment; filename="audit-export.json"')
|
||||||
|
.send(JSON.stringify(rows));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
app.log.info("Enterprise audit export route registered");
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { registerAuditExport } from "./audit-export.js";
|
||||||
|
|
||||||
|
export async function registerEnterpriseRoutes(app: FastifyInstance) {
|
||||||
|
await registerAuditExport(app);
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||||
|
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
|
||||||
|
let testApp: TestApp;
|
||||||
|
let adminToken: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
testApp = await buildTestApp();
|
||||||
|
adminToken = await loginAsAdmin(testApp.app);
|
||||||
|
}, 30_000);
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await testApp.cleanup();
|
||||||
|
}, 10_000);
|
||||||
|
|
||||||
|
describe("audit export", () => {
|
||||||
|
it("returns 403 without enterprise license", async () => {
|
||||||
|
const res = await testApp.app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/api/v1/enterprise/audit/export?format=json",
|
||||||
|
headers: { authorization: `Bearer ${adminToken}` },
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(403);
|
||||||
|
const body = JSON.parse(res.body);
|
||||||
|
expect(body.error).toContain("enterprise");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 403 for CSV format without enterprise license", async () => {
|
||||||
|
const res = await testApp.app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/api/v1/enterprise/audit/export?format=csv",
|
||||||
|
headers: { authorization: `Bearer ${adminToken}` },
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 401 without auth", async () => {
|
||||||
|
const res = await testApp.app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/api/v1/enterprise/audit/export?format=json",
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 403 for non-admin user", async () => {
|
||||||
|
// Create a regular user
|
||||||
|
await testApp.app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/auth/register",
|
||||||
|
headers: { authorization: `Bearer ${adminToken}` },
|
||||||
|
payload: {
|
||||||
|
username: "auditexportuser",
|
||||||
|
password: "TestPass1",
|
||||||
|
role: "user",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await db
|
||||||
|
.update(schema.users)
|
||||||
|
.set({ mustChangePassword: false })
|
||||||
|
.where(eq(schema.users.username, "auditexportuser"));
|
||||||
|
|
||||||
|
const loginRes = await testApp.app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/auth/login",
|
||||||
|
payload: { username: "auditexportuser", password: "TestPass1" },
|
||||||
|
});
|
||||||
|
const userToken = JSON.parse(loginRes.body).token;
|
||||||
|
|
||||||
|
const res = await testApp.app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/api/v1/enterprise/audit/export?format=json",
|
||||||
|
headers: { authorization: `Bearer ${userToken}` },
|
||||||
|
});
|
||||||
|
// Regular users lack audit:read, so they get 403 before the enterprise check
|
||||||
|
expect(res.statusCode).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -64,6 +64,7 @@ import { settingsRoutes } from "../../apps/api/src/routes/settings.js";
|
|||||||
import { teamsRoutes } from "../../apps/api/src/routes/teams.js";
|
import { teamsRoutes } from "../../apps/api/src/routes/teams.js";
|
||||||
import { registerToolRoutes } from "../../apps/api/src/routes/tools/index.js";
|
import { registerToolRoutes } from "../../apps/api/src/routes/tools/index.js";
|
||||||
import { userFileRoutes } from "../../apps/api/src/routes/user-files.js";
|
import { userFileRoutes } from "../../apps/api/src/routes/user-files.js";
|
||||||
|
import { registerEnterpriseRoutes } from "../../apps/api/src/routes/enterprise/index.js";
|
||||||
|
|
||||||
// Run migrations (idempotent -- template already has the schema, but this
|
// Run migrations (idempotent -- template already has the schema, but this
|
||||||
// ensures the __drizzle_migrations journal is consistent in each fork).
|
// ensures the __drizzle_migrations journal is consistent in each fork).
|
||||||
@@ -185,6 +186,9 @@ export async function buildTestApp(): Promise<TestApp> {
|
|||||||
// Admin ops routes (runtime log level, Prometheus metrics)
|
// Admin ops routes (runtime log level, Prometheus metrics)
|
||||||
await adminOpsRoutes(app);
|
await adminOpsRoutes(app);
|
||||||
|
|
||||||
|
// Enterprise routes (license-gated features)
|
||||||
|
await registerEnterpriseRoutes(app);
|
||||||
|
|
||||||
// Analytics routes
|
// Analytics routes
|
||||||
await analyticsRoutes(app);
|
await analyticsRoutes(app);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user