-
Notifications
You must be signed in to change notification settings - Fork 81
SafeQuery Explained
Ben Yu edited this page Nov 30, 2023
·
18 revisions
The StringFormat class offers compile-time safety with interpolation-style string formatting, using named placeholders.
What you shouldn't use it for, is to create SQL queries, because string interpolation with untrusted input can lead to SQL injection attack. For example:
private static final StringFormat FIND_USER_BY_ID =
new StringFormat("SELECT * FROM Users WHERE user_id = '{user_id}'");
...
String query = FIND_USER_BY_ID.format(userIdInput);If the userIdInput comes from untrusted sources, it can be used to steal information about other users. The attacker can just send a string like "' OR user_id = 'victim", and then they can see all information about the victim.
Instead, consider using the com.google.mu.safesql package:
private static final StringFormat.To<SafeQuery> FIND_USER_BY_ID =
SafeQuery.template("SELECT * FROM Users WHERE user_id = '{user_id}'");
...
SafeQuery query = FIND_USER_BY_ID.with(userIdInput);Benefits provided by the safesql package:
-
SafeQueryautomatically escapes special characters to prevent injection attack. - The same set of compile-time checks ensure that you can't make human errors (like passing the user password as the user id).
- Extra sql-aware compile-time checks ensure that your SQL template is sane.
- You can compose smaller
SafeQueryobjects to create largeSafeQueryobjects, making it easier to manage complex queries. - The
GoogleSqlclass provides extra GoogleSQL conversions such as translatingjava.time.Instantto GoogleSQL'sTIMESTAMP()function.