Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(api): sanitize search log queries for Postgres (#3655)

Abimael Martellde3b850d5893
diff --git a/apps/api/src/services/logging/log_job.test.ts b/apps/api/src/services/logging/log_job.test.ts
new file mode 100644
index 000000000..617588321
--- /dev/null
+++ b/apps/api/src/services/logging/log_job.test.ts
@@ -0,0 +1,118 @@
+import { jest } from "@jest/globals";
+
+const captureException = jest.fn();
+jest.mock("@sentry/node", () => ({
+ captureException,
+}));
+
+jest.mock("../../config", () => ({
+ config: {
+ GCS_BUCKET_NAME: undefined,
+ USE_DB_AUTHENTICATION: true,
+ },
+}));
+
+const logger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ child: jest.fn(() => logger),
+};
+jest.mock("../../lib/logger", () => ({
+ logger,
+}));
+
+const insert = jest.fn<(data: any) => Promise<{ error: any }>>();
+const from = jest.fn(() => ({
+ insert,
+}));
+jest.mock("../supabase", () => ({
+ supabase_service: {
+ from,
+ },
+}));
+
+jest.mock("../../lib/gcs-jobs", () => ({
+ saveDeepResearchToGCS: jest.fn(),
+ saveExtractToGCS: jest.fn(),
+ saveLlmsTxtToGCS: jest.fn(),
+ saveMapToGCS: jest.fn(),
+ saveScrapeToGCS: jest.fn(),
+ saveSearchToGCS: jest.fn(),
+}));
+
+jest.mock("../../lib/extract/extract-redis", () => ({
+ saveExtractResult: jest.fn(),
+}));
+
+import { logSearch, type LoggedSearch } from "./log_job";
+
+function makeSearch(overrides: Partial<LoggedSearch> = {}): LoggedSearch {
+ return {
+ id: "019e6f45-7778-727d-adf0-0abe9d5062b6",
+ request_id: "019e6f45-7778-727d-adf0-0abe9d5062b6",
+ query: "hello",
+ team_id: "team-id",
+ options: {
+ query: "hello",
+ sources: [{ type: "web", location: "Boston" }],
+ },
+ time_taken: 100,
+ credits_cost: 1,
+ is_successful: true,
+ num_results: 0,
+ results: null,
+ zeroDataRetention: false,
+ ...overrides,
+ };
+}
+
+describe("logSearch", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ insert.mockResolvedValue({ error: null });
+ });
+
+ it("removes null bytes from search query log fields", async () => {
+ const search = makeSearch({
+ query: "hello\u0000world",
+ options: {
+ query: "nested\u0000query",
+ sources: [{ type: "web", location: "New\u0000York" }],
+ },
+ });
+
+ await logSearch(search);
+
+ expect(from).toHaveBeenCalledWith("searches");
+ const inserted = insert.mock.calls[0][0];
+ expect(inserted.query).toBe("helloworld");
+ expect(inserted.options.query).toBe("nestedquery");
+ expect(inserted.options.sources[0].location).toBe("New\u0000York");
+ expect(search.options.query).toBe("nested\u0000query");
+ });
+
+ it("uses sanitized data in Sentry insert failure context", async () => {
+ insert.mockResolvedValueOnce({
+ error: {
+ code: "22P05",
+ message: "unsupported Unicode escape sequence",
+ },
+ });
+
+ await logSearch(
+ makeSearch({
+ query: "bad\u0000query",
+ options: { query: "bad\u0000query" },
+ }),
+ );
+
+ expect(captureException).toHaveBeenCalled();
+ const context = captureException.mock.calls[0][1] as {
+ extra: { data: string };
+ };
+ expect(context.extra.data).not.toContain("\\u0000");
+ expect(context.extra.data).toContain("badquery");
+ });
+});
diff --git a/apps/api/src/services/logging/log_job.ts b/apps/api/src/services/logging/log_job.ts
index bc5363303..508ce7423 100644
--- a/apps/api/src/services/logging/log_job.ts
+++ b/apps/api/src/services/logging/log_job.ts
@@ -20,6 +20,7 @@ import { saveExtractResult } from "../../lib/extract/extract-redis";
configDotenv();
const previewTeamId = "3adefd26-77ec-5968-8dcf-c94b5630d1de";
+const nullByteRegex = /\u0000/g;
/**
* Sanitize string fields by removing null bytes (\u0000)
@@ -29,7 +30,7 @@ const previewTeamId = "3adefd26-77ec-5968-8dcf-c94b5630d1de";
function sanitizeString(value: string | null | undefined): string | null {
if (value === null || value === undefined) return null;
- return value.replace(/\u0000/g, "");
+ return value.replace(nullByteRegex, "");
}
async function robustInsert(
@@ -435,6 +436,11 @@ export async function logSearch(search: LoggedSearch, force: boolean = false) {
zeroDataRetention: search.zeroDataRetention,
});
+ const options =
+ search.zeroDataRetention || typeof search.options?.query !== "string"
+ ? search.options
+ : { ...search.options, query: sanitizeString(search.options.query) };
+
await robustInsert(
"searches",
{
@@ -442,14 +448,14 @@ export async function logSearch(search: LoggedSearch, force: boolean = false) {
request_id: search.request_id,
query: search.zeroDataRetention
? "<redacted due to zero data retention>"
- : search.query,
+ : sanitizeString(search.query),
team_id:
search.team_id === "preview" || search.team_id?.startsWith("preview_")
? previewTeamId
: search.team_id,
options: search.zeroDataRetention
? { enterprise: search.options?.enterprise }
- : search.options,
+ : options,
credits_cost: search.credits_cost,
is_successful: search.is_successful,
error: search.zeroDataRetention ? null : (search.error ?? null),