decoder_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package xml // import "miniflux.app/v2/internal/reader/xml"
  4. import (
  5. "bytes"
  6. "encoding/xml"
  7. "fmt"
  8. "os"
  9. "strings"
  10. "testing"
  11. "unicode/utf8"
  12. "golang.org/x/text/encoding"
  13. "golang.org/x/text/encoding/unicode"
  14. )
  15. func TestXMLDocumentWithISO88591Encoding(t *testing.T) {
  16. fp, err := os.Open("testdata/iso88591.xml")
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. defer fp.Close()
  21. type myXMLDocument struct {
  22. XMLName xml.Name `xml:"note"`
  23. To string `xml:"to"`
  24. From string `xml:"from"`
  25. }
  26. var doc myXMLDocument
  27. decoder := NewXMLDecoder(fp)
  28. err = decoder.Decode(&doc)
  29. if err != nil {
  30. t.Fatal(err)
  31. }
  32. expectedTo := "Anaïs"
  33. expectedFrom := "Jürgen"
  34. if doc.To != expectedTo {
  35. t.Errorf(`Incorrect "to" field, expected: %q, got: %q`, expectedTo, doc.To)
  36. }
  37. if doc.From != expectedFrom {
  38. t.Errorf(`Incorrect "from" field, expected: %q, got: %q`, expectedFrom, doc.From)
  39. }
  40. }
  41. func TestXMLDocumentWithISO88591FileEncodingButUTF8Prolog(t *testing.T) {
  42. fp, err := os.Open("testdata/iso88591_utf8_mismatch.xml")
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. defer fp.Close()
  47. type myXMLDocument struct {
  48. XMLName xml.Name `xml:"note"`
  49. To string `xml:"to"`
  50. From string `xml:"from"`
  51. }
  52. var doc myXMLDocument
  53. decoder := NewXMLDecoder(fp)
  54. err = decoder.Decode(&doc)
  55. if err != nil {
  56. t.Fatal(err)
  57. }
  58. // TODO: detect actual encoding from bytes if not UTF-8 and convert to UTF-8 if needed.
  59. // For now we just expect the invalid characters to be stripped out.
  60. expectedTo := "Anas"
  61. expectedFrom := "Jrgen"
  62. if doc.To != expectedTo {
  63. t.Errorf(`Incorrect "to" field, expected: %q, got: %q`, expectedTo, doc.To)
  64. }
  65. if doc.From != expectedFrom {
  66. t.Errorf(`Incorrect "from" field, expected: %q, got: %q`, expectedFrom, doc.From)
  67. }
  68. }
  69. func TestXMLDocumentWithKOI8REncoding(t *testing.T) {
  70. fp, err := os.Open("testdata/koi8r.xml")
  71. if err != nil {
  72. t.Fatal(err)
  73. }
  74. defer fp.Close()
  75. type item struct {
  76. Title string `xml:"title"`
  77. Description string `xml:"description"`
  78. }
  79. type channel struct {
  80. Title string `xml:"title"`
  81. Description string `xml:"description"`
  82. Items []item `xml:"item"`
  83. }
  84. type rss struct {
  85. XMLName xml.Name `xml:"rss"`
  86. Channel channel `xml:"channel"`
  87. }
  88. var doc rss
  89. decoder := NewXMLDecoder(fp)
  90. err = decoder.Decode(&doc)
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. if doc.Channel.Title != "Пример RSS ленты" {
  95. t.Errorf("Incorrect channel title, expected: %q, got: %q", "Пример RSS ленты", doc.Channel.Title)
  96. }
  97. if doc.Channel.Description != "Тестовая лента в кодировке KOI8-R" {
  98. t.Errorf("Incorrect channel description, expected: %q, got: %q", "Тестовая лента в кодировке KOI8-R", doc.Channel.Description)
  99. }
  100. if len(doc.Channel.Items) != 2 {
  101. t.Fatalf("Incorrect number of items, expected: %d, got: %d", 2, len(doc.Channel.Items))
  102. }
  103. if doc.Channel.Items[0].Title != "Первая новость" {
  104. t.Errorf("Incorrect first item title, expected: %q, got: %q", "Первая новость", doc.Channel.Items[0].Title)
  105. }
  106. if !strings.Contains(doc.Channel.Items[0].Description, "Привет мир! Ёжик, чай, Москва, Санкт-Петербург.") {
  107. t.Errorf("First item description does not contain expected text, got: %q", doc.Channel.Items[0].Description)
  108. }
  109. if !strings.Contains(doc.Channel.Items[1].Description, "Проверка специальных символов") {
  110. t.Errorf("Second item description does not contain expected text, got: %q", doc.Channel.Items[1].Description)
  111. }
  112. }
  113. func TestXMLDocumentWithIllegalUnicodeCharacters(t *testing.T) {
  114. type myxml struct {
  115. XMLName xml.Name `xml:"rss"`
  116. Version string `xml:"version,attr"`
  117. Title string `xml:"title"`
  118. }
  119. expected := "Title & 中文标题"
  120. data := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><title>Title & 中文%s标题</title></rss>`, "\x10")
  121. reader := strings.NewReader(data)
  122. var x myxml
  123. decoder := NewXMLDecoder(reader)
  124. err := decoder.Decode(&x)
  125. if err != nil {
  126. t.Error(err)
  127. return
  128. }
  129. if x.Title != expected {
  130. t.Errorf("Incorrect entry title, expected: %s, got: %s", expected, x.Title)
  131. }
  132. }
  133. func TestXMLDocumentWindows251EncodedWithIllegalCharacters(t *testing.T) {
  134. type myxml struct {
  135. XMLName xml.Name `xml:"rss"`
  136. Version string `xml:"version,attr"`
  137. Title string `xml:"title"`
  138. }
  139. expected := "Title & 中文标题"
  140. data := fmt.Sprintf(`<?xml version="1.0" encoding="windows-1251"?><rss version="2.0"><title>Title & 中文%s标题</title></rss>`, "\x10")
  141. reader := strings.NewReader(data)
  142. var x myxml
  143. decoder := NewXMLDecoder(reader)
  144. err := decoder.Decode(&x)
  145. if err != nil {
  146. t.Error(err)
  147. return
  148. }
  149. if x.Title != expected {
  150. t.Errorf("Incorrect entry title, expected: %s, got: %s", expected, x.Title)
  151. }
  152. }
  153. func TestXMLDocumentWithIncorrectEncodingField(t *testing.T) {
  154. type myxml struct {
  155. XMLName xml.Name `xml:"rss"`
  156. Version string `xml:"version,attr"`
  157. Title string `xml:"title"`
  158. }
  159. expected := "Title & 中文标题"
  160. data := fmt.Sprintf(`<?xml version="1.0" encoding="invalid"?><rss version="2.0"><title>Title & 中文%s标题</title></rss>`, "\x10")
  161. reader := strings.NewReader(data)
  162. var x myxml
  163. decoder := NewXMLDecoder(reader)
  164. err := decoder.Decode(&x)
  165. if err != nil {
  166. t.Error(err)
  167. return
  168. }
  169. if x.Title != expected {
  170. t.Errorf("Incorrect entry title, expected: %s, got: %s", expected, x.Title)
  171. }
  172. }
  173. func TestXMLDocumentWithUTF16Encoding(t *testing.T) {
  174. type myXMLDocument struct {
  175. XMLName xml.Name `xml:"note"`
  176. To string `xml:"to"`
  177. From string `xml:"from"`
  178. }
  179. encodings := map[string]encoding.Encoding{
  180. "little endian with BOM": unicode.UTF16(unicode.LittleEndian, unicode.UseBOM),
  181. "big endian with BOM": unicode.UTF16(unicode.BigEndian, unicode.UseBOM),
  182. "little endian without BOM": unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM),
  183. "big endian without BOM": unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM),
  184. }
  185. documents := map[string]string{
  186. "with prolog": `<?xml version="1.0" encoding="utf-16"?><note><to>Anaïs</to><from>Jürgen 😀</from></note>`,
  187. "without prolog": `<note><to>Anaïs</to><from>Jürgen 😀</from></note>`,
  188. }
  189. for encodingName, enc := range encodings {
  190. for documentName, document := range documents {
  191. t.Run(encodingName+" "+documentName, func(t *testing.T) {
  192. data, err := enc.NewEncoder().Bytes([]byte(document))
  193. if err != nil {
  194. t.Fatal(err)
  195. }
  196. var doc myXMLDocument
  197. if err := NewXMLDecoder(bytes.NewReader(data)).Decode(&doc); err != nil {
  198. t.Fatal(err)
  199. }
  200. if doc.To != "Anaïs" {
  201. t.Errorf(`Incorrect "to" field, got: %q`, doc.To)
  202. }
  203. if doc.From != "Jürgen 😀" {
  204. t.Errorf(`Incorrect "from" field, got: %q`, doc.From)
  205. }
  206. })
  207. }
  208. }
  209. }
  210. func TestXMLDocumentWithStrayBytesBeforeUTF8Document(t *testing.T) {
  211. type myXMLDocument struct {
  212. XMLName xml.Name `xml:"note"`
  213. To string `xml:"to"`
  214. }
  215. document := `<note><to>Anaïs</to></note>`
  216. prefixes := map[string]string{
  217. "little endian BOM": "\xFF\xFE",
  218. "big endian BOM": "\xFE\xFF",
  219. "NUL": "\x00",
  220. }
  221. for name, prefix := range prefixes {
  222. t.Run(name, func(t *testing.T) {
  223. var doc myXMLDocument
  224. if err := NewXMLDecoder(strings.NewReader(prefix + document)).Decode(&doc); err != nil {
  225. t.Fatal(err)
  226. }
  227. if doc.To != "Anaïs" {
  228. t.Errorf(`Incorrect "to" field, got: %q`, doc.To)
  229. }
  230. })
  231. }
  232. t.Run("NUL after the first character", func(t *testing.T) {
  233. var doc myXMLDocument
  234. if err := NewXMLDecoder(strings.NewReader("<\x00" + document[1:])).Decode(&doc); err != nil {
  235. t.Fatal(err)
  236. }
  237. if doc.To != "Anaïs" {
  238. t.Errorf(`Incorrect "to" field, got: %q`, doc.To)
  239. }
  240. })
  241. }
  242. func TestFilterValidXMLCharsWithInvalidUTF8Sequence(t *testing.T) {
  243. // Create input with invalid UTF-8 sequence
  244. input := []byte{0x41, 0xC0, 0xAF, 0x42} // 'A', invalid UTF-8, 'B'
  245. filtered := filterValidXMLChars(input)
  246. // The function would replace invalid UTF-8 with replacement char
  247. // rather than properly filtering
  248. if utf8.Valid(filtered) {
  249. r, _ := utf8.DecodeRune(filtered[1:])
  250. if r == utf8.RuneError {
  251. t.Error("Invalid UTF-8 was not properly filtered")
  252. }
  253. }
  254. }
  255. func FuzzFilterValidXMLChars(f *testing.F) {
  256. f.Fuzz(func(t *testing.T, s []byte) {
  257. filterValidXMLChars(s)
  258. })
  259. }