Skip to content
NewSecurity Audit for AI-Built Apps. Fixed scope, clear report
GeekTech
Vibe Coding

How to Secure File Uploads in an AI-Built App

How to secure file uploads in an AI-built app: check type and size on the server, rename every file, lock down storage access and serve files safely.

6 min read

GeekTech Engineering Team18 years building and securing software

To secure file uploads in an AI-built app, decide on the server who may upload and where, accept only the types and sizes the feature needs, check the type from the file's contents, and give every file a name your server generates. Keep private files in private storage, serve uploads so the browser can't execute them, and treat every file as untrusted input when you process it.

Ask Cursor, Lovable, Bolt or Replit for "attach a PDF" and you get a working feature in minutes. The gaps sit in requests that skip your UI and go straight to your API or storage.

Where AI-generated upload code goes wrong

Weak spotWhat can happenWhere to look
Type checked only in the browserAny file type reaches storageThe upload component and API route
Trusting the extension or Content-Type headerAn HTML or SVG file passes as an imageServer-side validation
User filenames in storage pathsOverwritten files, path traversalCode that builds the storage key
Storage policy checks only the bucketAny user reads or replaces any fileSupabase policies, bucket settings
Public bucket for private documentsAnyone with the URL downloads invoices or IDsBucket configuration
Uploads served from the app's domainStored cross-site scripting (XSS)File URLs and response headers
No size or count limitsFull storage, stuck processing jobsAPI limits, bucket settings

Upload features concentrate several of the security mistakes in apps built with AI tools in one place.

Check who can upload, and where

Every upload needs two server-side decisions: is this user signed in, and may they write to this location? OWASP's File Upload Cheat Sheet lists both, authentication to identify the uploader and authorization to access or modify the files.

In Supabase, browser uploads are governed by row-level security (RLS) policies on the storage.objects table. Supabase's Storage access control guide notes that an upload needs only an INSERT policy, and that overwriting with upsert also needs SELECT and UPDATE. A generated policy that checks only bucket_id lets any signed-in user write anywhere in that bucket. Scope it to a folder named after the user:

create policy "Users upload to their own folder"
on storage.objects for insert to authenticated
with check (
  bucket_id = 'documents' and
  (storage.foldername(name))[1] = (select auth.jwt() ->> 'sub')
);

Write matching select, update and delete policies. Public buckets skip access control for reads, so anyone with a file's URL can download it. Storage policies fail in the same ways as table policies, covered in our list of Supabase row-level security mistakes.

With presigned URLs for direct uploads to Amazon S3, your server makes the authorization decision. AWS's presigned URL documentation calls them bearer tokens: usable multiple times until they expire, and an upload replaces any existing object with the same key. The server picks the key, never the client.

Validate file type and size on the server

An accept="image/*" attribute helps honest users. Anyone can call your API or storage endpoint directly with any file.

Server-side checks, in order:

  1. Allowlist the extensions the feature needs. OWASP's example is a CV upload that accepts docx and pdf only.
  2. Check the file's first bytes against the expected signature. OWASP warns that the Content-Type header comes from the client and is trivial to spoof.
  3. Enforce a size limit and a per-user quota.
  4. For archives you extract, apply the size limit after decompression.

Signature checks can be bypassed too, so they are one layer among several. An example Next.js route handler:

// app/api/uploads/route.ts (example)
const MAX_BYTES = 5 * 1024 * 1024;
const TYPES = [
  { mime: "image/png", ext: "png", magic: [0x89, 0x50, 0x4e, 0x47] },
  { mime: "image/jpeg", ext: "jpg", magic: [0xff, 0xd8, 0xff] },
  { mime: "application/pdf", ext: "pdf", magic: [0x25, 0x50, 0x44, 0x46] },
];
 
export async function POST(request: Request) {
  const user = await requireUser(); // from the server-side session
  const file = (await request.formData()).get("file");
  if (!(file instanceof File) || file.size > MAX_BYTES) {
    return new Response("Invalid file", { status: 400 });
  }
  const head = new Uint8Array(await file.slice(0, 8).arrayBuffer());
  const type = TYPES.find((t) => t.magic.every((b, i) => head[i] === b));
  if (!type) return new Response("Unsupported file type", { status: 415 });
 
  const key = `${user.id}/${crypto.randomUUID()}.${type.ext}`;
  await saveToPrivateBucket(key, file, type.mime);
  return Response.json({ key });
}

