Repository: gradio-app/gradio
File: gradio/utils.py (Python)

Code before:
    try:
        yield
    except Exception:
        pass


def sanitize_value_for_csv(value: str | float) -> str | float:
    """
    Sanitizes a value that is being written to a CSV file to prevent CSV injection attacks.
    Reference: https://owasp.org/www-community/attacks/CSV_Injection
    """
    # Numeric types are always safe for CSV and can't trigger formula execution.
    if isinstance(value, (float, int)):
        return value

    # Be defensive: sometimes non-str types (e.g. tuples) can be passed in.
    if not isinstance(value, str):
        value = str(value)

    unsafe_prefixes = ["=", "+", "-", "@", "\t", "\n"]
    unsafe_sequences = [",=", ",+", ",-", ",@", ",\t", ",\n"]

    # JSON-like strings (used for cached Plotly examples and other complex outputs)
    # are later parsed with json.loads. Adding a leading quote to them would corrupt
    # the JSON and cause decoding errors, so we skip sanitization for these.
    if value.startswith("{") or value.startswith("["):
        return value

    # For normal string values, keep the existing CSV-injection protections.
    if any(value.startswith(prefix) for prefix in unsafe_prefixes) or any(
        sequence in value for sequence in unsafe_sequences
    ):
        return f"'{value}"

    return value



def sanitize_list_for_csv(values: list[Any]) -> list[Any]:
    """
    Sanitizes a list of values (or a list of list of values) that is being written to a
    CSV file to prevent CSV injection attacks.
    """
    sanitized_values = []
    for value in values:
        if isinstance(value, list):
            sanitized_value = [sanitize_value_for_csv(v) for v in value]
            sanitized_values.append(sanitized_value)
        else:
            sanitized_value = sanitize_value_for_csv(value)
            sanitized_values.append(sanitized_value)

Review comment (security):
I think this is too broad and could lead to a security vulnerability. I think we should serialize with json to ensure the text is valid json

```python
      if value.startswith(("{", "[")):
          try:
              parsed = json.loads(value)
              return json.dumps(parsed)
          except (json.JSONDecodeError, ValueError):
              pass  # Not valid JSON, fall through to normal sanitization
```

Code after:
    except Exception:
        pass


def sanitize_value_for_csv(value: str | float) -> str | float:
    """
    Sanitizes a value that is being written to a CSV file to prevent CSV injection attacks.
    Reference: https://owasp.org/www-community/attacks/CSV_Injection
    """
    # Numbers are always safe in CSV context
    if isinstance(value, (float, int)):
        return value

    # Coerce non-strings (e.g. tuples) to string defensively
    if not isinstance(value, str):
        value = str(value)

    # Special handling for JSON-like values
    if value.startswith(("{", "[")):
        try:
            parsed = json.loads(value)
            # Return normalized, safe JSON
            return json.dumps(parsed)
        except (json.JSONDecodeError, ValueError, TypeError):
            # Not valid JSON → treat as normal string
            pass

    # Typical CSV injection protection
    unsafe_prefixes = ["=", "+", "-", "@", "\t", "\n"]
    unsafe_sequences = [",=", ",+", ",-", ",@", ",\t", ",\n"]

    # If starts with any unsafe prefix or contains an unsafe sequence
    if any(value.startswith(prefix) for prefix in unsafe_prefixes) or any(
        sequence in value for sequence in unsafe_sequences
    ):
        return f"'{value}"

    return value


def sanitize_list_for_csv(values: list[Any]) -> list[Any]:
    """
    Sanitizes a list of values (or a list of list of values) that is being written to a
    CSV file to prevent CSV injection attacks.
    """
    sanitized_values = []
    for value in values:
        if isinstance(value, list):
            sanitized_value = [sanitize_value_for_csv(v) for v in value]
            sanitized_values.append(sanitized_value)
        else: