encoding_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package encoding // import "miniflux.app/v2/internal/reader/encoding"
  4. import (
  5. "bytes"
  6. "errors"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "testing"
  12. "testing/iotest"
  13. "unicode/utf8"
  14. textencoding "golang.org/x/text/encoding"
  15. "golang.org/x/text/encoding/charmap"
  16. "golang.org/x/text/encoding/japanese"
  17. "golang.org/x/text/encoding/korean"
  18. "golang.org/x/text/encoding/simplifiedchinese"
  19. "golang.org/x/text/encoding/traditionalchinese"
  20. "golang.org/x/text/encoding/unicode"
  21. )
  22. var htmlReaderConstructors = []struct {
  23. name string
  24. newReader func(input []byte, contentType string) (io.Reader, error)
  25. }{
  26. {
  27. name: "NewCharsetReader",
  28. newReader: func(input []byte, contentType string) (io.Reader, error) {
  29. return NewCharsetReader(bytes.NewReader(input), contentType)
  30. },
  31. },
  32. {
  33. name: "NewCharsetReaderFromBytes",
  34. newReader: NewCharsetReaderFromBytes,
  35. },
  36. }
  37. func readFixture(tb testing.TB, name string) []byte {
  38. tb.Helper()
  39. data, err := os.ReadFile(filepath.Join("testdata", name))
  40. if err != nil {
  41. tb.Fatalf("Unable to read fixture %q: %v", name, err)
  42. }
  43. return data
  44. }
  45. func encodeString(tb testing.TB, textEncoding textencoding.Encoding, text string) []byte {
  46. tb.Helper()
  47. data, err := textEncoding.NewEncoder().Bytes([]byte(text))
  48. if err != nil {
  49. tb.Fatalf("Unable to encode %q: %v", text, err)
  50. }
  51. return data
  52. }
  53. func readAllUTF8(t *testing.T, reader io.Reader) string {
  54. t.Helper()
  55. data, err := io.ReadAll(reader)
  56. if err != nil {
  57. t.Fatalf("Unable to read data: %v", err)
  58. }
  59. if !utf8.Valid(data) {
  60. t.Fatalf("Data is not valid UTF-8: %q", data)
  61. }
  62. return string(data)
  63. }
  64. func assertContains(t *testing.T, data string, expectedContents []string) {
  65. t.Helper()
  66. for _, expectedContent := range expectedContents {
  67. if !strings.Contains(data, expectedContent) {
  68. t.Errorf("Data does not contain expected unicode string %q", expectedContent)
  69. }
  70. }
  71. }
  72. func TestCharsetReader(t *testing.T) {
  73. testCases := []struct {
  74. name string
  75. label string
  76. fixture string
  77. expectedContents []string
  78. }{
  79. {
  80. name: "UTF-8 document",
  81. label: "UTF-8",
  82. fixture: "utf8.xml",
  83. expectedContents: []string{"Café"},
  84. },
  85. {
  86. name: "ISO-8859-1 document",
  87. label: "ISO-8859-1",
  88. fixture: "iso-8859-1.xml",
  89. expectedContents: []string{"Café", "Présentation"},
  90. },
  91. {
  92. name: "Windows-1252 document",
  93. label: "windows-1252",
  94. fixture: "windows-1252.xml",
  95. expectedContents: []string{"Euro €"},
  96. },
  97. {
  98. name: "KOI8-R document",
  99. label: "KOI8-R",
  100. fixture: "koi8r.xml",
  101. expectedContents: []string{"Пример RSS ленты", "Привет мир! Ёжик, чай, Москва, Санкт-Петербург."},
  102. },
  103. {
  104. name: "unknown label with UTF-8 document",
  105. label: "invalid",
  106. fixture: "invalid-prolog.xml",
  107. expectedContents: []string{"Café"},
  108. },
  109. {
  110. name: "UTF-8 document declared as ISO-8859-1",
  111. label: "ISO-8859-1",
  112. fixture: "utf8-incorrect-prolog.xml",
  113. expectedContents: []string{"Café"},
  114. },
  115. {
  116. name: "UTF-8 document declared as Windows-1252",
  117. label: "windows-1252",
  118. fixture: "windows-1252-incorrect-prolog.xml",
  119. expectedContents: []string{"Euro €"},
  120. },
  121. }
  122. for _, testCase := range testCases {
  123. t.Run(testCase.name, func(t *testing.T) {
  124. reader, err := CharsetReader(testCase.label, bytes.NewReader(readFixture(t, testCase.fixture)))
  125. if err != nil {
  126. t.Fatalf("Unable to create reader: %v", err)
  127. }
  128. assertContains(t, readAllUTF8(t, reader), testCase.expectedContents)
  129. })
  130. }
  131. }
  132. func TestCharsetReaderRoundTrip(t *testing.T) {
  133. testCases := []struct {
  134. label string
  135. textEncoding textencoding.Encoding
  136. text string
  137. }{
  138. {label: "koi8-r", textEncoding: charmap.KOI8R, text: "Привет мир"},
  139. {label: "KOI8-R", textEncoding: charmap.KOI8R, text: "Привет мир"},
  140. {label: "windows-1251", textEncoding: charmap.Windows1251, text: "Съешь же ещё этих мягких французских булок"},
  141. {label: "iso-8859-2", textEncoding: charmap.ISO8859_2, text: "Zażółć gęślą jaźń"},
  142. {label: "shift_jis", textEncoding: japanese.ShiftJIS, text: "こんにちは世界"},
  143. {label: "euc-jp", textEncoding: japanese.EUCJP, text: "こんにちは世界"},
  144. {label: "gbk", textEncoding: simplifiedchinese.GBK, text: "你好世界"},
  145. {label: "big5", textEncoding: traditionalchinese.Big5, text: "你好世界"},
  146. {label: "euc-kr", textEncoding: korean.EUCKR, text: "안녕하세요 세계"},
  147. {label: "utf-16le", textEncoding: unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM), text: "Café 😀"},
  148. }
  149. for _, testCase := range testCases {
  150. t.Run(testCase.label, func(t *testing.T) {
  151. input := encodeString(t, testCase.textEncoding, testCase.text)
  152. reader, err := CharsetReader(testCase.label, bytes.NewReader(input))
  153. if err != nil {
  154. t.Fatalf("Unable to create reader: %v", err)
  155. }
  156. if data := readAllUTF8(t, reader); data != testCase.text {
  157. t.Errorf("Data does not match expected unicode string, got %q expected %q", data, testCase.text)
  158. }
  159. })
  160. }
  161. }
  162. // The XML decoder converts UTF-16 documents to UTF-8 but keeps encoding="utf-16" in the prolog.
  163. func TestCharsetReaderWithUTF16LabelAndUTF8Input(t *testing.T) {
  164. input := "<rss><channel><title>Título 😀</title></channel></rss>"
  165. reader, err := CharsetReader("utf-16", strings.NewReader(input))
  166. if err != nil {
  167. t.Fatalf("Unable to create reader: %v", err)
  168. }
  169. if data := readAllUTF8(t, reader); data != input {
  170. t.Errorf("Data does not match expected unicode string, got %q expected %q", data, input)
  171. }
  172. }
  173. func TestCharsetReaderWithUnknownLabelAndNonUTF8Input(t *testing.T) {
  174. input := encodeString(t, charmap.Windows1252, "Euro €")
  175. if _, err := CharsetReader("not-a-charset", bytes.NewReader(input)); err == nil {
  176. t.Fatal("Expected an error for an unknown label with non UTF-8 input")
  177. }
  178. }
  179. func TestCharsetReaderWithEmptyInput(t *testing.T) {
  180. reader, err := CharsetReader("ISO-8859-1", bytes.NewReader(nil))
  181. if err != nil {
  182. t.Fatalf("Unable to create reader: %v", err)
  183. }
  184. if data := readAllUTF8(t, reader); data != "" {
  185. t.Errorf("Expected empty data, got %q", data)
  186. }
  187. }
  188. func TestCharsetReaderWithReadError(t *testing.T) {
  189. expectedErr := errors.New("read failure")
  190. if _, err := CharsetReader("ISO-8859-1", iotest.ErrReader(expectedErr)); !errors.Is(err, expectedErr) {
  191. t.Fatalf("Expected error %v, got %v", expectedErr, err)
  192. }
  193. }
  194. func TestNewCharsetReader(t *testing.T) {
  195. windows1251Document := `<!DOCTYPE html><html><head><meta charset="windows-1251"><title>Привет мир</title></head><body><p>Съешь же ещё этих мягких французских булок</p></body></html>`
  196. mislabeledWindows1251Document := `<!DOCTYPE html><html><head><meta charset="iso-8859-1"><title>Привет мир</title></head><body><p>Съешь же ещё этих мягких французских булок</p></body></html>`
  197. shiftJISDocument := `<!DOCTYPE html><html><head><title>こんにちは世界</title></head><body><p>日本語のテキスト</p></body></html>`
  198. utf16Document := `<!DOCTYPE html><html><head><title>Café</title></head><body><p>Jürgen 😀</p></body></html>`
  199. testCases := []struct {
  200. name string
  201. contentType string
  202. input []byte
  203. expectedContents []string
  204. expectedOutput string
  205. }{
  206. {
  207. name: "UTF-8 HTML with charset in Content-Type",
  208. contentType: "text/html; charset=UTF-8",
  209. input: readFixture(t, "utf8.html"),
  210. expectedContents: []string{"Café"},
  211. },
  212. {
  213. name: "UTF-8 HTML without charset in Content-Type",
  214. contentType: "text/html",
  215. input: readFixture(t, "utf8.html"),
  216. expectedContents: []string{"Café"},
  217. },
  218. {
  219. name: "UTF-8 HTML with meta tag after 1024 bytes",
  220. contentType: "text/html",
  221. input: readFixture(t, "utf8-meta-after-1024.html"),
  222. expectedContents: []string{"Café"},
  223. },
  224. {
  225. name: "ISO-8859-1 HTML with charset in Content-Type",
  226. contentType: "text/html; charset=ISO-8859-1",
  227. input: readFixture(t, "iso-8859-1.html"),
  228. expectedContents: []string{"Frédéric", "Café"},
  229. },
  230. {
  231. name: "ISO-8859-1 HTML with charset in meta tag",
  232. contentType: "text/html",
  233. input: readFixture(t, "iso-8859-1.html"),
  234. expectedContents: []string{"Frédéric", "Café"},
  235. },
  236. {
  237. // The meta tag is not detected: the Windows-1252 fallback happens to decode ISO-8859-1 text correctly.
  238. name: "ISO-8859-1 HTML with meta tag after 1024 bytes",
  239. contentType: "text/html",
  240. input: readFixture(t, "iso-8859-1-meta-after-1024.html"),
  241. expectedContents: []string{"Café"},
  242. },
  243. {
  244. name: "ISO-8859-1 XML without Content-Type",
  245. contentType: "",
  246. input: readFixture(t, "iso-8859-1.xml"),
  247. expectedContents: []string{"Café", "Présentation"},
  248. },
  249. {
  250. name: "KOI8-R text with charset in Content-Type",
  251. contentType: "text/xml; charset=koi8-r",
  252. input: encodeString(t, charmap.KOI8R, "Привет мир"),
  253. expectedOutput: "Привет мир",
  254. },
  255. {
  256. name: "KOI8-R feed with charset in Content-Type",
  257. contentType: "application/rss+xml; charset=KOI8-R",
  258. input: readFixture(t, "koi8r.xml"),
  259. expectedContents: []string{"Тестовая лента в кодировке KOI8-R", "Проверка специальных символов"},
  260. },
  261. {
  262. name: "Windows-1251 HTML with charset in meta tag",
  263. contentType: "text/html",
  264. input: encodeString(t, charmap.Windows1251, windows1251Document),
  265. expectedOutput: windows1251Document,
  266. },
  267. {
  268. name: "Windows-1251 HTML with charset in Content-Type and a different charset in meta tag",
  269. contentType: "text/html; charset=windows-1251",
  270. input: encodeString(t, charmap.Windows1251, mislabeledWindows1251Document),
  271. expectedOutput: mislabeledWindows1251Document,
  272. },
  273. {
  274. name: "Shift_JIS HTML with charset in Content-Type",
  275. contentType: "text/html; charset=shift_jis",
  276. input: encodeString(t, japanese.ShiftJIS, shiftJISDocument),
  277. expectedOutput: shiftJISDocument,
  278. },
  279. {
  280. name: "UTF-16LE HTML with byte order mark",
  281. contentType: "text/html",
  282. input: encodeString(t, unicode.UTF16(unicode.LittleEndian, unicode.UseBOM), utf16Document),
  283. expectedContents: []string{"Café", "Jürgen 😀"},
  284. },
  285. {
  286. name: "UTF-16BE HTML with byte order mark",
  287. contentType: "text/html",
  288. input: encodeString(t, unicode.UTF16(unicode.BigEndian, unicode.UseBOM), utf16Document),
  289. expectedContents: []string{"Café", "Jürgen 😀"},
  290. },
  291. }
  292. for _, testCase := range testCases {
  293. for _, constructor := range htmlReaderConstructors {
  294. t.Run(testCase.name+"/"+constructor.name, func(t *testing.T) {
  295. reader, err := constructor.newReader(testCase.input, testCase.contentType)
  296. if err != nil {
  297. t.Fatalf("Unable to create reader: %v", err)
  298. }
  299. data := readAllUTF8(t, reader)
  300. assertContains(t, data, testCase.expectedContents)
  301. if testCase.expectedOutput != "" && data != testCase.expectedOutput {
  302. t.Errorf("Data does not match expected unicode string, got %q expected %q", data, testCase.expectedOutput)
  303. }
  304. })
  305. }
  306. }
  307. }
  308. func TestNewCharsetReaderWithEmptyInput(t *testing.T) {
  309. for _, constructor := range htmlReaderConstructors {
  310. t.Run(constructor.name, func(t *testing.T) {
  311. reader, err := constructor.newReader(nil, "text/html")
  312. if err != nil {
  313. t.Fatalf("Unable to create reader: %v", err)
  314. }
  315. if data := readAllUTF8(t, reader); data != "" {
  316. t.Errorf("Expected empty data, got %q", data)
  317. }
  318. })
  319. }
  320. }
  321. func TestNewCharsetReaderWithReadError(t *testing.T) {
  322. expectedErr := errors.New("read failure")
  323. if _, err := NewCharsetReader(iotest.ErrReader(expectedErr), "text/html"); !errors.Is(err, expectedErr) {
  324. t.Fatalf("Expected error %v, got %v", expectedErr, err)
  325. }
  326. }
  327. func FuzzCharsetReader(f *testing.F) {
  328. fixtures := []struct {
  329. label string
  330. fixture string
  331. }{
  332. {"UTF-8", "utf8.xml"},
  333. {"ISO-8859-1", "iso-8859-1.xml"},
  334. {"windows-1252", "windows-1252.xml"},
  335. {"KOI8-R", "koi8r.xml"},
  336. {"invalid", "invalid-prolog.xml"},
  337. {"ISO-8859-1", "utf8-incorrect-prolog.xml"},
  338. }
  339. for _, seed := range fixtures {
  340. f.Add(seed.label, readFixture(f, seed.fixture))
  341. }
  342. f.Add("shift_jis", encodeString(f, japanese.ShiftJIS, "こんにちは世界"))
  343. f.Add("utf-16le", encodeString(f, unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM), "Café 😀"))
  344. f.Add("not-a-charset", []byte("Euro \x80"))
  345. f.Fuzz(func(t *testing.T, label string, input []byte) {
  346. reader, err := CharsetReader(label, bytes.NewReader(input))
  347. if err != nil {
  348. return
  349. }
  350. data, err := io.ReadAll(reader)
  351. if err != nil {
  352. t.Fatalf("Unable to read data: %v", err)
  353. }
  354. if !utf8.Valid(data) {
  355. t.Fatalf("Data is not valid UTF-8 for label %q: %q", label, data)
  356. }
  357. })
  358. }
  359. func FuzzNewCharsetReaderFromBytes(f *testing.F) {
  360. fixtures := []struct {
  361. contentType string
  362. fixture string
  363. }{
  364. {"text/html", "utf8.html"},
  365. {"text/html; charset=ISO-8859-1", "iso-8859-1.html"},
  366. {"text/html", "iso-8859-1-meta-after-1024.html"},
  367. {"text/html", "utf8-meta-after-1024.html"},
  368. {"application/rss+xml; charset=KOI8-R", "koi8r.xml"},
  369. {"", "iso-8859-1.xml"},
  370. }
  371. for _, seed := range fixtures {
  372. f.Add(seed.contentType, readFixture(f, seed.fixture))
  373. }
  374. // Output is not checked for valid UTF-8: charset.NewReader skips decoding when the
  375. // first 1024 bytes look like UTF-8, even if invalid bytes come later.
  376. f.Fuzz(func(t *testing.T, contentType string, input []byte) {
  377. reader, err := NewCharsetReaderFromBytes(input, contentType)
  378. if err != nil {
  379. t.Fatalf("Unable to create reader: %v", err)
  380. }
  381. if _, err := io.ReadAll(reader); err != nil {
  382. t.Fatalf("Unable to read data: %v", err)
  383. }
  384. })
  385. }