Supabase buckets also accept allowedMimeTypes and fileSizeLimit settings and reject uploads that don't meet them. Set both. Browser-to-storage uploads never pass through your route handler, so check their content in a processing step.

Rename every file and keep user filenames out of paths

Generated code often builds the storage path from file.name. That lets a user pick names like ../config.json, avatar.png.html or another user's exact filename. OWASP recommends generating the stored filename on the server, for example a UUID.

Keep the original name in your database if users need it, and render it as text. The storage key should contain only values your server created: the user ID, a random file ID and an allowlisted extension.

Leave overwrites off unless the feature needs them. Supabase's standard upload returns an error when the path exists, unless the request sets upsert.

Serve uploaded files so the browser can't run them

An uploaded HTML page, or an SVG with a script inside, served from your app's domain runs with your users' session. That is stored XSS.

  • Serve user files from a separate domain or the storage provider's host, never your app's origin. OWASP puts a separate host first in its list of storage options.
  • Send Content-Disposition: attachment for files users download rather than view.
  • Send the correct Content-Type with X-Content-Type-Options: nosniff, so browsers don't guess.
  • For private files, create a short-lived signed URL after an authorization check.
  • Accept SVG only where a raster image won't do.

Process uploaded files as untrusted input

Image libraries and PDF parsers read attacker-controlled bytes. For images, OWASP advises decoding and re-encoding to an allowed format, removing unnecessary metadata and using an up-to-date library with resource limits.

Other steps:

  • Run processing in a separate worker with narrow permissions and a timeout, so a parser crash or a decompression bomb can't take down the app.
  • Scan with antivirus or content disarm and reconstruction (CDR) when users share files with each other.
  • Avoid ZIP uploads unless the feature needs them. OWASP notes that archives can contain any file type.
  • Keep new files under a quarantine prefix until processing passes.

When uploaded documents go to an LLM for summaries or search, their text can carry instructions. Treat that as indirect prompt injection and limit what the model can do with it.

Common mistakes in AI-generated upload code

  • Checking file type in a React component and nowhere else.
  • Putting the Supabase service role key in the browser to get past an upload permission error. Supabase's guide says service keys bypass RLS entirely.
  • Setting upsert: true by default, so a loose policy lets one user replace another's file.
  • Saving permanent public URLs for files that should be private.
  • Deleting a record but leaving its file in storage.

A checklist to secure file uploads before launch

Run these with two test accounts:

  1. Rename an .html file to .png and upload it through the API. The server rejects it.
  2. Upload a file over your size limit, once through the API and once straight to the bucket. Both are rejected.
  3. As user A, upload into user B's folder, read user B's file and overwrite it. All three fail.
  4. Open a private file's URL while signed out. It fails, or the signed URL has expired.
  5. Upload a file named ../test.png. The stored key is one your server generated.
  6. Open an uploaded file in the browser. It comes from a separate domain with nosniff set.
  7. Search the client bundle for the service role key. Nothing turns up.

If nobody has reviewed your upload code, our security audit for AI-built apps covers file uploads and storage alongside authentication and access rules, with a written report and a prioritized fix list. To check on your own first, use our security checklist for AI-built apps.

Frequently asked questions

Is checking the file extension enough?

No. The uploader chooses the extension, and OWASP lists bypasses such as double extensions (.jpg.php), case changes and null bytes. Treat the allowlist as a first filter only.

Should files upload through my server or directly to storage?

Direct uploads with signed or presigned URLs keep large files off your app server, but your route handler never sees the bytes. Validate in a processing step and only then mark the file as ready. For small files such as avatars, a server-side route is simpler to secure.

How long should a signed upload URL last?

Long enough for one upload. Supabase's signed upload URLs are valid for two hours, and S3 presigned URLs work repeatedly until they expire. Issue one per file, tied to a server-generated path.

Do I need antivirus scanning for uploads?

If users download files that other users uploaded, add scanning and a way to report abusive content, as OWASP suggests. For files only the uploader sees, type allowlists and image re-encoding come first.

Insights

Related insights

More on Vibe Coding →

Get AI security and automation insights, monthly

AI security, automation and governance, written by engineers. No spam, unsubscribe any time.

Book a free 30-min call