on dev help sign in
escape literal text
commit45d226b0c21746f54b458f9c4e553a212a5e32c3 authorEitan Chatav <eitan.chatav@gmail.com> dateMon 24 Apr 2017, 21:53 (10 years ago) parent7034fb3
2 files changed+17−5
squeel-postgresql/src/Squeel/PostgreSQL/Query.hs+14−1 squeel-postgresql/test/Squeel/PostgreSQL/QuerySpec.hs+3−4
squeel-postgresql/src/Squeel/PostgreSQL/Query.hs+14−1
@@ -3,6 +3,7 @@
33 , FlexibleContexts
44 , FlexibleInstances
55 , GADTs
6+ , LambdaCase
67 , MultiParamTypeClasses
78 , OverloadedStrings
89 , PolyKinds
@@ -118,7 +119,19 @@ instance HasField label xs x => IsLabel label (Expression ps xs x) where
118119 fieldName (Proxy @label) (Proxy @xs) (Proxy @x)
119120
120121instance IsString (Expression ps xs 'PGText) where
121− fromString str = UnsafeExpression $ "\'" <> fromString str <> "\'"
122+ fromString str = UnsafeExpression $
123+ "E\'" <> fromString (escape =<< str) <> "\'"
124+ where
125+ escape = \case
126+ '\NUL' -> "\\0"
127+ '\'' -> "''"
128+ '"' -> "\\\""
129+ '\b' -> "\\b"
130+ '\n' -> "\\n"
131+ '\r' -> "\\r"
132+ '\t' -> "\\t"
133+ '\\' -> "\\\\"
134+ c -> [c]
122135
123136instance Num (Expression ps xs 'PGInt2) where
124137 fromInteger n = UnsafeExpression . fromString $ show n
squeel-postgresql/test/Squeel/PostgreSQL/QuerySpec.hs+3−4
@@ -55,10 +55,9 @@ spec = do
5555 `shouldBe`
5656 "INSERT INTO table1 (col1, col2) VALUES (2, 4);"
5757 it "should be safe against SQL injection in literal text" $ do
58− pendingWith "gotta find an escape function"
59− -- renderQuery (select (literalText `from` table1))
60− -- `shouldBe`
61− -- "SELECT '\\'DROP TABLE table1;' AS literal FROM table1;"
58+ renderQuery (select (literalText `from` table1))
59+ `shouldBe`
60+ "SELECT E''';DROP TABLE table1;' AS literal FROM table1;"
6261
6362type Columns = '[ '("col1", 'PGInt4), '("col2", 'PGInt4)]
6463type Tables = '[ '("table1", Columns)]