|
| 1 | +from dataclasses import dataclass |
| 2 | +from string.templatelib import Interpolation, Template, convert |
| 3 | +from typing import Any |
| 4 | + |
| 5 | + |
| 6 | +@dataclass(frozen=True) |
| 7 | +class SQLQuery: |
| 8 | + statement: str |
| 9 | + params: list[Any] |
| 10 | + |
| 11 | + def __init__(self, template: Template) -> None: |
| 12 | + items, params = [], [] |
| 13 | + for item in template: |
| 14 | + match item: |
| 15 | + case str(): |
| 16 | + items.append(item) |
| 17 | + case Interpolation(value, _, conversion, format_spec): |
| 18 | + converted = convert(value, conversion) |
| 19 | + if format_spec: |
| 20 | + converted = format(converted, format_spec) |
| 21 | + params.append(converted) |
| 22 | + items.append("?") |
| 23 | + super().__setattr__("statement", "".join(items)) |
| 24 | + super().__setattr__("params", params) |
| 25 | + |
| 26 | + |
| 27 | +def find_users_query_v1(name: str) -> str: |
| 28 | + """Return a SQL query to find users by name.""" |
| 29 | + return f"SELECT * FROM users WHERE name = '{name}'" |
| 30 | + |
| 31 | + |
| 32 | +# Uncomment for Python 3.14: |
| 33 | +# |
| 34 | +# def find_users_query_v2(name: str) -> Template: |
| 35 | +# """Return a SQL query to find users by name.""" |
| 36 | +# return t"SELECT * FROM users WHERE name = '{name}'" |
| 37 | +# |
| 38 | +# |
| 39 | +# def find_users(name: str) -> SQLQuery: |
| 40 | +# """Return a SQL query to find users by name.""" |
| 41 | +# return SQLQuery(t"SELECT * FROM users WHERE name = {name}") |
| 42 | + |
| 43 | + |
| 44 | +def render(template: Template) -> str: |
| 45 | + return "".join( |
| 46 | + f"{text}{value}" |
| 47 | + for text, value in zip(template.strings, template.values) |
| 48 | + ) |
| 49 | + |
| 50 | + |
| 51 | +def safer_render(template: Template) -> str: |
| 52 | + items = [] |
| 53 | + for item in template: |
| 54 | + if isinstance(item, str): |
| 55 | + items.append(item) |
| 56 | + else: |
| 57 | + sanitized = str(item.value).replace("'", "''") |
| 58 | + items.append(sanitized) |
| 59 | + return "".join(items) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + # Insecure f-strings |
| 64 | + print(find_users_query_v1("' OR '1'='1")) |
| 65 | + |
| 66 | + # Uncomment for Python 3.14: |
| 67 | + # |
| 68 | + # # More secure t-strings |
| 69 | + # print(find_users_query_v2("' OR '1'='1")) |
| 70 | + # |
| 71 | + # # Insecure way of rendering t-strings into plain strings |
| 72 | + # print(render(find_users_query_v2("' OR '1'='1"))) |
| 73 | + # |
| 74 | + # # More secure way of rendering t-strings |
| 75 | + # print(safer_render(find_users_query_v2("' OR '1'='1"))) |
| 76 | + # |
| 77 | + # # Rendering t-strings into an alternative representation |
| 78 | + # print(find_users("' OR '1'='1")) |
0 commit comments