Skip to content

Commit

Permalink
Added basic protection for SQL-injections
Browse files Browse the repository at this point in the history
  • Loading branch information
idle sign committed Mar 13, 2020
1 parent ab91200 commit 6fa3507
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ pg_analyse changelog
====================


Unreleased
----------
+ Added basic protection for SQL-injections.


v0.2.2 [2020-03-12]
-------------------
* Fix. Repack with SQLs previously missing.
Expand Down
8 changes: 6 additions & 2 deletions pg_analyse/inspections/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,16 @@ def _tpl_read(self) -> str:
def get_sql(self) -> str:
"""Returns SQL ready to be executed."""

out = self._tpl_read()
# Here we replace ":var"-like param placeholders
# with "%(var)s"-like acceptable for psycopg2,
# escaping % with %%.

out = self._tpl_read().replace('%', '%%')
aliases = self.params_aliases

for name, value in self.arguments.items():
name_sql = aliases.get(name, name)
out = out.replace(f':{name_sql}', f"'{value}'")
out = out.replace(f':{name_sql}', f'%({name})s')

return out

Expand Down
7 changes: 4 additions & 3 deletions pg_analyse/toolbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ def __init__(self, *, dsn: str = ''):

self.dsn = dsn

def _sql_exec(self, *, connection, sql: str) -> InspectionResult:
def _sql_exec(self, *, connection, sql: str, params: dict) -> InspectionResult:

with connection.cursor() as cursor:
cursor.execute(sql)
cursor.execute(sql, params)
columns = [column.name for column in cursor.description]
rows = cursor.fetchall()

Expand Down Expand Up @@ -68,7 +68,8 @@ def run(self, *, only: TypeOnly = None, arguments: TypeInspectionsArgs = None) -

inspection.result = self._sql_exec(
connection=connection,
sql=inspection.get_sql()
sql=inspection.get_sql(),
params=inspection.arguments,
)

results.append(inspection)
Expand Down

0 comments on commit 6fa3507

Please sign in to comment.