-
Notifications
You must be signed in to change notification settings - Fork 3.7k
fix(logs): run PII redaction over HTTP and fix Presidio provisioning #5143
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { createMockRequest } from '@sim/testing' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockCheckInternalAuth, mockMaskPIIBatch } = vi.hoisted(() => ({ | ||
| mockCheckInternalAuth: vi.fn(), | ||
| mockMaskPIIBatch: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/auth/hybrid', () => ({ | ||
| checkInternalAuth: mockCheckInternalAuth, | ||
| })) | ||
|
|
||
| vi.mock('@/lib/guardrails/validate_pii', () => ({ | ||
| maskPIIBatch: mockMaskPIIBatch, | ||
| })) | ||
|
|
||
| import { POST } from '@/app/api/guardrails/mask-batch/route' | ||
|
|
||
| describe('POST /api/guardrails/mask-batch', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockCheckInternalAuth.mockResolvedValue({ success: true }) | ||
| mockMaskPIIBatch.mockImplementation(async (texts: string[]) => texts.map((t) => `M(${t})`)) | ||
| }) | ||
|
|
||
| it('returns 401 without internal auth', async () => { | ||
| mockCheckInternalAuth.mockResolvedValue({ | ||
| success: false, | ||
| error: 'Internal authentication required', | ||
| }) | ||
|
|
||
| const res = await POST( | ||
| createMockRequest('POST', { texts: ['a@b.com'], entityTypes: ['EMAIL_ADDRESS'] }) | ||
| ) | ||
|
|
||
| expect(res.status).toBe(401) | ||
| expect(mockMaskPIIBatch).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('masks the batch in-process and preserves order', async () => { | ||
| const res = await POST( | ||
| createMockRequest('POST', { | ||
| texts: ['a@b.com', 'hello'], | ||
| entityTypes: ['EMAIL_ADDRESS'], | ||
| language: 'en', | ||
| }) | ||
| ) | ||
|
|
||
| expect(res.status).toBe(200) | ||
| const json = await res.json() | ||
| expect(json.masked).toEqual(['M(a@b.com)', 'M(hello)']) | ||
| expect(mockMaskPIIBatch).toHaveBeenCalledWith(['a@b.com', 'hello'], ['EMAIL_ADDRESS'], 'en') | ||
| }) | ||
|
|
||
| it('rejects an invalid body with 400', async () => { | ||
| const res = await POST(createMockRequest('POST', { texts: 'not-an-array', entityTypes: [] })) | ||
|
|
||
| expect(res.status).toBe(400) | ||
| expect(mockMaskPIIBatch).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { guardrailsMaskBatchContract } from '@/lib/api/contracts' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { checkInternalAuth } from '@/lib/auth/hybrid' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { maskPIIBatch } from '@/lib/guardrails/validate_pii' | ||
|
|
||
| const logger = createLogger('GuardrailsMaskBatchAPI') | ||
|
|
||
| /** | ||
| * Internal batch PII masking. The log-redaction persist path runs in both the | ||
| * Next.js server and the trigger.dev runtime, but Presidio (Python venv) lives | ||
| * only in the app container — so redaction calls this endpoint server-to-server | ||
| * (internal JWT) to keep Presidio centralized here. | ||
| */ | ||
| export const POST = withRouteHandler(async (request: NextRequest) => { | ||
| const auth = await checkInternalAuth(request, { requireWorkflowId: false }) | ||
| if (!auth.success) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| const parsed = await parseRequest(guardrailsMaskBatchContract, request, {}) | ||
| if (!parsed.success) return parsed.response | ||
|
|
||
| const { texts, entityTypes, language } = parsed.data.body | ||
|
|
||
| try { | ||
| const masked = await maskPIIBatch(texts, entityTypes, language) | ||
| logger.info('Masked PII batch', { count: texts.length }) | ||
| return NextResponse.json({ masked }) | ||
| } catch (error) { | ||
| // A broken/absent venv makes maskPIIBatch throw; fail loudly here (the | ||
| // caller scrubs to REDACTION_FAILED, so PII is never leaked). | ||
| logger.error('PII batch masking failed', { | ||
| error: getErrorMessage(error), | ||
| count: texts.length, | ||
| }) | ||
| return NextResponse.json( | ||
| { error: getErrorMessage(error, 'PII masking failed') }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockToken, mockBaseUrl } = vi.hoisted(() => ({ | ||
| mockToken: vi.fn(), | ||
| mockBaseUrl: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/auth/internal', () => ({ generateInternalToken: mockToken })) | ||
| vi.mock('@/lib/core/utils/urls', () => ({ getInternalApiBaseUrl: mockBaseUrl })) | ||
|
|
||
| import { maskPIIBatchViaHttp } from '@/lib/guardrails/mask-client' | ||
|
|
||
| describe('maskPIIBatchViaHttp', () => { | ||
| let fetchMock: ReturnType<typeof vi.fn> | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockToken.mockResolvedValue('tok') | ||
| mockBaseUrl.mockReturnValue('http://app.internal:3000') | ||
| fetchMock = vi.fn(async (_url: string, init: { body: string }) => { | ||
| const { texts } = JSON.parse(init.body) as { texts: string[] } | ||
| return new Response(JSON.stringify({ masked: texts.map((t) => `M(${t})`) }), { | ||
| status: 200, | ||
| headers: { 'content-type': 'application/json' }, | ||
| }) | ||
| }) | ||
| vi.stubGlobal('fetch', fetchMock) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllGlobals() | ||
| }) | ||
|
|
||
| it('masks a small batch in a single request, with an abort timeout', async () => { | ||
| const out = await maskPIIBatchViaHttp(['a', 'b', 'c'], ['EMAIL_ADDRESS']) | ||
|
|
||
| expect(out).toEqual(['M(a)', 'M(b)', 'M(c)']) | ||
| expect(fetchMock).toHaveBeenCalledTimes(1) | ||
| expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal) | ||
| }) | ||
|
|
||
| it('splits by count into multiple requests, preserving global order', async () => { | ||
| const texts = Array.from({ length: 5000 }, (_, i) => `t${i}`) | ||
|
|
||
| const out = await maskPIIBatchViaHttp(texts, []) | ||
|
|
||
| expect(out).toHaveLength(5000) | ||
| expect(out[0]).toBe('M(t0)') | ||
| expect(out[4999]).toBe('M(t4999)') | ||
| expect(fetchMock).toHaveBeenCalledTimes(3) // 2000-per-request cap | ||
| }) | ||
|
|
||
| it('throws on a non-2xx response so the caller can scrub', async () => { | ||
| fetchMock.mockResolvedValueOnce(new Response('boom', { status: 500 })) | ||
|
|
||
| await expect(maskPIIBatchViaHttp(['a'], [])).rejects.toThrow(/mask-batch request failed/) | ||
| }) | ||
|
|
||
| it('returns [] without any request for empty input', async () => { | ||
| const out = await maskPIIBatchViaHttp([], []) | ||
|
|
||
| expect(out).toEqual([]) | ||
| expect(fetchMock).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| import type { GuardrailsMaskBatchResult } from '@/lib/api/contracts' | ||
| import { generateInternalToken } from '@/lib/auth/internal' | ||
| import { getInternalApiBaseUrl } from '@/lib/core/utils/urls' | ||
|
|
||
| /** | ||
| * Per-request limits. A chunk is flushed when it hits either bound, keeping each | ||
| * request small enough for one short Presidio pass under a tight timeout and far | ||
| * below the contract's 100k-entry cap — so large executions split across | ||
| * requests instead of failing validation. | ||
| */ | ||
| const REQUEST_MAX_BYTES = 256 * 1024 | ||
| const REQUEST_MAX_COUNT = 2_000 | ||
| /** Slightly above the 30s Python subprocess timeout so a hung app container aborts gracefully. */ | ||
| const REQUEST_TIMEOUT_MS = 45_000 | ||
|
|
||
| /** | ||
| * Mask PII across many strings via the internal app-container endpoint. | ||
| * | ||
| * Presidio (a Python venv) only exists in the app container, but the | ||
| * log-redaction persist path also runs inside the trigger.dev runtime — so | ||
| * redaction always routes through HTTP, the same way the guardrails tool does. | ||
| * Strings are grouped into byte/count-budgeted chunks; order is preserved, so | ||
| * the returned array matches `texts` length. | ||
| * | ||
| * Rejects on any non-2xx, timeout, or shape mismatch so the caller can apply | ||
| * its own fail-safe (scrubbing rather than leaking). | ||
| */ | ||
| export async function maskPIIBatchViaHttp( | ||
| texts: string[], | ||
| entityTypes: string[], | ||
| language?: string | ||
| ): Promise<string[]> { | ||
| if (texts.length === 0) return [] | ||
|
|
||
| const url = `${getInternalApiBaseUrl()}/api/guardrails/mask-batch` | ||
|
|
||
| const masked: string[] = [] | ||
| let batch: string[] = [] | ||
| let batchBytes = 0 | ||
|
|
||
| const flush = async () => { | ||
| if (batch.length === 0) return | ||
| const out = await postChunk(url, batch, entityTypes, language) | ||
| if (out.length !== batch.length) { | ||
| throw new Error('PII mask-batch returned an unexpected result') | ||
| } | ||
| for (const item of out) masked.push(item) | ||
| batch = [] | ||
| batchBytes = 0 | ||
| } | ||
|
|
||
| for (const text of texts) { | ||
| const bytes = Buffer.byteLength(text, 'utf8') | ||
| if ( | ||
| batch.length > 0 && | ||
| (batch.length >= REQUEST_MAX_COUNT || batchBytes + bytes > REQUEST_MAX_BYTES) | ||
| ) { | ||
| await flush() | ||
| } | ||
| batch.push(text) | ||
| batchBytes += bytes | ||
| } | ||
| await flush() | ||
|
|
||
| return masked | ||
| } | ||
|
|
||
| async function postChunk( | ||
| url: string, | ||
| texts: string[], | ||
| entityTypes: string[], | ||
| language: string | undefined | ||
| ): Promise<string[]> { | ||
| // Mint per request: a single token (5min TTL) can expire mid-batch when a | ||
| // large execution fans out into many sequential chunk requests. | ||
| const token = await generateInternalToken() | ||
|
|
||
| // boundary-raw-fetch: internal server-to-server call to the app container (internal JWT auth, configurable base URL) | ||
| const response = await fetch(url, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'content-type': 'application/json', | ||
| authorization: `Bearer ${token}`, | ||
| }, | ||
| body: JSON.stringify({ texts, entityTypes, language }), | ||
| signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), | ||
| }) | ||
|
TheodoreSpeaks marked this conversation as resolved.
|
||
|
|
||
| if (!response.ok) { | ||
| const detail = await response.text().catch(() => '') | ||
| throw new Error(`PII mask-batch request failed (${response.status}): ${detail.slice(0, 200)}`) | ||
| } | ||
|
|
||
| const data = (await response.json()) as GuardrailsMaskBatchResult | ||
| if (!Array.isArray(data.masked)) { | ||
| throw new Error('PII mask-batch returned an unexpected result') | ||
| } | ||
| return data.masked | ||
| } | ||
|
cursor[bot] marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.