high · M4 · MASVS-CODE-4 · PTKD-VC-SQL-STRING-BUILT

    SQL built by joining request data into a string (text search)

    Server or edge function code builds a SQL statement with a template string or + that includes request data. That is SQL injection: a caller can read or change any table the database user can reach, past every RLS policy if it uses a privileged connection.

    How it is exploited

    An edge function runs query(`select * from notes where title like '%${body.q}%'`) on a service connection. A request with q = %' union select email, encrypted_password from auth.users -- returns every user's credentials.

    Why it matters

    Reading or changing any table the connection can reach, past every row-level security policy when it uses a privileged role.

    How to fix it

    1. Pass request values as parameters ($1 placeholders, postgres.js sql`` tagged templates, or the Supabase query builder).
    2. Never build SQL text from request data; allow-list identifiers such as sort columns.
    3. Use a connection with the user's own role (or the anon key plus RLS) for user-driven queries, not the service role.

    TypeScript (postgres.js)

    const rows = await sql`select * from notes where title ilike ${"%" + body.q + "%"}`;

    Does your app have this?

    PTKD checks your build or your source project for PTKD-VC-SQL-STRING-BUILT and every other check in this knowledge base.

    Scan your app

    References

    Related checks (M4)