AI Security
Zero‑Trust Document Handling for AI Summaries with Cloudflare Workers AI
TL;DR: Store incoming documents in an encrypted bucket, use Cloudflare Workers AI to read them via signed URLs, process the content in‑memory only, write the summary back to a separate encrypted bucket, and delete the original file immediately. Enforce least‑privilege IAM, enable audit logs, and rotate keys regularly.
What is the threat model for AI‑generated document summaries?
When a small company hands a customer file to an AI summarization service, the following risks are common:
- Data exposure: The raw document or its summary could be read by an unauthorized party, either on the storage side or inside the AI runtime.
- Replay attacks: An attacker re‑uses a previously uploaded file to extract the same summary repeatedly.
- Man‑in‑the‑middle tampering: Modifying the document before the AI sees it, causing incorrect or malicious output.
- Retention leakage: Stale files left in storage or logs that contain snippets of the original content.
Zero‑trust means assuming every component – storage, worker, and AI model – could be compromised, so you must verify identity, encrypt data at rest and in transit, and limit the data’s lifespan.
How can I enforce zero‑trust file handling with Cloudflare Workers AI?
Cloudflare Workers AI provides a serverless environment that can fetch files from any HTTPS endpoint. To keep the flow zero‑trust, follow these steps:
- Upload to an encrypted bucket. Use Cloudflare R2 with
Server‑Side Encryption (SSE‑AES256). Enablepublic‑access‑blockso objects are not publicly readable. - Generate a short‑lived signed URL. Create a signed URL that expires in
30s(or less) for the worker to download the file. The URL includes a HMAC signature that only the worker can generate using a secret stored in a Workers KV namespace withread‑onlyaccess. - Fetch the file inside the worker. Use
fetch(signedUrl)and stream the response directly into memory. Do not write the file to the local filesystem. - Call the AI model. Pass the raw bytes to the
ai.runendpoint. Cloudflare ensures the data never leaves the edge runtime. - Write the summary to a separate encrypted bucket. Store the summary in a different R2 bucket with a distinct access policy, so even if one bucket is compromised the other remains safe.
- Delete the original file. Issue a
DELETErequest to the source bucket immediately after a successful summarization.
Below is a minimal Workers script illustrating the pattern:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// 1️⃣ Verify our own API key (sent in a custom header)
const apiKey = request.headers.get('x‑api‑key')
if (apiKey !== MY_SECRET) return new Response('Unauthorized', {status: 401})
const {fileId} = await request.json()
// 2️⃣ Generate signed URL (valid for 30 seconds)
const signedUrl = await generateSignedUrl(fileId)
// 3️⃣ Stream file into memory
const fileResp = await fetch(signedUrl)
const fileBytes = await fileResp.arrayBuffer()
// 4️⃣ Call Workers AI model (e.g., @cf/meta/llama-2-7b-chat-fp16)
const aiResp = await AI.run({
model: '@cf/meta/llama-2-7b-chat-fp16',
prompt: `Summarize the following document:\n${new TextDecoder().decode(fileBytes)}`,
max_tokens: 200
})
// 5️⃣ Store summary in a different bucket
const summaryKey = `summary/${fileId}.txt`
await R2_SUMMARY.put(summaryKey, aiResp.response, {
httpMetadata: {contentType: 'text/plain'}
})
// 6️⃣ Delete original file
await R2_SOURCE.delete(fileId)
return new Response(JSON.stringify({summaryUrl: summaryKey}), {status: 200})
}
How to store and delete intermediate files securely?
Even though the worker streams data in memory, the underlying R2 bucket still holds the original file. Implement these safeguards:
- Object‑level expiration: Set
Expiresmetadata tonow + 5 minuteswhen uploading. This acts as a safety net if deletion fails. - Versioning disabled: Turn off R2 versioning so accidental overwrites don’t create hidden copies.
- Audit‑log the delete operation: After
DELETE, write an entry to a Cloudflare Logpush destination (e.g., a Splunk endpoint) with the file ID, timestamp, and requestor identity. - Verify deletion: Perform a
HEADrequest to confirm the object no longer exists; retry up to three times before raising an alert.
How to audit and monitor the summarization pipeline?
Visibility is essential for compliance and incident response. Enable the following:
- Request logging: Use
request.cfmetadata to capture the client IP, user‑agent, and worker ID. Forward logs to a SIEM via Cloudflare Logpush. - Data‑flow tracing: Tag each summary with a UUID that propagates through the worker, AI call, and storage write. This lets you trace a summary back to its source document.
- Key rotation alerts: Store the HMAC secret for signed URLs in a KV namespace with a TTL. Rotate the secret weekly and trigger a Cloudflare Alert if the same secret is used beyond its TTL.
- Model usage metrics: Cloudflare provides
ai.runusage stats. Monitor token counts and request latency; spikes may indicate abuse.
What fallback steps should I have if a breach is detected?
Even with zero‑trust controls, you need an incident‑response playbook:
- Immediate revocation: Disable the KV secret that signs URLs, effectively blocking any further file access.
- Bulk purge: Use R2’s
DELETEwith a prefix to remove all files uploaded in the last 24 hours. - Notify customers: Draft a template that explains the exposure, the data involved, and remediation steps.
- Post‑mortem analysis: Review Logpush logs for anomalous IPs, repeated failed deletions, or unusually large token usage.
Document this workflow in a shared Confluence page or internal wiki so the whole team knows the exact steps.
When should I consider an alternative to Cloudflare Workers AI?
If any of the following apply, you might need a different solution:
- Regulatory requirements mandate that data never leave a specific geographic region not covered by Cloudflare’s edge locations.
- You need on‑premise model execution for ultra‑low latency.
- Your summarization model requires GPU inference that Cloudflare’s serverless environment does not provide.
In those cases evaluate Azure OpenAI, AWS Bedrock, or self‑hosted LLM stacks, but keep the same zero‑trust principles.
Implementing the pattern above lets a solo founder or a five‑person startup use AI summarization without exposing raw customer documents, while staying compliant with data‑privacy expectations.
Need a practical AI security review?
AISecAll reviews prompts, tool permissions, document flows, and agent behavior so small teams can use AI without guessing where the risk sits.