mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat(audit): add TOOL_EXECUTED logging with opt-in setting
Add isToolAuditEnabled() helper that checks the auditToolOperations DB setting (off by default) or falls back to the enterprise audit_export feature flag. The createToolRoute factory now emits a TOOL_EXECUTED audit entry on successful tool execution when enabled, using a fire-and-forget pattern so a failed audit write never blocks the tool response.
This commit is contained in:
@@ -1,9 +1,39 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
|
||||
const MAX_AUDIT_INPUT_LENGTH = 200;
|
||||
|
||||
/**
|
||||
* Check whether tool operation audit logging is enabled.
|
||||
*
|
||||
* Two paths can enable it:
|
||||
* 1. The `auditToolOperations` admin setting is explicitly "true".
|
||||
* 2. An active enterprise license enables the `audit_export` feature.
|
||||
*
|
||||
* Returns false on any error so a broken check never blocks tool execution.
|
||||
*/
|
||||
export async function isToolAuditEnabled(): Promise<boolean> {
|
||||
try {
|
||||
const result = await db
|
||||
.select({ value: schema.settings.value })
|
||||
.from(schema.settings)
|
||||
.where(eq(schema.settings.key, "auditToolOperations"))
|
||||
.limit(1);
|
||||
if (result.length > 0 && result[0].value === "true") return true;
|
||||
} catch {
|
||||
// fall through to enterprise check
|
||||
}
|
||||
|
||||
try {
|
||||
const enterprise = await import("@snapotter/enterprise");
|
||||
return enterprise.isFeatureEnabled("audit_export");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function sanitizeAuditInput(raw: string): string {
|
||||
return raw.replace(/[<>&"']/g, "").slice(0, MAX_AUDIT_INPUT_LENGTH) || "(empty)";
|
||||
}
|
||||
|
||||
@@ -469,6 +469,31 @@ export function createToolRoute<T>(app: FastifyInstance, config: ToolRouteConfig
|
||||
is_ai_tool: getBundleForTool(config.toolId) !== null,
|
||||
});
|
||||
|
||||
// Fire-and-forget: audit log must never block the response
|
||||
import("../lib/audit.js")
|
||||
.then(({ isToolAuditEnabled, auditLog }) =>
|
||||
isToolAuditEnabled().then((enabled) => {
|
||||
if (!enabled) return;
|
||||
const user = getAuthUser(request);
|
||||
return auditLog(
|
||||
request.log,
|
||||
"TOOL_EXECUTED",
|
||||
{
|
||||
userId: user?.id,
|
||||
username: user?.username,
|
||||
toolId: config.toolId,
|
||||
inputFileCount: received.length,
|
||||
totalInputSize: received.reduce((sum, r) => sum + r.size, 0),
|
||||
outputFormat: (settings as Record<string, unknown>)?.format ?? null,
|
||||
status: "success",
|
||||
durationMs: Date.now() - startTime,
|
||||
},
|
||||
request.ip,
|
||||
);
|
||||
}),
|
||||
)
|
||||
.catch(() => {});
|
||||
|
||||
return reply.send({
|
||||
jobId,
|
||||
downloadUrl: `/api/v1/download/${jobId}/${encodeURIComponent(result.filename)}`,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Integration tests for TOOL_EXECUTED audit logging.
|
||||
*
|
||||
* Verifies that the createToolRoute factory emits audit entries when the
|
||||
* `auditToolOperations` admin setting is enabled and stays silent when it
|
||||
* is disabled (the default).
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, createMultipartPayload, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
const PNG = readFileSync(join(__dirname, "..", "fixtures", "test-1x1.png"));
|
||||
|
||||
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);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Helpers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function setSetting(key: string, value: string): Promise<void> {
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { [key]: value },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
}
|
||||
|
||||
async function fetchAuditLog(
|
||||
action: string,
|
||||
): Promise<{ entries: any[]; total: number }> {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/audit-log?action=${action}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return JSON.parse(res.body);
|
||||
}
|
||||
|
||||
async function processResize(): Promise<number> {
|
||||
const { body, contentType } = createMultipartPayload([
|
||||
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
|
||||
{ name: "settings", content: JSON.stringify({ width: 1 }) },
|
||||
]);
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/tools/resize",
|
||||
headers: {
|
||||
authorization: `Bearer ${adminToken}`,
|
||||
"content-type": contentType,
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
return res.statusCode;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Tests */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("tool operation audit logging", () => {
|
||||
it("does not log TOOL_EXECUTED when auditToolOperations is disabled", async () => {
|
||||
await setSetting("auditToolOperations", "false");
|
||||
|
||||
await processResize();
|
||||
|
||||
// Small delay to ensure fire-and-forget audit would have landed
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
|
||||
const body = await fetchAuditLog("TOOL_EXECUTED");
|
||||
expect(body.total).toBe(0);
|
||||
});
|
||||
|
||||
it("logs TOOL_EXECUTED when auditToolOperations is enabled", async () => {
|
||||
await setSetting("auditToolOperations", "true");
|
||||
|
||||
const statusCode = await processResize();
|
||||
expect(statusCode).toBe(200);
|
||||
|
||||
// Small delay for the fire-and-forget audit write to complete
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
|
||||
const body = await fetchAuditLog("TOOL_EXECUTED");
|
||||
expect(body.total).toBeGreaterThanOrEqual(1);
|
||||
|
||||
const entry = body.entries[0];
|
||||
expect(entry.action).toBe("TOOL_EXECUTED");
|
||||
expect(entry.details.toolId).toBe("resize");
|
||||
expect(entry.details.status).toBe("success");
|
||||
expect(typeof entry.details.durationMs).toBe("number");
|
||||
expect(entry.details.inputFileCount).toBe(1);
|
||||
expect(typeof entry.details.totalInputSize).toBe("number");
|
||||
expect(entry.details.totalInputSize).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user