summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/encoding_helper_spec.rb
blob: 4c1fbb93c136623acbebca8ff824a5e6ace6ab63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Gitlab::EncodingHelper do
  using RSpec::Parameterized::TableSyntax

  let(:ext_class) { Class.new { extend Gitlab::EncodingHelper } }
  let(:binary_string) { File.read(Rails.root + "spec/fixtures/dk.png") }

  describe '#encode!' do
    [
      ["nil", nil, nil],
      ["empty string", "".encode("ASCII-8BIT"), "".encode("UTF-8")],
      ["invalid utf-8 encoded string", (+"my bad string\xE5").force_encoding("UTF-8"), "my bad string"],
      ["frozen non-ascii string", (+"é").force_encoding("ASCII-8BIT").freeze, "é".encode("UTF-8")],
      [
        'leaves ascii only string as is',
        'ascii only string',
        'ascii only string'
      ],
      [
        'leaves valid utf8 string as is',
        'multibyte string №∑∉',
        'multibyte string №∑∉'
      ],
      [
        'removes invalid bytes from ASCII-8bit encoded multibyte string. This can occur when a git diff match line truncates in the middle of a multibyte character. This occurs after the second word in this example. The test string is as short as we can get while still triggering the error condition when not looking at `detect[:confidence]`.',
        (+"mu ns\xC3\n Lorem ipsum dolor sit amet, consectetur adipisicing ut\xC3\xA0y\xC3\xB9abcd\xC3\xB9efg kia elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non p\n {: .normal_pn}\n \n-Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in\n# *Lorem ipsum\xC3\xB9l\xC3\xB9l\xC3\xA0 dolor\xC3\xB9k\xC3\xB9 sit\xC3\xA8b\xC3\xA8 N\xC3\xA8 amet b\xC3\xA0d\xC3\xAC*\n+# *consectetur\xC3\xB9l\xC3\xB9l\xC3\xA0 adipisicing\xC3\xB9k\xC3\xB9 elit\xC3\xA8b\xC3\xA8 N\xC3\xA8 sed do\xC3\xA0d\xC3\xAC*{: .italic .smcaps}\n \n \xEF\x9B\xA1 eiusmod tempor incididunt, ut\xC3\xAAn\xC3\xB9 labore et dolore. Tw\xC4\x83nj\xC3\xAC magna aliqua. Ut enim ad minim veniam\n {: .normal}\n@@ -9,5 +9,5 @@ quis nostrud\xC3\xAAt\xC3\xB9 exercitiation ullamco laboris m\xC3\xB9s\xC3\xB9k\xC3\xB9abc\xC3\xB9 nisi ").force_encoding('ASCII-8BIT'),
        "mu ns\n Lorem ipsum dolor sit amet, consectetur adipisicing ut\xC3\xA0y\xC3\xB9abcd\xC3\xB9efg kia elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non p\n {: .normal_pn}\n \n-Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in\n# *Lorem ipsum\xC3\xB9l\xC3\xB9l\xC3\xA0 dolor\xC3\xB9k\xC3\xB9 sit\xC3\xA8b\xC3\xA8 N\xC3\xA8 amet b\xC3\xA0d\xC3\xAC*\n+# *consectetur\xC3\xB9l\xC3\xB9l\xC3\xA0 adipisicing\xC3\xB9k\xC3\xB9 elit\xC3\xA8b\xC3\xA8 N\xC3\xA8 sed do\xC3\xA0d\xC3\xAC*{: .italic .smcaps}\n \n \xEF\x9B\xA1 eiusmod tempor incididunt, ut\xC3\xAAn\xC3\xB9 labore et dolore. Tw\xC4\x83nj\xC3\xAC magna aliqua. Ut enim ad minim veniam\n {: .normal}\n@@ -9,5 +9,5 @@ quis nostrud\xC3\xAAt\xC3\xB9 exercitiation ullamco laboris m\xC3\xB9s\xC3\xB9k\xC3\xB9abc\xC3\xB9 nisi "
      ],
      [
        'string with detected encoding that is not supported in Ruby',
        "\xFFe,i\xFF,\xB8oi,'\xB8,\xFF,-",
        "--broken encoding: IBM420_ltr"
      ]
    ].each do |description, test_string, xpect|
      it description do
        expect(ext_class.encode!(test_string)).to eq(xpect)
      end
    end

    it 'leaves binary string as is' do
      expect(ext_class.encode!(binary_string)).to eq(binary_string)
    end

    context 'with corrupted diff' do
      let(:corrupted_diff) do
        with_empty_bare_repository do |repo|
          content = File.read(Rails.root.join(
            'spec/fixtures/encoding/Japanese.md').to_s)
          commit_a = commit(repo, 'Japanese.md', content)
          commit_b = commit(repo, 'Japanese.md',
            content.sub('[TODO: Link]', '[現在作業中です: Link]'))

          repo.diff(commit_a, commit_b).each_line.map(&:content).join
        end
      end

      let(:cleaned_diff) do
        corrupted_diff.dup.force_encoding('UTF-8')
          .encode!('UTF-8', invalid: :replace, replace: '')
      end

      let(:encoded_diff) do
        described_class.encode!(corrupted_diff.dup)
      end

      it 'does not corrupt data but remove invalid characters' do
        expect(encoded_diff).to eq(cleaned_diff)
      end

      def commit(repo, path, content)
        oid = repo.write(content, :blob)
        index = repo.index

        index.read_tree(repo.head.target.tree) unless repo.empty?

        index.add(path: path, oid: oid, mode: 0100644)
        user = { name: 'Test', email: 'test@example.com' }

        Rugged::Commit.create(
          repo,
          tree: index.write_tree(repo),
          author: user,
          committer: user,
          message: "Update #{path}",
          parents: repo.empty? ? [] : [repo.head.target].compact,
          update_ref: 'HEAD'
        )
      end
    end
  end

  describe '#encode_utf8_no_detect' do
    where(:input, :expected) do
      "abcd" | "abcd"
      "DzDzDz" | "DzDzDz"
      "\xC7\xB2\xC7DzDzDz" | "Dz�DzDzDz"
      "🐤🐤🐤🐤\xF0\x9F\x90" | "🐤🐤🐤🐤�"
    end

    with_them do
      it 'drops invalid UTF-8' do
        expect(ext_class.encode_utf8_no_detect(input.dup.force_encoding(Encoding::ASCII_8BIT))).to eq(expected)
        expect(ext_class.encode_utf8_no_detect(input)).to eq(expected)
      end
    end
  end

  describe '#encode_utf8' do
    [
      ["nil", nil, nil],
      ["empty string", "".encode("ASCII-8BIT"), "".encode("UTF-8")],
      ["invalid utf-8 encoded string", (+"my bad string\xE5").force_encoding("UTF-8"), "my bad stringå"],
      [
        "encodes valid utf8 encoded string to utf8",
        "λ, λ, λ".encode("UTF-8"),
        "λ, λ, λ".encode("UTF-8")
      ],
      [
        "encodes valid ASCII-8BIT encoded string to utf8",
        "ascii only".encode("ASCII-8BIT"),
        "ascii only".encode("UTF-8")
      ],
      [
        "encodes valid ISO-8859-1 encoded string to utf8",
        "Rüby ist eine Programmiersprache. Wir verlängern den text damit ICU die Sprache erkennen kann.".encode("ISO-8859-1", "UTF-8"),
        "Rüby ist eine Programmiersprache. Wir verlängern den text damit ICU die Sprache erkennen kann.".encode("UTF-8")
      ],
      [
        # Test case from https://gitlab.com/gitlab-org/gitlab-foss/issues/39227
        "Equifax branch name",
        "refs/heads/Equifax".encode("UTF-8"),
        "refs/heads/Equifax".encode("UTF-8")
      ]
    ].each do |description, test_string, xpect|
      it description do
        r = ext_class.encode_utf8(test_string)
        expect(r).to eq(xpect)
        expect(r.encoding.name).to eq('UTF-8') if xpect
      end
    end

    it 'returns empty string on conversion errors' do
      expect { ext_class.encode_utf8('') }.not_to raise_error
    end

    it 'replaces invalid and undefined chars with the replace argument' do
      str = 'hællo'.encode(Encoding::UTF_16LE).force_encoding(Encoding::ASCII_8BIT)

      expect(ext_class.encode_utf8(str, replace: "\u{FFFD}")).to eq("h�llo")
    end

    context 'with strings that can be forcefully encoded into utf8' do
      let(:test_string) do
        "refs/heads/FixSymbolsTitleDropdown".encode("ASCII-8BIT")
      end

      let(:expected_string) do
        "refs/heads/FixSymbolsTitleDropdown".encode("UTF-8")
      end

      subject { ext_class.encode_utf8(test_string) }

      it "doesn't use CharlockHolmes if the encoding can be forced into utf_8" do
        expect(CharlockHolmes::EncodingDetector).not_to receive(:detect)

        expect(subject).to eq(expected_string)
        expect(subject.encoding.name).to eq('UTF-8')
      end
    end
  end

  describe '#clean' do
    [
      [
        'leaves ascii only string as is',
        'ascii only string',
        'ascii only string'
      ],
      [
        'leaves valid utf8 string as is',
        'multibyte string №∑∉',
        'multibyte string №∑∉'
      ],
      [
        'removes invalid bytes from ASCII-8bit encoded multibyte string.',
        (+"Lorem ipsum\xC3\n dolor sit amet, xy\xC3\xA0y\xC3\xB9abcd\xC3\xB9efg").force_encoding('ASCII-8BIT'),
        "Lorem ipsum\n dolor sit amet, xyàyùabcdùefg"
      ],
      [
        'handles UTF-16BE encoded strings',
        (+"\xFE\xFF\x00\x41").force_encoding('ASCII-8BIT'), # An "A" prepended with UTF-16 BOM
        "\xEF\xBB\xBFA" # An "A" prepended with UTF-8 BOM
      ]
    ].each do |description, test_string, xpect|
      it description do
        expect(ext_class.encode!(test_string)).to eq(xpect)
      end
    end
  end

  describe 'encode_binary' do
    [
      [nil, ""],
      ["", ""],
      ["  ", "  "],
      %w(a1 a1),
      ["编码", "\xE7\xBC\x96\xE7\xA0\x81".b]
    ].each do |input, result|
      it "encodes #{input.inspect} to #{result.inspect}" do
        expect(ext_class.encode_binary(input)).to eq(result)
      end
    end
  end

  describe '#binary_io' do
    it 'does not mutate the original string encoding' do
      test = 'my-test'

      io_stream = ext_class.binary_io(test)

      expect(io_stream.external_encoding.name).to eq('ASCII-8BIT')
      expect(test.encoding.name).to eq('UTF-8')
    end

    it 'returns a copy of the IO with the correct encoding' do
      test = fixture_file_upload('spec/fixtures/doc_sample.txt').to_io

      io_stream = ext_class.binary_io(test)

      expect(io_stream.external_encoding.name).to eq('ASCII-8BIT')
      expect(test).not_to eq(io_stream)
    end
  end

  describe '#detect_encoding' do
    subject { ext_class.detect_encoding(data, **kwargs) }

    let(:data) { binary_string }
    let(:kwargs) { {} }

    context 'detects encoding' do
      it { is_expected.to be_a(Hash) }

      it 'correctly detects the binary' do
        expect(subject[:type]).to eq(:binary)
      end

      context 'data is nil' do
        let(:data) { nil }

        it { is_expected.to be_nil }
      end

      context 'limit is provided' do
        let(:kwargs) do
          { limit: 10 }
        end

        it 'correctly detects the binary' do
          expect(subject[:type]).to eq(:binary)
        end
      end
    end
  end

  describe '#unquote_path' do
    it do
      expect(described_class.unquote_path('unquoted')).to eq('unquoted')
      expect(described_class.unquote_path('"quoted"')).to eq('quoted')
      expect(described_class.unquote_path('"\\311\\240\\304\\253\\305\\247\\305\\200\\310\\247\\306\\200"')).to eq('ɠīŧŀȧƀ')
      expect(described_class.unquote_path('"\\\\303\\\\251"')).to eq('\303\251')
      expect(described_class.unquote_path('"\a\b\e\f\n\r\t\v\""')).to eq("\a\b\e\f\n\r\t\v\"")
    end
  end
end