Function calling / tools
4.10.3kata 3 de 4

Input Validation & Security

Sanitizar, validar y aplicar listas blancas

Los argumentos que el modelo genera vienen del contexto del usuario y pueden contener prompt injection o ataques maliciosamente diseñados. NUNCA ejecutes argumentos sin validarlos. Tres defensas: (1) JSON Schema en la definición de la herramienta (lo que esperas). (2) Validación de tipos al recibir los argumentos (está bien tipado). (3) Listas blancas / whitelist para valores finitos (solo ejecutar dentro de un conjunto permitido).

Un ejemplo clásico: una herramienta `delete_record(table, id)` sin validación puede ser manipulada a delete_record(table="users", id="OR 1=1") — SQL injection. Con lista blanca: ALLOWED_TABLES = {'orders', 'sessions'}, rechazas cualquier tabla fuera de esa lista.

Para operaciones de sistema operativo (archivos, procesos), la lista blanca es obligatoria. Para consultas SQL, usa prepared statements. Para ejecución de comandos, usa shell=False y argumentos como lista, no como string concatenado.

structure.txt
# Input validation: allowlist + type checking

ALLOWED_TABLES = {'invoices', 'customers', 'orders'}
ALLOWED_OPERATIONS = {'read', 'count', 'update'}

def query_database(table: str, operation: str, filter_id: str) -> str:
    # Validation 1: whitelist
    if table not in ALLOWED_TABLES:
        return json.dumps({'error': f'table {table} not allowed'})
    if operation not in ALLOWED_OPERATIONS:
        return json.dumps({'error': f'operation {operation} not allowed'})
    # Validation 2: type check (already done by schema + Pydantic)
    # Validation 3: prepared statement (parameterized query)
    if operation == 'read':
        query = f'SELECT * FROM {table} WHERE id = %s'
        result = db.execute(query, (filter_id,))  # filter_id as parameter, not string concat
        return json.dumps(result)

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    def save_to_file(filename: str, content: str) -> str: open(f'./uploads/{filename}', 'w').write(content) # filename from model

  2. 02

    def execute_sql(table: str, filter_id: str): query = f'SELECT * FROM {table} WHERE id = {filter_id}' return db.execute(query)

  3. 03

    def delete_records(table: str, ids: list[str]): for id in ids: db.execute(f'DELETE FROM {table} WHERE id = {id}')