robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesfix(zip): missed "password:" prompt if output trails it #41364c5ea9ca2ad

master
16.9 KiB533 linesraw
1local n = require('test.functional.testnvim')()
2local t = require('test.testutil')
3
4local describe, it, before_each, after_each = t.describe, t.it, t.before_each, t.after_each
5local api = n.api
6local eq = t.eq
7local exec_capture = n.exec_capture
8local exec_lua = n.exec_lua
9local feed = n.feed
10local fn = n.fn
11local poke_eventloop = n.poke_eventloop
12
13local fixtures = vim.fs.joinpath(t.paths.test_source_path, 'test/functional/fixtures/zip')
14local old_samples = vim.fs.joinpath(t.paths.test_source_path, 'test/old/testdir/samples')
15
16local function lines()
17  return api.nvim_buf_get_lines(0, 0, -1, false)
18end
19
20local function edit(path)
21  api.nvim_cmd({ cmd = 'edit', args = { path }, magic = { file = false, bar = false } }, {})
22end
23
24local function clear_zip()
25  n.clear({ args = { '--clean' } })
26end
27
28local function line_of(text)
29  for i, line in ipairs(lines()) do
30    if line == text then
31      return i
32    end
33  end
34  error(('missing line %q in %s'):format(text, vim.inspect(lines())))
35end
36
37describe('nvim.zip', function()
38  local root
39
40  --- Copy an archive into the test directory and return its path.
41  local function stage(source_dir, source, as)
42    local target = vim.fs.joinpath(root, as or source)
43    assert(vim.uv.fs_copyfile(vim.fs.joinpath(source_dir, source), target))
44    return target
45  end
46
47  --- Stage the browsing fixture, restart, and open it.
48  local function browse(as)
49    local archive = stage(fixtures, 'browser.zip', as)
50    clear_zip()
51    edit(archive)
52    return archive
53  end
54
55  before_each(function()
56    t.skip(vim.fn.executable('unzip') == 0, 'unzip not available')
57    root = vim.fs.normalize(t.tmpname(false) .. ' space%#')
58    t.mkdir(root)
59  end)
60
61  after_each(function()
62    n.rmdir(root)
63  end)
64
65  describe('activation', function()
66    it('uses zip.lua by default', function()
67      browse()
68
69      eq('folder/', lines()[1])
70      eq(true, exec_lua('return vim.g.loaded_nvim_zip_plugin == true'))
71      eq(false, exec_lua('return vim.g.loaded_zipPlugin ~= nil'))
72    end)
73
74    it('defers to zipPlugin.vim loaded before startup plugins', function()
75      local archive = stage(old_samples, 'test.zip', 'legacy.zip')
76      n.clear({ args = { '--clean', '--cmd', 'packadd old-zip' } })
77
78      edit(archive)
79
80      eq(true, lines()[1]:find('" zip.vim version', 1, true) ~= nil)
81      eq(0, fn.exists('#nvim.zip'))
82      eq(false, exec_lua('return vim.g.loaded_nvim_zip_plugin ~= nil'))
83    end)
84
85    it('yields to zipPlugin.vim loaded after startup', function()
86      local archive = stage(old_samples, 'test.zip', 'legacy.zip')
87      clear_zip()
88      exec_lua([[vim.cmd.packadd('old-zip')]])
89
90      edit(archive)
91
92      eq(true, lines()[1]:find('" zip.vim version', 1, true) ~= nil)
93      eq(1, fn.exists('#nvim.zip'))
94      eq(true, exec_lua('return vim.g.loaded_nvim_zip_plugin == true'))
95    end)
96
97    it('can be disabled', function()
98      local archive = stage(fixtures, 'browser.zip')
99      n.clear({
100        args = { '--clean', '--cmd', 'let g:loaded_nvim_zip_plugin = 1' },
101      })
102
103      edit(archive)
104
105      eq(0, fn.exists('#nvim.zip'))
106      eq('', api.nvim_get_option_value('filetype', { buf = 0 }))
107    end)
108
109    it('can source zip.lua repeatedly', function()
110      clear_zip()
111
112      -- Re-sourcing must reuse the augroup rather than stack duplicate autocmds.
113      eq(
114        2,
115        exec_lua(function()
116          vim.cmd.runtime('plugin/zip.lua')
117          vim.cmd.runtime('plugin/zip.lua')
118          local ids = {}
119          for _, autocmd in ipairs(vim.api.nvim_get_autocmds({ group = 'nvim.zip' })) do
120            ids[autocmd.id] = true
121          end
122          return vim.tbl_count(ids)
123        end)
124      )
125    end)
126
127    it('reports an unavailable backend without claiming the buffer', function()
128      local archive = stage(fixtures, 'browser.zip')
129      clear_zip()
130      exec_lua([[vim.env.PATH = '']])
131
132      edit(archive)
133      poke_eventloop()
134
135      eq(true, exec_capture('messages'):find('unzip executable not found', 1, true) ~= nil)
136      eq(false, exec_lua('return vim.b.nvim_dir ~= nil'))
137    end)
138  end)
139
140  describe('browsing', function()
141    it('opens zip-compatible file types', function()
142      browse('browser.jar')
143
144      eq('folder/', lines()[1])
145      eq('zip', api.nvim_get_option_value('filetype', { buf = 0 }))
146    end)
147
148    it('browses directories and opens entries', function()
149      browse()
150
151      eq({
152        'folder/',
153        'inner.zip',
154        '../escape.txt',
155        '/absolute.txt',
156        'crlf.txt',
157        'noeol.txt',
158        'names/',
159      }, lines())
160      eq('zip', api.nvim_get_option_value('filetype', { buf = 0 }))
161      eq(true, exec_capture('syntax list zipDirectory'):find('zipDirectory', 1, true) ~= nil)
162
163      feed('<CR>')
164      poke_eventloop()
165      eq({ 'nested/', 'root.txt', 'root.java' }, lines())
166
167      feed('<CR>')
168      poke_eventloop()
169      eq({ 'file.txt' }, lines())
170
171      feed('-')
172      poke_eventloop()
173      eq({ 'nested/', 'root.txt', 'root.java' }, lines())
174      eq('nested/', api.nvim_get_current_line())
175
176      api.nvim_win_set_cursor(0, { 2, 0 })
177      feed('<CR>')
178      poke_eventloop()
179      eq({ 'root text' }, lines())
180      eq('nowrite', api.nvim_get_option_value('buftype', { buf = 0 }))
181      eq(true, api.nvim_get_option_value('readonly', { buf = 0 }))
182      eq(false, api.nvim_get_option_value('modifiable', { buf = 0 }))
183      eq(false, api.nvim_get_option_value('swapfile', { buf = 0 }))
184    end)
185
186    it('opens the containing directory from the archive root', function()
187      browse()
188      feed('-')
189      poke_eventloop()
190
191      eq(root, vim.fs.normalize(api.nvim_buf_get_name(0)))
192      eq('browser.zip', api.nvim_get_current_line())
193      eq('directory', api.nvim_get_option_value('filetype', { buf = 0 }))
194    end)
195
196    it('opens entries at quickfix locations', function()
197      local archive = stage(fixtures, 'browser.zip')
198      clear_zip()
199      local uri = ('zip://%s/crlf.txt'):format(archive)
200      fn.setqflist({}, 'r', { items = { { filename = uri, lnum = 2, col = 1 } } })
201
202      api.nvim_cmd({ cmd = 'cfirst' }, {})
203
204      eq(uri, api.nvim_buf_get_name(0))
205      eq({ 2, 0 }, api.nvim_win_get_cursor(0))
206      eq('text', api.nvim_get_option_value('filetype', { buf = 0 }))
207    end)
208
209    it('does not reinterpret an entry ending in .zip as an archive', function()
210      browse()
211      api.nvim_win_set_cursor(0, { line_of('inner.zip'), 0 })
212      feed('<CR>')
213      poke_eventloop()
214
215      eq({ 'nested payload' }, lines())
216      eq(false, exec_lua('return vim.b.nvim_dir ~= nil'))
217    end)
218
219    it('preserves normal file reading details for entries', function()
220      local archive = stage(fixtures, 'browser.zip')
221      clear_zip()
222
223      edit(('zip://%s/crlf.txt'):format(archive))
224      eq({ 'one', 'two' }, lines())
225      eq('dos', api.nvim_get_option_value('fileformat', { buf = 0 }))
226      eq(true, api.nvim_get_option_value('endofline', { buf = 0 }))
227
228      edit(('zip://%s/noeol.txt'):format(archive))
229      eq({ 'no final newline' }, lines())
230      eq(false, api.nvim_get_option_value('endofline', { buf = 0 }))
231    end)
232
233    it('keeps suspicious entry paths visible and readable', function()
234      browse()
235      api.nvim_win_set_cursor(0, { line_of('../escape.txt'), 0 })
236      feed('<CR>')
237      poke_eventloop()
238
239      eq({ 'escape payload' }, lines())
240    end)
241
242    it('opens non-zip files normally', function()
243      local archive = vim.fs.joinpath(root, 'plain.zip')
244      t.write_file(archive, 'plain text', true)
245      clear_zip()
246
247      edit(archive)
248
249      eq({ 'plain text' }, lines())
250      eq(false, exec_lua('return vim.b.nvim_dir ~= nil'))
251    end)
252
253    it('lists a valid empty archive as empty', function()
254      local archive = vim.fs.joinpath(root, 'empty.zip')
255      local file = assert(io.open(archive, 'wb'))
256      -- An end-of-central-directory record with no entries: a valid, empty archive.
257      file:write('PK\5\6' .. string.rep('\0', 18))
258      file:close()
259      clear_zip()
260
261      edit(archive)
262
263      eq({ '' }, lines())
264      eq('zip', api.nvim_get_option_value('filetype', { buf = 0 }))
265      eq(true, exec_lua('return vim.b.nvim_zip ~= nil'))
266    end)
267
268    it('keeps the current level when reload fails', function()
269      local archive = browse()
270      feed('<CR>')
271      poke_eventloop()
272      eq({ 'nested/', 'root.txt', 'root.java' }, lines())
273
274      assert(os.remove(archive))
275      feed('R')
276      poke_eventloop()
277      eq({ 'nested/', 'root.txt', 'root.java' }, lines())
278
279      stage(fixtures, 'browser.zip')
280      feed('R')
281      poke_eventloop()
282      eq({ 'nested/', 'root.txt', 'root.java' }, lines())
283    end)
284
285    it('integrates Java sources with zip.lua and zipPlugin.vim', function()
286      local archive = stage(fixtures, 'browser.zip', 'source.jar')
287
288      for _, legacy in ipairs({ false, true }) do
289        if legacy then
290          n.clear({ args = { '--clean', '--cmd', 'packadd old-zip' } })
291        else
292          clear_zip()
293        end
294        exec_lua('vim.g.ftplugin_java_source_path = ...', archive)
295        api.nvim_buf_set_name(0, vim.fs.joinpath(root, 'Test.java'))
296        api.nvim_buf_set_lines(0, 0, -1, false, { 'folder.root' })
297        api.nvim_cmd({ cmd = 'setfiletype', args = { 'java' } }, {})
298        api.nvim_cmd({ cmd = 'runtime', args = { 'ftplugin/java.vim' } }, {})
299
300        feed('gf')
301        poke_eventloop()
302
303        local uri = legacy and ('zipfile://%s::folder/root.java'):format(archive)
304          or ('zip://%s/folder/root.java'):format(archive)
305        eq(uri, api.nvim_buf_get_name(0))
306        eq({ 'class root {}' }, lines())
307        eq('java', api.nvim_get_option_value('filetype', { buf = 0 }))
308      end
309    end)
310  end)
311
312  -- Info-ZIP expands globs itself and reads leading dashes as options, so archive
313  -- and entry paths must always reach it as literal text.
314  describe('backend arguments', function()
315    it('reads entry selectors literally', function()
316      t.skip(t.is_os('win'), 'N/A: archive contains backslashes in entry paths')
317      local archive = stage(old_samples, 'testa.zip', 'special.zip')
318      clear_zip()
319
320      local cases = {
321        { 'zipglob/a[a].txt', 'a test file with []' },
322        { 'zipglob/a*.txt', 'a test file with a*' },
323        { 'zipglob/a?.txt', 'a test file with a?' },
324        { [[zipglob/a\.txt]], [[a test file with a\]] },
325        { [[zipglob/a\\.txt]], [[a test file with a double \]] },
326      }
327      for _, case in ipairs(cases) do
328        edit(('zip://%s/%s'):format(archive, case[1]))
329        eq({ case[2] }, lines())
330      end
331    end)
332
333    it('runs the backend when the cwd is its directory', function()
334      t.skip(t.is_os('win'), 'N/A: Windows searches the cwd before $PATH')
335      local archive = stage(fixtures, 'browser.zip')
336      local bin = vim.fs.joinpath(assert(vim.uv.fs_realpath(root)), 'bin')
337      t.mkdir(bin)
338      assert(vim.uv.fs_symlink(vim.fn.exepath('unzip'), vim.fs.joinpath(bin, 'unzip')))
339      n.clear({ args = { '--clean' }, env = { PATH = bin .. ':' .. os.getenv('PATH') } })
340
341      api.nvim_set_current_dir(bin)
342      edit(archive)
343      eq('folder/', lines()[1])
344    end)
345
346    it('keeps a leading dash in a path from becoming a backend option', function()
347      local archive = stage(old_samples, 'poc.zip')
348      clear_zip()
349
350      edit(archive)
351      eq({ '-d/', 'pwned' }, lines())
352
353      edit(('zip://%s/-d/tmp'):format(archive))
354      eq({ '' }, lines())
355    end)
356
357    it('treats archive glob characters literally', function()
358      t.skip(t.is_os('win'), 'N/A: Windows filenames cannot contain these characters')
359      local archive = stage(fixtures, 'browser.zip', 'archive::[*?].zip')
360      -- Would be matched instead of the archive above if the name were globbed.
361      stage(old_samples, 'test.zip', 'archivex.zip')
362      clear_zip()
363
364      edit(archive)
365
366      eq('folder/', lines()[1])
367      api.nvim_win_set_cursor(0, { line_of('inner.zip'), 0 })
368      feed('<CR>')
369      poke_eventloop()
370      eq({ 'nested payload' }, lines())
371
372      local uri = ('zip://%s/crlf.txt'):format(archive)
373      edit(uri)
374      eq(uri, api.nvim_buf_get_name(0))
375      eq({ 'one', 'two' }, lines())
376    end)
377
378    it('lists and opens entries with difficult names', function()
379      t.skip(t.is_os('win'), 'N/A: Windows filenames cannot contain these characters')
380      local archive = browse()
381
382      -- "star*" and "-dash" are the glob and option cases; the rest are shell
383      -- metacharacters that must survive an argv-based backend untouched.
384      local names = {
385        'space name.txt',
386        'two  spaces.txt',
387        ' leading.txt',
388        'trailing .txt',
389        [[back\slash.txt]],
390        [[single'quote.txt]],
391        'double"quote.txt',
392        'dollar$name.txt',
393        'backtick`name.txt',
394        'semi;name.txt',
395        'pipe|name.txt',
396        'amp&name.txt',
397        'paren(name).txt',
398        'bang!name.txt',
399        'hash#name.txt',
400        'percent%name.txt',
401        'star*.txt',
402        'question?.txt',
403        '[bracket].txt',
404        '-dash.txt',
405      }
406
407      api.nvim_win_set_cursor(0, { line_of('names/'), 0 })
408      feed('<CR>')
409      poke_eventloop()
410      eq(names, lines())
411
412      api.nvim_win_set_cursor(0, { line_of('star*.txt'), 0 })
413      feed('<CR>')
414      poke_eventloop()
415      eq(('zip://%s/names/star*.txt'):format(archive), api.nvim_buf_get_name(0))
416      eq({ 'content of star*.txt' }, lines())
417
418      for _, name in ipairs(names) do
419        edit(('zip://%s/names/%s'):format(archive, name))
420        eq({ 'content of ' .. name }, lines())
421      end
422    end)
423  end)
424
425  it('prompts for the password of an encrypted archive', function()
426    local archive = stage(fixtures, 'encrypted.zip')
427    clear_zip()
428
429    edit(archive)
430    eq({ 'secret.txt' }, lines())
431
432    -- The password is queued first, so that the prompt consumes it from typeahead.
433    exec_lua(function(uri)
434      vim.api.nvim_input('hunter2<CR>')
435      vim.api.nvim_cmd({ cmd = 'edit', args = { uri }, magic = { file = false, bar = false } }, {})
436    end, ('zip://%s/secret.txt'):format(archive))
437    poke_eventloop()
438
439    eq({ 'secret content' }, lines())
440  end)
441
442  it('reports an incorrect archive password', function()
443    local archive = stage(fixtures, 'encrypted.zip')
444    clear_zip()
445
446    -- Info-ZIP allows three attempts before giving up. Failure msg is scheduled, so wait() for it.
447    local reported = exec_lua(function(uri)
448      vim.api.nvim_input('no1<CR>no2<CR>no3<CR>')
449      vim.api.nvim_cmd({ cmd = 'edit', args = { uri }, magic = { file = false, bar = false } }, {})
450      local function messages()
451        return vim.api.nvim_exec2('messages', { output = true }).output
452      end
453      vim.wait(1000, function()
454        return messages():find('zip: ', 1, true) ~= nil
455      end)
456      return messages()
457    end, ('zip://%s/secret.txt'):format(archive))
458
459    t.matches('incorrect password', reported)
460  end)
461
462  describe('extract', function()
463    --- Stage an archive, restart with the cwd inside the test directory, and open it.
464    local function open_in_cwd(source_dir, source)
465      local archive = stage(source_dir, source)
466      clear_zip()
467      api.nvim_set_current_dir(root)
468      edit(archive)
469      return archive
470    end
471
472    it('extracts the entry under the cursor into the current directory', function()
473      open_in_cwd(fixtures, 'browser.zip')
474      feed('<CR>')
475      poke_eventloop()
476      api.nvim_win_set_cursor(0, { line_of('root.java'), 0 })
477      feed('x')
478      poke_eventloop()
479
480      eq('class root {}\n', t.read_file(vim.fs.joinpath(root, 'root.java')))
481    end)
482
483    it('refuses to extract a directory', function()
484      open_in_cwd(fixtures, 'browser.zip')
485      api.nvim_win_set_cursor(0, { line_of('folder/'), 0 })
486      feed('x')
487      poke_eventloop()
488
489      eq(true, exec_capture('messages'):find('not a directory', 1, true) ~= nil)
490      eq(nil, vim.uv.fs_stat(vim.fs.joinpath(root, 'folder')))
491    end)
492
493    it('refuses to overwrite an existing file when extracting', function()
494      local target = vim.fs.joinpath(root, 'root.java')
495      stage(fixtures, 'browser.zip')
496      t.write_file(target, 'untouched', true)
497      clear_zip()
498      api.nvim_set_current_dir(root)
499
500      edit(vim.fs.joinpath(root, 'browser.zip'))
501      feed('<CR>')
502      poke_eventloop()
503      api.nvim_win_set_cursor(0, { line_of('root.java'), 0 })
504      feed('x')
505      poke_eventloop()
506
507      eq(true, exec_capture('messages'):find('already exists', 1, true) ~= nil)
508      eq('untouched', t.read_file(target))
509    end)
510
511    it('extracts suspicious entries without escaping the current directory', function()
512      open_in_cwd(old_samples, 'evil.zip')
513
514      eq({
515        '../../../../etc/ax-pwn',
516        'a/../../../../../../../../../../../../../../../../../../tmp/foobar',
517        '/tmp/vim_zip/a/b/payload.txt',
518      }, lines())
519
520      for _, entry in ipairs(lines()) do
521        api.nvim_win_set_cursor(0, { line_of(entry), 0 })
522        feed('x')
523        poke_eventloop()
524      end
525
526      -- Each lands flat in the cwd, never at the path the entry asked for.
527      for _, name in ipairs({ 'ax-pwn', 'foobar', 'payload.txt' }) do
528        eq(true, vim.uv.fs_stat(vim.fs.joinpath(root, name)) ~= nil)
529      end
530      eq(nil, vim.uv.fs_stat(vim.fs.joinpath(root, '..', 'ax-pwn')))
531    end)
532  end)
533end)