sanitize.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. package sanitize
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "slices"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. "unicode/utf8"
  12. )
  13. // Part is either a string or an int. A string is raw SQL. An int is a
  14. // argument placeholder.
  15. type Part any
  16. type Query struct {
  17. Parts []Part
  18. }
  19. // utf.DecodeRune returns the utf8.RuneError for errors. But that is actually rune U+FFFD -- the unicode replacement
  20. // character. utf8.RuneError is not an error if it is also width 3.
  21. //
  22. // https://github.com/jackc/pgx/issues/1380
  23. const replacementcharacterwidth = 3
  24. const maxBufSize = 16384 // 16 Ki
  25. var bufPool = &pool[*bytes.Buffer]{
  26. new: func() *bytes.Buffer {
  27. return &bytes.Buffer{}
  28. },
  29. reset: func(b *bytes.Buffer) bool {
  30. n := b.Len()
  31. b.Reset()
  32. return n < maxBufSize
  33. },
  34. }
  35. var null = []byte("null")
  36. func (q *Query) Sanitize(args ...any) (string, error) {
  37. argUse := make([]bool, len(args))
  38. buf := bufPool.get()
  39. defer bufPool.put(buf)
  40. for _, part := range q.Parts {
  41. switch part := part.(type) {
  42. case string:
  43. buf.WriteString(part)
  44. case int:
  45. argIdx := part - 1
  46. var p []byte
  47. if argIdx < 0 {
  48. return "", fmt.Errorf("first sql argument must be > 0")
  49. }
  50. if argIdx >= len(args) {
  51. return "", fmt.Errorf("insufficient arguments")
  52. }
  53. // Prevent SQL injection via Line Comment Creation
  54. // https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p
  55. buf.WriteByte(' ')
  56. arg := args[argIdx]
  57. switch arg := arg.(type) {
  58. case nil:
  59. p = null
  60. case int64:
  61. p = strconv.AppendInt(buf.AvailableBuffer(), arg, 10)
  62. case float64:
  63. p = strconv.AppendFloat(buf.AvailableBuffer(), arg, 'f', -1, 64)
  64. case bool:
  65. p = strconv.AppendBool(buf.AvailableBuffer(), arg)
  66. case []byte:
  67. p = QuoteBytes(buf.AvailableBuffer(), arg)
  68. case string:
  69. p = QuoteString(buf.AvailableBuffer(), arg)
  70. case time.Time:
  71. p = arg.Truncate(time.Microsecond).
  72. AppendFormat(buf.AvailableBuffer(), "'2006-01-02 15:04:05.999999999Z07:00:00'")
  73. default:
  74. return "", fmt.Errorf("invalid arg type: %T", arg)
  75. }
  76. argUse[argIdx] = true
  77. buf.Write(p)
  78. // Prevent SQL injection via Line Comment Creation
  79. // https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p
  80. buf.WriteByte(' ')
  81. default:
  82. return "", fmt.Errorf("invalid Part type: %T", part)
  83. }
  84. }
  85. for i, used := range argUse {
  86. if !used {
  87. return "", fmt.Errorf("unused argument: %d", i)
  88. }
  89. }
  90. return buf.String(), nil
  91. }
  92. func NewQuery(sql string) (*Query, error) {
  93. query := &Query{}
  94. query.init(sql)
  95. return query, nil
  96. }
  97. var sqlLexerPool = &pool[*sqlLexer]{
  98. new: func() *sqlLexer {
  99. return &sqlLexer{}
  100. },
  101. reset: func(sl *sqlLexer) bool {
  102. *sl = sqlLexer{}
  103. return true
  104. },
  105. }
  106. func (q *Query) init(sql string) {
  107. parts := q.Parts[:0]
  108. if parts == nil {
  109. // dirty, but fast heuristic to preallocate for ~90% usecases
  110. n := strings.Count(sql, "$") + strings.Count(sql, "--") + 1
  111. parts = make([]Part, 0, n)
  112. }
  113. l := sqlLexerPool.get()
  114. defer sqlLexerPool.put(l)
  115. l.src = sql
  116. l.stateFn = rawState
  117. l.parts = parts
  118. for l.stateFn != nil {
  119. l.stateFn = l.stateFn(l)
  120. }
  121. q.Parts = l.parts
  122. }
  123. func QuoteString(dst []byte, str string) []byte {
  124. const quote = '\''
  125. // Preallocate space for the worst case scenario
  126. dst = slices.Grow(dst, len(str)*2+2)
  127. // Add opening quote
  128. dst = append(dst, quote)
  129. // Iterate through the string without allocating
  130. for i := 0; i < len(str); i++ {
  131. if str[i] == quote {
  132. dst = append(dst, quote, quote)
  133. } else {
  134. dst = append(dst, str[i])
  135. }
  136. }
  137. // Add closing quote
  138. dst = append(dst, quote)
  139. return dst
  140. }
  141. func QuoteBytes(dst, buf []byte) []byte {
  142. if len(buf) == 0 {
  143. return append(dst, `'\x'`...)
  144. }
  145. // Calculate required length
  146. requiredLen := 3 + hex.EncodedLen(len(buf)) + 1
  147. // Ensure dst has enough capacity
  148. if cap(dst)-len(dst) < requiredLen {
  149. newDst := make([]byte, len(dst), len(dst)+requiredLen)
  150. copy(newDst, dst)
  151. dst = newDst
  152. }
  153. // Record original length and extend slice
  154. origLen := len(dst)
  155. dst = dst[:origLen+requiredLen]
  156. // Add prefix
  157. dst[origLen] = '\''
  158. dst[origLen+1] = '\\'
  159. dst[origLen+2] = 'x'
  160. // Encode bytes directly into dst
  161. hex.Encode(dst[origLen+3:len(dst)-1], buf)
  162. // Add suffix
  163. dst[len(dst)-1] = '\''
  164. return dst
  165. }
  166. type sqlLexer struct {
  167. src string
  168. start int
  169. pos int
  170. nested int // multiline comment nesting level.
  171. stateFn stateFn
  172. parts []Part
  173. }
  174. type stateFn func(*sqlLexer) stateFn
  175. func rawState(l *sqlLexer) stateFn {
  176. for {
  177. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  178. l.pos += width
  179. switch r {
  180. case 'e', 'E':
  181. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  182. if nextRune == '\'' {
  183. l.pos += width
  184. return escapeStringState
  185. }
  186. case '\'':
  187. return singleQuoteState
  188. case '"':
  189. return doubleQuoteState
  190. case '$':
  191. nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:])
  192. if '0' <= nextRune && nextRune <= '9' {
  193. if l.pos-l.start > 0 {
  194. l.parts = append(l.parts, l.src[l.start:l.pos-width])
  195. }
  196. l.start = l.pos
  197. return placeholderState
  198. }
  199. case '-':
  200. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  201. if nextRune == '-' {
  202. l.pos += width
  203. return oneLineCommentState
  204. }
  205. case '/':
  206. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  207. if nextRune == '*' {
  208. l.pos += width
  209. return multilineCommentState
  210. }
  211. case utf8.RuneError:
  212. if width != replacementcharacterwidth {
  213. if l.pos-l.start > 0 {
  214. l.parts = append(l.parts, l.src[l.start:l.pos])
  215. l.start = l.pos
  216. }
  217. return nil
  218. }
  219. }
  220. }
  221. }
  222. func singleQuoteState(l *sqlLexer) stateFn {
  223. for {
  224. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  225. l.pos += width
  226. switch r {
  227. case '\'':
  228. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  229. if nextRune != '\'' {
  230. return rawState
  231. }
  232. l.pos += width
  233. case utf8.RuneError:
  234. if width != replacementcharacterwidth {
  235. if l.pos-l.start > 0 {
  236. l.parts = append(l.parts, l.src[l.start:l.pos])
  237. l.start = l.pos
  238. }
  239. return nil
  240. }
  241. }
  242. }
  243. }
  244. func doubleQuoteState(l *sqlLexer) stateFn {
  245. for {
  246. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  247. l.pos += width
  248. switch r {
  249. case '"':
  250. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  251. if nextRune != '"' {
  252. return rawState
  253. }
  254. l.pos += width
  255. case utf8.RuneError:
  256. if width != replacementcharacterwidth {
  257. if l.pos-l.start > 0 {
  258. l.parts = append(l.parts, l.src[l.start:l.pos])
  259. l.start = l.pos
  260. }
  261. return nil
  262. }
  263. }
  264. }
  265. }
  266. // placeholderState consumes a placeholder value. The $ must have already has
  267. // already been consumed. The first rune must be a digit.
  268. func placeholderState(l *sqlLexer) stateFn {
  269. num := 0
  270. for {
  271. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  272. l.pos += width
  273. if '0' <= r && r <= '9' {
  274. num *= 10
  275. num += int(r - '0')
  276. } else {
  277. l.parts = append(l.parts, num)
  278. l.pos -= width
  279. l.start = l.pos
  280. return rawState
  281. }
  282. }
  283. }
  284. func escapeStringState(l *sqlLexer) stateFn {
  285. for {
  286. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  287. l.pos += width
  288. switch r {
  289. case '\\':
  290. _, width = utf8.DecodeRuneInString(l.src[l.pos:])
  291. l.pos += width
  292. case '\'':
  293. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  294. if nextRune != '\'' {
  295. return rawState
  296. }
  297. l.pos += width
  298. case utf8.RuneError:
  299. if width != replacementcharacterwidth {
  300. if l.pos-l.start > 0 {
  301. l.parts = append(l.parts, l.src[l.start:l.pos])
  302. l.start = l.pos
  303. }
  304. return nil
  305. }
  306. }
  307. }
  308. }
  309. func oneLineCommentState(l *sqlLexer) stateFn {
  310. for {
  311. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  312. l.pos += width
  313. switch r {
  314. case '\\':
  315. _, width = utf8.DecodeRuneInString(l.src[l.pos:])
  316. l.pos += width
  317. case '\n', '\r':
  318. return rawState
  319. case utf8.RuneError:
  320. if width != replacementcharacterwidth {
  321. if l.pos-l.start > 0 {
  322. l.parts = append(l.parts, l.src[l.start:l.pos])
  323. l.start = l.pos
  324. }
  325. return nil
  326. }
  327. }
  328. }
  329. }
  330. func multilineCommentState(l *sqlLexer) stateFn {
  331. for {
  332. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  333. l.pos += width
  334. switch r {
  335. case '/':
  336. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  337. if nextRune == '*' {
  338. l.pos += width
  339. l.nested++
  340. }
  341. case '*':
  342. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  343. if nextRune != '/' {
  344. continue
  345. }
  346. l.pos += width
  347. if l.nested == 0 {
  348. return rawState
  349. }
  350. l.nested--
  351. case utf8.RuneError:
  352. if width != replacementcharacterwidth {
  353. if l.pos-l.start > 0 {
  354. l.parts = append(l.parts, l.src[l.start:l.pos])
  355. l.start = l.pos
  356. }
  357. return nil
  358. }
  359. }
  360. }
  361. }
  362. var queryPool = &pool[*Query]{
  363. new: func() *Query {
  364. return &Query{}
  365. },
  366. reset: func(q *Query) bool {
  367. n := len(q.Parts)
  368. q.Parts = q.Parts[:0]
  369. return n < 64 // drop too large queries
  370. },
  371. }
  372. // SanitizeSQL replaces placeholder values with args. It quotes and escapes args
  373. // as necessary. This function is only safe when standard_conforming_strings is
  374. // on.
  375. func SanitizeSQL(sql string, args ...any) (string, error) {
  376. query := queryPool.get()
  377. query.init(sql)
  378. defer queryPool.put(query)
  379. return query.Sanitize(args...)
  380. }
  381. type pool[E any] struct {
  382. p sync.Pool
  383. new func() E
  384. reset func(E) bool
  385. }
  386. func (pool *pool[E]) get() E {
  387. v, ok := pool.p.Get().(E)
  388. if !ok {
  389. v = pool.new()
  390. }
  391. return v
  392. }
  393. func (p *pool[E]) put(v E) {
  394. if p.reset(v) {
  395. p.p.Put(v)
  396. }
  397. }