Does SQLAlchemy's filer_by function protect against SQL injection?

821 views Asked by At

I want to use the SQLAlchemy filter_by function, but cannot find an explicit statement that the filter_by function escapes input to protect against SQL injection. Our usage is very simple but obviosuly very sensitive.

 self.database.active_session()
        .query(Users)
        .filter_by(
            username=username,
            is_active=1
        ).first()

Where can I read more about the filter_by function, or can anyone tell me whether it escapes input?

1

There are 1 answers

0
Yevhen Bondar On BEST ANSWER

Here is the output for postgresql connection

# trying to inject
query = db.query(User).filter_by(username="'user'; drop table user; --"")
print(query)

Output

SELECT "user".id AS user_id, "user".created_at AS user_created_at, "user".updated_at AS user_updated_at, "user".username AS user_username, "user".hashed_password AS user_hashed_password, "user".is_active AS user_is_active, "user".is_superuser AS user_is_superuser 
FROM "user" 
WHERE "user".username = %(username_1)s

String value passes as param to query, so you are protected from SQL injection.