diff options
28 files changed, 1087 insertions, 73 deletions
diff --git a/runtime/doc/deprecated.txt b/runtime/doc/deprecated.txt index 5e6bc957a1..401ac87d90 100644 --- a/runtime/doc/deprecated.txt +++ b/runtime/doc/deprecated.txt @@ -128,10 +128,6 @@ NORMAL COMMANDS OPTIONS - *cpo-<* *:menu-<special>* *:menu-special* *:map-<special>* *:map-special* `<>` notation is always enabled. -- *'exrc'* *'ex'* Security risk: downloaded files could include - a malicious .nvimrc or .exrc file. See 'secure'. - Recommended alternative: define an autocommand in your - |vimrc| to set options for a matching directory. - 'gdefault' Enables the |:substitute| flag 'g' by default. - *'fe'* 'fenc'+'enc' before Vim 6.0; no longer used. - *'highlight'* *'hl'* Names of builtin |highlight-groups| cannot be changed. diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index cab2f49d94..c5ede97725 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -2354,4 +2354,20 @@ parents({start}) *vim.fs.parents()* Return: ~ (function) Iterator + +============================================================================== +Lua module: secure *lua-secure* + +read({path}) *vim.secure.read()* + Attempt to read the file at {path} prompting the user if the file should + be trusted. The user's choice is persisted in a trust database at + $XDG_STATE_HOME/nvim/trust. + + Parameters: ~ + • {path} (string) Path to a file to read. + + Return: ~ + (string|nil) The contents of the given file if it exists and is + trusted, or nil otherwise. + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index d339df8479..42a5d7e7ee 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -39,6 +39,9 @@ NEW FEATURES *news-features* The following new APIs or features were added. +• |vim.secure.read()| reads a file and prompts the user if it should be + trusted and, if so, returns the file's contents. + • When using Nvim inside tmux 3.2 or later, the default clipboard provider will now copy to the system clipboard. |provider-clipboard| @@ -57,6 +60,8 @@ CHANGED FEATURES *news-changes* The following changes to existing APIs or features add new behavior. +• 'exrc' is no longer marked deprecated. + ============================================================================== REMOVED FEATURES *news-removed* diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index fd76f11046..0895d980f5 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -2264,6 +2264,20 @@ A jump table for the options with a short description can be found at |Q_op|. This option is reset when the 'paste' option is set and restored when the 'paste' option is reset. + *'exrc'* *'ex'* *'noexrc'* *'noex'* +'exrc' 'ex' boolean (default off) + global + Enables the reading of .nvimrc and .exrc files in the current + directory. + + The file is only sourced if the user indicates the file is trusted. If + it is, the SHA256 hash of the file contents and the full path of the + file are persisted to a trust database. The user is only prompted + again if the file contents change. See |vim.secure.read()|. + + This option cannot be set from a |modeline| or in the |sandbox|, for + security reasons. + *'fileencoding'* *'fenc'* *E213* 'fileencoding' 'fenc' string (default: "") local to buffer @@ -5115,19 +5129,6 @@ A jump table for the options with a short description can be found at |Q_op|. two letters (See |object-motions|). The default makes a section start at the nroff macros ".SH", ".NH", ".H", ".HU", ".nh" and ".sh". - *'secure'* *'nosecure'* *E523* -'secure' boolean (default off) - global - When on, ":autocmd", shell and write commands are not allowed in - ".nvimrc" and ".exrc" in the current directory and map commands are - displayed. Switch it off only if you know that you will not run into - problems, or when the 'exrc' option is off. On Unix this option is - only used if the ".nvimrc" or ".exrc" is not owned by you. This can be - dangerous if the systems allows users to do a "chown". You better set - 'secure' at the end of your |init.vim| then. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - *'selection'* *'sel'* 'selection' 'sel' string (default "inclusive") global diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index fe6c28c809..b5222c9ddd 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -417,6 +417,8 @@ Options: 'jumpoptions' "view" tries to restore the |mark-view| when moving through the |jumplist|, |changelist|, |alternate-file| or using |mark-motions|. 'shortmess' the "F" flag does not affect output from autocommands + 'exrc' searches for ".nvimrc" or ".exrc" files. The user is prompted whether + to trust the file. Shell: Shell output (|:!|, |:make|, …) is always routed through the UI, so it @@ -639,6 +641,9 @@ Options: *'prompt'* *'noprompt'* *'remap'* *'noremap'* *'restorescreen'* *'rs'* *'norestorescreen'* *'nors'* + *'secure'* + Everything is allowed in 'exrc' files since they must be explicitly marked + trusted. *'shelltype'* *'shortname'* *'sn'* *'noshortname'* *'nosn'* *'swapsync'* *'sws'* diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua index 0013f38d89..ad4dc20efb 100644 --- a/runtime/lua/vim/_editor.lua +++ b/runtime/lua/vim/_editor.lua @@ -36,6 +36,7 @@ for k, v in pairs({ ui = true, health = true, fs = true, + secure = true, }) do vim._submodules[k] = v end diff --git a/runtime/lua/vim/secure.lua b/runtime/lua/vim/secure.lua new file mode 100644 index 0000000000..341ff8df05 --- /dev/null +++ b/runtime/lua/vim/secure.lua @@ -0,0 +1,106 @@ +local M = {} + +--- Attempt to read the file at {path} prompting the user if the file should be +--- trusted. The user's choice is persisted in a trust database at +--- $XDG_STATE_HOME/nvim/trust. +--- +---@param path (string) Path to a file to read. +--- +---@return (string|nil) The contents of the given file if it exists and is +--- trusted, or nil otherwise. +function M.read(path) + vim.validate({ path = { path, 's' } }) + local fullpath = vim.loop.fs_realpath(vim.fs.normalize(path)) + if not fullpath then + return nil + end + + local trust = {} + do + local f = io.open(vim.fn.stdpath('state') .. '/trust', 'r') + if f then + local contents = f:read('*a') + if contents then + for line in vim.gsplit(contents, '\n') do + local hash, file = string.match(line, '^(%S+) (.+)$') + if hash and file then + trust[file] = hash + end + end + end + f:close() + end + end + + if trust[fullpath] == '!' then + -- File is denied + return nil + end + + local contents + do + local f = io.open(fullpath, 'r') + if not f then + return nil + end + contents = f:read('*a') + f:close() + end + + local hash = vim.fn.sha256(contents) + if trust[fullpath] == hash then + -- File already exists in trust database + return contents + end + + -- File either does not exist in trust database or the hash does not match + local choice = vim.fn.confirm( + string.format('%s is not trusted.', fullpath), + '&ignore\n&view\n&deny\n&allow', + 1 + ) + + if choice == 0 or choice == 1 then + -- Cancelled or ignored + return nil + elseif choice == 2 then + -- View + vim.cmd('new') + local buf = vim.api.nvim_get_current_buf() + local lines = vim.split(string.gsub(contents, '\n$', ''), '\n') + vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) + vim.bo[buf].bufhidden = 'hide' + vim.bo[buf].buftype = 'nofile' + vim.bo[buf].swapfile = false + vim.bo[buf].modeline = false + vim.bo[buf].buflisted = false + vim.bo[buf].readonly = true + vim.bo[buf].modifiable = false + return nil + elseif choice == 3 then + -- Deny + trust[fullpath] = '!' + contents = nil + elseif choice == 4 then + -- Allow + trust[fullpath] = hash + end + + do + local f, err = io.open(vim.fn.stdpath('state') .. '/trust', 'w') + if not f then + error(err) + end + + local t = {} + for p, h in pairs(trust) do + t[#t + 1] = string.format('%s %s\n', h, p) + end + f:write(table.concat(t)) + f:close() + end + + return contents +end + +return M diff --git a/scripts/gen_vimdoc.py b/scripts/gen_vimdoc.py index e77d3ea286..a720f055ed 100755 --- a/scripts/gen_vimdoc.py +++ b/scripts/gen_vimdoc.py @@ -131,6 +131,7 @@ CONFIG = { 'filetype.lua', 'keymap.lua', 'fs.lua', + 'secure.lua', ], 'files': [ 'runtime/lua/vim/_editor.lua', @@ -140,6 +141,7 @@ CONFIG = { 'runtime/lua/vim/filetype.lua', 'runtime/lua/vim/keymap.lua', 'runtime/lua/vim/fs.lua', + 'runtime/lua/vim/secure.lua', ], 'file_patterns': '*.lua', 'fn_name_prefix': '', @@ -166,6 +168,7 @@ CONFIG = { 'filetype': 'vim.filetype', 'keymap': 'vim.keymap', 'fs': 'vim.fs', + 'secure': 'vim.secure', }, 'append_only': [ 'shared.lua', diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index c6dd30e549..1efde7ef3f 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -1134,8 +1134,7 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out int scroll_save = msg_scroll; // - // Disallow shell commands from .exrc and .vimrc in current directory for - // security reasons. + // Disallow shell commands in secure mode // if (check_secure()) { return; @@ -1477,8 +1476,7 @@ filterend: /// @param flags may be SHELL_DOOUT when output is redirected void do_shell(char *cmd, int flags) { - // Disallow shell commands from .exrc and .vimrc in current directory for - // security reasons. + // Disallow shell commands in secure mode if (check_secure()) { msg_end(); return; @@ -3215,8 +3213,7 @@ void ex_z(exarg_T *eap) ex_no_reprint = true; } -/// @return true if the secure flag is set (.exrc or .vimrc in current directory) -/// and also give an error message. +/// @return true if the secure flag is set and also give an error message. /// Otherwise, return false. bool check_secure(void) { diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index e0e4fa332f..0733bcf683 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -4223,8 +4223,7 @@ theend: static void ex_autocmd(exarg_T *eap) { - // Disallow autocommands from .exrc and .vimrc in current - // directory for security reasons. + // Disallow autocommands in secure mode. if (secure) { secure = 2; eap->errmsg = _(e_curdir); diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 6c5469d020..d6bc861c09 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -2211,8 +2211,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en return FAIL; } - // Disallow writing from .exrc and .vimrc in current directory for - // security reasons. + // Disallow writing in secure mode. if (check_secure()) { return FAIL; } diff --git a/src/nvim/globals.h b/src/nvim/globals.h index 76f62fe267..130f3f6c48 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -489,8 +489,7 @@ EXTERN int stdin_fd INIT(= -1); // true when doing full-screen output, otherwise only writing some messages. EXTERN int full_screen INIT(= false); -/// Non-zero when only "safe" commands are allowed, e.g. when sourcing .exrc or -/// .vimrc in current directory. +/// Non-zero when only "safe" commands are allowed EXTERN int secure INIT(= 0); /// Non-zero when changing text and jumping to another window or editing another buffer is not @@ -864,7 +863,7 @@ EXTERN char e_api_spawn_failed[] INIT(= N_("E903: Could not spawn API job")); EXTERN char e_argreq[] INIT(= N_("E471: Argument required")); EXTERN char e_backslash[] INIT(= N_("E10: \\ should be followed by /, ? or &")); EXTERN char e_cmdwin[] INIT(= N_("E11: Invalid in command-line window; <CR> executes, CTRL-C quits")); -EXTERN char e_curdir[] INIT(= N_("E12: Command not allowed from exrc/vimrc in current dir or tag search")); +EXTERN char e_curdir[] INIT(= N_("E12: Command not allowed in secure mode in current dir or tag search")); EXTERN char e_command_too_recursive[] INIT(= N_("E169: Command too recursive")); EXTERN char e_endif[] INIT(= N_("E171: Missing :endif")); EXTERN char e_endtry[] INIT(= N_("E600: Missing :endtry")); diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 79cc3ed112..43a3b12a98 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -2193,3 +2193,27 @@ plain: kv_printf(str, "<Lua %d>", ref); return str.items; } + +char *nlua_read_secure(const char *path) +{ + lua_State *const lstate = global_lstate; + lua_getglobal(lstate, "vim"); + lua_getfield(lstate, -1, "secure"); + lua_getfield(lstate, -1, "read"); + lua_pushstring(lstate, path); + lua_call(lstate, 1, 1); + + size_t len = 0; + const char *contents = lua_tolstring(lstate, -1, &len); + char *buf = NULL; + if (contents != NULL) { + // Add one to include trailing null byte + buf = xcalloc(len + 1, sizeof(char)); + memcpy(buf, contents, len + 1); + } + + // Pop return value, "vim", and "secure" + lua_pop(lstate, 3); + + return buf; +} diff --git a/src/nvim/main.c b/src/nvim/main.c index d8570f49eb..a369ca0256 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -1989,35 +1989,22 @@ static void source_startup_scripts(const mparm_T *const parmp) do_system_initialization(); if (do_user_initialization()) { - // Read initialization commands from ".vimrc" or ".exrc" in current + // Read initialization commands from ".nvimrc" or ".exrc" in current // directory. This is only done if the 'exrc' option is set. - // Because of security reasons we disallow shell and write commands - // now, except for unix if the file is owned by the user or 'secure' - // option has been reset in environment of global "exrc" or "vimrc". // Only do this if VIMRC_FILE is not the same as vimrc file sourced in // do_user_initialization. -#if defined(UNIX) - // If vimrc file is not owned by user, set 'secure' mode. - if (!os_file_owned(VIMRC_FILE)) // NOLINT(readability/braces) -#endif - secure = p_secure; - - if (do_source(VIMRC_FILE, true, DOSO_VIMRC) == FAIL) { -#if defined(UNIX) - // if ".exrc" is not owned by user set 'secure' mode - if (!os_file_owned(EXRC_FILE)) { - secure = p_secure; - } else { - secure = 0; + char *str = nlua_read_secure(VIMRC_FILE); + if (str != NULL) { + do_source_str(str, VIMRC_FILE); + xfree(str); + } else { + str = nlua_read_secure(EXRC_FILE); + if (str != NULL) { + do_source_str(str, EXRC_FILE); + xfree(str); } -#endif - (void)do_source(EXRC_FILE, false, DOSO_NONE); } } - if (secure == 2) { - need_wait_return = true; - } - secure = 0; } TIME_MSG("sourcing vimrc file(s)"); } diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 9b10ea901e..76a646083e 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -2446,8 +2446,7 @@ void ex_abbreviate(exarg_T *eap) /// ":map" and friends. void ex_map(exarg_T *eap) { - // If we are sourcing .exrc or .vimrc in current directory we - // print the mappings for security reasons. + // If we are in a secure mode we print the mappings for security reasons. if (secure) { secure = 2; msg_outtrans(eap->cmd); diff --git a/src/nvim/memline.c b/src/nvim/memline.c index 02a7e1f697..5f21a3dd0e 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -72,7 +72,7 @@ #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/option.h" -#include "nvim/os/fs_defs.h" +#include "nvim/os/fs.h" #include "nvim/os/input.h" #include "nvim/os/os.h" #include "nvim/os/process.h" @@ -131,7 +131,8 @@ struct data_block { unsigned db_free; // free space available unsigned db_txt_start; // byte where text starts unsigned db_txt_end; // byte just after data block - linenr_T db_line_count; // number of lines in this block + // linenr_T db_line_count; + long db_line_count; // number of lines in this block unsigned db_index[1]; // index for start of line (actually bigger) // followed by empty space up to db_txt_start // followed by the text in the lines until @@ -698,6 +699,23 @@ static void add_b0_fenc(ZERO_BL *b0p, buf_T *buf) } } +/// Return true if the process with number "b0p->b0_pid" is still running. +/// "swap_fname" is the name of the swap file, if it's from before a reboot then +/// the result is false; +static bool swapfile_process_running(const ZERO_BL *b0p, const char *swap_fname) +{ + FileInfo st; + double uptime; + // If the system rebooted after when the swap file was written then the + // process can't be running now. + if (os_fileinfo(swap_fname, &st) + && uv_uptime(&uptime) == 0 + && (Timestamp)st.stat.st_mtim.tv_sec < os_time() - (Timestamp)uptime) { + return false; + } + return os_proc_running((int)char_to_long(b0p->b0_pid)); +} + /// Try to recover curbuf from the .swp file. /// /// @param checkext if true, check the extension and detect whether it is a @@ -1139,7 +1157,7 @@ void ml_recover(bool checkext) msg(_("Recovery completed. Buffer contents equals file contents.")); } msg_puts(_("\nYou may want to delete the .swp file now.")); - if (os_proc_running((int)char_to_long(b0p->b0_pid))) { + if (swapfile_process_running(b0p, fname_used)) { // Warn there could be an active Vim on the same file, the user may // want to kill it. msg_puts(_("\nNote: process STILL RUNNING: ")); @@ -1485,7 +1503,7 @@ static time_t swapfile_info(char_u *fname) if (char_to_long(b0.b0_pid) != 0L) { msg_puts(_("\n process ID: ")); msg_outnum(char_to_long(b0.b0_pid)); - if (os_proc_running((int)char_to_long(b0.b0_pid))) { + if (swapfile_process_running(&b0, (const char *)fname)) { msg_puts(_(" (STILL RUNNING)")); process_still_running = true; } @@ -1555,8 +1573,7 @@ static bool swapfile_unchanged(char *fname) } // process must be known and not running. - long pid = char_to_long(b0.b0_pid); - if (pid == 0L || os_proc_running((int)pid)) { + if (char_to_long(b0.b0_pid) == 0L || swapfile_process_running(&b0, fname)) { ret = false; } diff --git a/src/nvim/options.lua b/src/nvim/options.lua index dc0561d560..1cf8ab3253 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -2007,7 +2007,7 @@ return { }, { full_name='secure', - short_desc=N_("mode for reading .vimrc in current dir"), + short_desc=N_("No description"), type='bool', scope={'global'}, secure=true, varname='p_secure', diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index e1a2483438..db8dc04907 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -1930,7 +1930,7 @@ int do_source(char *fname, int check_other, int is_vimrc) cookie.fp = fopen_noinh_readbin(fname_exp); if (cookie.fp == NULL && check_other) { - // Try again, replacing file name ".vimrc" by "_vimrc" or vice versa, + // Try again, replacing file name ".nvimrc" by "_nvimrc" or vice versa, // and ".exrc" by "_exrc" or vice versa. p = path_tail(fname_exp); if ((*p == '.' || *p == '_') diff --git a/src/nvim/testdir/check.vim b/src/nvim/testdir/check.vim index 8a1080a2f3..61d3a99a67 100644 --- a/src/nvim/testdir/check.vim +++ b/src/nvim/testdir/check.vim @@ -90,6 +90,14 @@ func CheckUnix() endif endfunc +" Command to check for running on Linux +command CheckLinux call CheckLinux() +func CheckLinux() + if !has('linux') + throw 'Skipped: only works on Linux' + endif +endfunc + " Command to check that making screendumps is supported. " Caller must source screendump.vim command CheckScreendump call CheckScreendump() diff --git a/src/nvim/testdir/runtest.vim b/src/nvim/testdir/runtest.vim index ce23141c7a..a1b04a4601 100644 --- a/src/nvim/testdir/runtest.vim +++ b/src/nvim/testdir/runtest.vim @@ -174,7 +174,12 @@ func RunTheTest(test) if a:test =~ 'Test_nocatch_' " Function handles errors itself. This avoids skipping commands after the " error. + let g:skipped_reason = '' exe 'call ' . a:test + if g:skipped_reason != '' + call add(s:messages, ' Skipped') + call add(s:skipped, 'SKIPPED ' . a:test . ': ' . g:skipped_reason) + endif else try let s:test = a:test diff --git a/src/nvim/testdir/test_diffmode.vim b/src/nvim/testdir/test_diffmode.vim index 0de5310735..d83cd505a6 100644 --- a/src/nvim/testdir/test_diffmode.vim +++ b/src/nvim/testdir/test_diffmode.vim @@ -243,6 +243,36 @@ func Test_diffput_two() bwipe! b endfunc +" Test for :diffget/:diffput with a range that is inside a diff chunk +func Test_diffget_diffput_range() + call setline(1, range(1, 10)) + new + call setline(1, range(11, 20)) + windo diffthis + 3,5diffget + call assert_equal(['13', '14', '15'], getline(3, 5)) + call setline(1, range(1, 10)) + 4,8diffput + wincmd p + call assert_equal(['13', '4', '5', '6', '7', '8', '19'], getline(3, 9)) + %bw! +endfunc + +" Test for :diffget/:diffput with an empty buffer and a non-empty buffer +func Test_diffget_diffput_empty_buffer() + %d _ + new + call setline(1, 'one') + windo diffthis + diffget + call assert_equal(['one'], getline(1, '$')) + %d _ + diffput + wincmd p + call assert_equal([''], getline(1, '$')) + %bw! +endfunc + " :diffput and :diffget completes names of buffers which " are in diff mode and which are different then current buffer. " No completion when the current window is not in diff mode. @@ -645,7 +675,11 @@ func Test_diffexpr() call assert_equal(normattr, screenattr(1, 1)) call assert_equal(normattr, screenattr(2, 1)) call assert_notequal(normattr, screenattr(3, 1)) + diffoff! + " Try using an non-existing function for 'diffexpr'. + set diffexpr=NewDiffFunc() + call assert_fails('windo diffthis', ['E117:', 'E97:']) diffoff! %bwipe! set diffexpr& diffopt& @@ -1316,6 +1350,89 @@ func Test_diff_filler_cursorcolumn() call delete('Xtest_diff_cuc') endfunc +" Test for adding/removing lines inside diff chunks, between diff chunks +" and before diff chunks +func Test_diff_modify_chunks() + enew! + let w2_id = win_getid() + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + new + let w1_id = win_getid() + call setline(1, ['a', '2', '3', 'd', 'e', 'f', '7', '8', 'i']) + windo diffthis + + " remove a line between two diff chunks and create a new diff chunk + call win_gotoid(w2_id) + 5d + call win_gotoid(w1_id) + call diff_hlID(5, 1)->synIDattr('name')->assert_equal('DiffAdd') + + " add a line between two diff chunks + call win_gotoid(w2_id) + normal! 4Goe + call win_gotoid(w1_id) + call diff_hlID(4, 1)->synIDattr('name')->assert_equal('') + call diff_hlID(5, 1)->synIDattr('name')->assert_equal('') + + " remove all the lines in a diff chunk. + call win_gotoid(w2_id) + 7,8d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', '', '', '', 'DiffAdd', + \ 'DiffAdd', ''], hl) + + " remove lines from one diff chunk to just before the next diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 2,6d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', 'DiffAdd', 'DiffAdd', + \ 'DiffAdd', 'DiffAdd', 'DiffAdd', ''], hl) + + " remove lines just before the top of a diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 5,6d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', '', 'DiffText', 'DiffText', + \ 'DiffAdd', 'DiffAdd', ''], hl) + + " remove line after the end of a diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 4d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', 'DiffAdd', '', '', 'DiffText', + \ 'DiffText', ''], hl) + + " remove lines starting from the end of one diff chunk and ending inside + " another diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 4,7d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', 'DiffText', 'DiffAdd', + \ 'DiffAdd', 'DiffAdd', 'DiffAdd', ''], hl) + + " removing the only remaining diff chunk should make the files equal + call win_gotoid(w2_id) + call setline(1, ['a', '2', '3', 'x', 'd', 'e', 'f', 'x', '7', '8', 'i']) + 8d + let hl = range(1, 10)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', '', '', 'DiffAdd', '', '', '', '', '', ''], hl) + call win_gotoid(w2_id) + 4d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', '', '', '', '', '', '', '', ''], hl) + + %bw! +endfunc func Test_diff_binary() CheckScreendump diff --git a/src/nvim/testdir/test_excmd.vim b/src/nvim/testdir/test_excmd.vim index 42b1f8ca48..44bed890f5 100644 --- a/src/nvim/testdir/test_excmd.vim +++ b/src/nvim/testdir/test_excmd.vim @@ -78,6 +78,14 @@ func Test_file_cmd() call assert_fails('3file', 'E474:') call assert_fails('0,0file', 'E474:') call assert_fails('0file abc', 'E474:') + if !has('win32') + " Change the name of the buffer to the same name + new Xfile1 + file Xfile1 + call assert_equal('Xfile1', @%) + call assert_equal('Xfile1', @#) + bw! + endif endfunc " Test for the :drop command diff --git a/src/nvim/testdir/test_prompt_buffer.vim b/src/nvim/testdir/test_prompt_buffer.vim index 9b8a776c95..b8f6c5240c 100644 --- a/src/nvim/testdir/test_prompt_buffer.vim +++ b/src/nvim/testdir/test_prompt_buffer.vim @@ -180,6 +180,8 @@ func Test_prompt_buffer_edit() call assert_beeps('normal! S') call assert_beeps("normal! \<C-A>") call assert_beeps("normal! \<C-X>") + call assert_beeps("normal! dp") + call assert_beeps("normal! do") " pressing CTRL-W in the prompt buffer should trigger the window commands call assert_equal(1, winnr()) exe "normal A\<C-W>\<C-W>" diff --git a/src/nvim/testdir/test_recover.vim b/src/nvim/testdir/test_recover.vim index fc073cacd2..92e22687af 100644 --- a/src/nvim/testdir/test_recover.vim +++ b/src/nvim/testdir/test_recover.vim @@ -1,5 +1,7 @@ " Test :recover +source check.vim + func Test_recover_root_dir() " This used to access invalid memory. split Xtest @@ -23,6 +25,21 @@ func Test_recover_root_dir() set dir& endfunc +" Make a copy of the current swap file to "Xswap". +" Return the name of the swap file. +func CopySwapfile() + preserve + " get the name of the swap file + let swname = split(execute("swapname"))[0] + let swname = substitute(swname, '[[:blank:][:cntrl:]]*\(.\{-}\)[[:blank:][:cntrl:]]*$', '\1', '') + " make a copy of the swap file in Xswap + set binary + exe 'sp ' . swname + w! Xswap + set nobinary + return swname +endfunc + " Inserts 10000 lines with text to fill the swap file with two levels of pointer " blocks. Then recovers from the swap file and checks all text is restored. " @@ -40,15 +57,9 @@ func Test_swap_file() let i += 1 endwhile $delete - preserve - " get the name of the swap file - let swname = split(execute("swapname"))[0] - let swname = substitute(swname, '[[:blank:][:cntrl:]]*\(.\{-}\)[[:blank:][:cntrl:]]*$', '\1', '') - " make a copy of the swap file in Xswap - set binary - exe 'sp ' . swname - w! Xswap - set nobinary + + let swname = CopySwapfile() + new only! bwipe! Xtest @@ -69,3 +80,388 @@ func Test_swap_file() set undolevels& enew! | only endfunc + +func Test_nocatch_process_still_running() + let g:skipped_reason = 'test_override() is N/A' + return + " sysinfo.uptime probably only works on Linux + if !has('linux') + let g:skipped_reason = 'only works on Linux' + return + endif + " the GUI dialog can't be handled + if has('gui_running') + let g:skipped_reason = 'only works in the terminal' + return + endif + + " don't intercept existing swap file here + au! SwapExists + + " Edit a file and grab its swapfile. + edit Xswaptest + call setline(1, ['a', 'b', 'c']) + let swname = CopySwapfile() + + " Forget we edited this file + new + only! + bwipe! Xswaptest + + call rename('Xswap', swname) + call feedkeys('e', 'tL') + redir => editOutput + edit Xswaptest + redir END + call assert_match('E325: ATTENTION', editOutput) + call assert_match('file name: .*Xswaptest', editOutput) + call assert_match('process ID: \d* (STILL RUNNING)', editOutput) + + " Forget we edited this file + new + only! + bwipe! Xswaptest + + " pretend we rebooted + call test_override("uptime", 0) + sleep 1 + + call feedkeys('e', 'tL') + redir => editOutput + edit Xswaptest + redir END + call assert_match('E325: ATTENTION', editOutput) + call assert_notmatch('(STILL RUNNING)', editOutput) + + call test_override("ALL", 0) + call delete(swname) +endfunc + +" Test for :recover with multiple swap files +func Test_recover_multiple_swap_files() + CheckUnix + new Xfile1 + call setline(1, ['a', 'b', 'c']) + preserve + let b = readblob(swapname('')) + call writefile(b, '.Xfile1.swm') + call writefile(b, '.Xfile1.swn') + call writefile(b, '.Xfile1.swo') + %bw! + call feedkeys(":recover Xfile1\<CR>3\<CR>q", 'xt') + call assert_equal(['a', 'b', 'c'], getline(1, '$')) + " try using out-of-range number to select a swap file + bw! + call feedkeys(":recover Xfile1\<CR>4\<CR>q", 'xt') + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + call feedkeys(":recover Xfile1\<CR>0\<CR>q", 'xt') + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + + call delete('.Xfile1.swm') + call delete('.Xfile1.swn') + call delete('.Xfile1.swo') +endfunc + +" Test for :recover using an empty swap file +func Test_recover_empty_swap_file() + CheckUnix + call writefile([], '.Xfile1.swp') + let msg = execute('recover Xfile1') + call assert_match('Unable to read block 0 from .Xfile1.swp', msg) + call assert_equal('Xfile1', @%) + bw! + + " make sure there are no old swap files laying around + for f in glob('.sw?', 0, 1) + call delete(f) + endfor + + " :recover from an empty buffer + call assert_fails('recover', 'E305:') + call delete('.Xfile1.swp') +endfunc + +" Test for :recover using a corrupted swap file +" Refer to the comments in the memline.c file for the swap file headers +" definition. +func Test_recover_corrupted_swap_file() + CheckUnix + + " recover using a partial swap file + call writefile(0z1234, '.Xfile1.swp') + call assert_fails('recover Xfile1', 'E295:') + bw! + + " recover using invalid content in the swap file + call writefile([repeat('1', 2*1024)], '.Xfile1.swp') + call assert_fails('recover Xfile1', 'E307:') + call delete('.Xfile1.swp') + + " :recover using a swap file with a corrupted header + edit Xfile1 + preserve + let sn = swapname('') + let b = readblob(sn) + let save_b = copy(b) + bw! + + " Not all fields are written in a system-independent manner. Detect whether + " the test is running on a little or big-endian system, so the correct + " corruption values can be set. + " The B0_MAGIC_LONG field may be 32-bit or 64-bit, depending on the system, + " even though the value stored is only 32-bits. Therefore, need to check + " both the high and low 32-bits to compute these values. + let little_endian = (b[1008:1011] == 0z33323130) || (b[1012:1015] == 0z33323130) + let system_64bit = little_endian ? (b[1012:1015] == 0z00000000) : (b[1008:1011] == 0z00000000) + + " clear the B0_MAGIC_LONG field + if system_64bit + let b[1008:1015] = 0z00000000.00000000 + else + let b[1008:1011] = 0z00000000 + endif + call writefile(b, sn) + let msg = execute('recover Xfile1') + call assert_match('the file has been damaged', msg) + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + + " reduce the page size + let b = copy(save_b) + let b[12:15] = 0z00010000 + call writefile(b, sn) + let msg = execute('recover Xfile1') + call assert_match('page size is smaller than minimum value', msg) + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + + " clear the pointer ID + let b = copy(save_b) + let b[4096:4097] = 0z0000 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E310:') + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + + " set the number of pointers in a pointer block to zero + let b = copy(save_b) + let b[4098:4099] = 0z0000 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???EMPTY BLOCK'], getline(1, '$')) + bw! + + " set the block number in a pointer entry to a negative number + let b = copy(save_b) + if system_64bit + let b[4104:4111] = little_endian ? 0z00000000.00000080 : 0z80000000.00000000 + else + let b[4104:4107] = little_endian ? 0z00000080 : 0z80000000 + endif + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???LINES MISSING'], getline(1, '$')) + bw! + + " clear the data block ID + let b = copy(save_b) + let b[8192:8193] = 0z0000 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???BLOCK MISSING'], getline(1, '$')) + bw! + + " set the number of lines in the data block to zero + let b = copy(save_b) + if system_64bit + let b[8208:8215] = 0z00000000.00000000 + else + let b[8208:8211] = 0z00000000 + endif + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['??? from here until ???END lines may have been inserted/deleted', + \ '???END'], getline(1, '$')) + bw! + + " use an invalid text start for the lines in a data block + let b = copy(save_b) + if system_64bit + let b[8216:8219] = 0z00000000 + else + let b[8212:8215] = 0z00000000 + endif + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???'], getline(1, '$')) + bw! + + " use an incorrect text end (db_txt_end) for the data block + let b = copy(save_b) + let b[8204:8207] = little_endian ? 0z80000000 : 0z00000080 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['??? from here until ???END lines may be messed up', '', + \ '???END'], getline(1, '$')) + bw! + + " remove the data block + let b = copy(save_b) + call writefile(b[:8191], sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???MANY LINES MISSING'], getline(1, '$')) + + bw! + call delete(sn) +endfunc + +" Test for :recover using an encrypted swap file +func Test_recover_encrypted_swap_file() + CheckFeature cryptv + CheckUnix + + " Recover an encrypted file from the swap file without the original file + new Xfile1 + call feedkeys(":X\<CR>vim\<CR>vim\<CR>", 'xt') + call setline(1, ['aaa', 'bbb', 'ccc']) + preserve + let b = readblob('.Xfile1.swp') + call writefile(b, '.Xfile1.swm') + bw! + call feedkeys(":recover Xfile1\<CR>vim\<CR>\<CR>", 'xt') + call assert_equal(['aaa', 'bbb', 'ccc'], getline(1, '$')) + bw! + call delete('.Xfile1.swm') + + " Recover an encrypted file from the swap file with the original file + new Xfile1 + call feedkeys(":X\<CR>vim\<CR>vim\<CR>", 'xt') + call setline(1, ['aaa', 'bbb', 'ccc']) + update + call setline(1, ['111', '222', '333']) + preserve + let b = readblob('.Xfile1.swp') + call writefile(b, '.Xfile1.swm') + bw! + call feedkeys(":recover Xfile1\<CR>vim\<CR>\<CR>", 'xt') + call assert_equal(['111', '222', '333'], getline(1, '$')) + call assert_true(&modified) + bw! + call delete('.Xfile1.swm') + call delete('Xfile1') +endfunc + +" Test for :recover using a unreadable swap file +func Test_recover_unreadble_swap_file() + CheckUnix + CheckNotRoot + new Xfile1 + let b = readblob('.Xfile1.swp') + call writefile(b, '.Xfile1.swm') + bw! + call setfperm('.Xfile1.swm', '-w-------') + call assert_fails('recover Xfile1', 'E306:') + call delete('.Xfile1.swm') +endfunc + +" Test for using :recover when the original file and the swap file have the +" same contents. +func Test_recover_unmodified_file() + CheckUnix + call writefile(['aaa', 'bbb', 'ccc'], 'Xfile1') + edit Xfile1 + preserve + let b = readblob('.Xfile1.swp') + %bw! + call writefile(b, '.Xfile1.swz') + let msg = execute('recover Xfile1') + call assert_equal(['aaa', 'bbb', 'ccc'], getline(1, '$')) + call assert_false(&modified) + call assert_match('Buffer contents equals file contents', msg) + bw! + call delete('Xfile1') + call delete('.Xfile1.swz') +endfunc + +" Test for recovering a file when editing a symbolically linked file +func Test_recover_symbolic_link() + CheckUnix + call writefile(['aaa', 'bbb', 'ccc'], 'Xfile1') + silent !ln -s Xfile1 Xfile2 + edit Xfile2 + call assert_equal('.Xfile1.swp', fnamemodify(swapname(''), ':t')) + preserve + let b = readblob('.Xfile1.swp') + %bw! + call writefile([], 'Xfile1') + call writefile(b, '.Xfile1.swp') + silent! recover Xfile2 + call assert_equal(['aaa', 'bbb', 'ccc'], getline(1, '$')) + call assert_true(&modified) + update + %bw! + call assert_equal(['aaa', 'bbb', 'ccc'], readfile('Xfile1')) + call delete('Xfile1') + call delete('Xfile2') + call delete('.Xfile1.swp') +endfunc + +" Test for recovering a file when an autocmd moves the cursor to an invalid +" line. This used to result in an internal error (E315) which is fixed +" by 8.2.2966. +func Test_recover_invalid_cursor_pos() + call writefile([], 'Xfile1') + edit Xfile1 + preserve + let b = readblob('.Xfile1.swp') + bw! + augroup Test + au! + au BufReadPost Xfile1 normal! 3G + augroup END + call writefile(range(1, 3), 'Xfile1') + call writefile(b, '.Xfile1.swp') + try + recover Xfile1 + catch /E308:/ + " this test is for the :E315 internal error. + " ignore the 'E308: Original file may have been changed' error + endtry + redraw! + augroup Test + au! + augroup END + augroup! Test + call delete('Xfile1') + call delete('.Xfile1.swp') +endfunc + +" Test for recovering a buffer without a name +func Test_noname_buffer() + new + call setline(1, ['one', 'two']) + preserve + let sn = swapname('') + let b = readblob(sn) + bw! + call writefile(b, sn) + exe "recover " .. sn + call assert_equal(['one', 'two'], getline(1, '$')) + call delete(sn) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_startup.vim b/src/nvim/testdir/test_startup.vim index f9f7c5b492..42467c5508 100644 --- a/src/nvim/testdir/test_startup.vim +++ b/src/nvim/testdir/test_startup.vim @@ -1024,6 +1024,7 @@ endfunc " Test for using the 'exrc' option func Test_exrc() + throw 'Skipped: Nvim requires user input for the exrc option' let after =<< trim [CODE] call assert_equal(1, &exrc) call assert_equal(1, &secure) diff --git a/src/nvim/testdir/test_swap.vim b/src/nvim/testdir/test_swap.vim index 284579b084..cf46b4c5bd 100644 --- a/src/nvim/testdir/test_swap.vim +++ b/src/nvim/testdir/test_swap.vim @@ -501,6 +501,81 @@ func Test_swap_auto_delete() augroup! test_swap_recover_ext endfunc +" Test for renaming a buffer when the swap file is deleted out-of-band +func Test_missing_swap_file() + CheckUnix + new Xfile2 + call delete(swapname('')) + call assert_fails('file Xfile3', 'E301:') + call assert_equal('Xfile3', bufname()) + call assert_true(bufexists('Xfile2')) + call assert_true(bufexists('Xfile3')) + %bw! +endfunc + +" Test for :preserve command +func Test_preserve() + new Xfile4 + setlocal noswapfile + call assert_fails('preserve', 'E313:') + bw! +endfunc + +" Test for the v:swapchoice variable +func Test_swapchoice() + call writefile(['aaa', 'bbb'], 'Xfile5') + edit Xfile5 + preserve + let swapfname = swapname('') + let b = readblob(swapfname) + bw! + call writefile(b, swapfname) + + autocmd! SwapExists + + " Test for v:swapchoice = 'o' (readonly) + augroup test_swapchoice + autocmd! + autocmd SwapExists * let v:swapchoice = 'o' + augroup END + edit Xfile5 + call assert_true(&readonly) + call assert_equal(['aaa', 'bbb'], getline(1, '$')) + %bw! + call assert_true(filereadable(swapfname)) + + " Test for v:swapchoice = 'a' (abort) + augroup test_swapchoice + autocmd! + autocmd SwapExists * let v:swapchoice = 'a' + augroup END + try + edit Xfile5 + catch /^Vim:Interrupt$/ + endtry + call assert_equal('', @%) + call assert_true(bufexists('Xfile5')) + %bw! + call assert_true(filereadable(swapfname)) + + " Test for v:swapchoice = 'd' (delete) + augroup test_swapchoice + autocmd! + autocmd SwapExists * let v:swapchoice = 'd' + augroup END + edit Xfile5 + call assert_equal('Xfile5', @%) + %bw! + call assert_false(filereadable(swapfname)) + + call delete('Xfile5') + call delete(swapfname) + augroup test_swapchoice + autocmd! + augroup END + augroup! test_swapchoice +endfunc + func Test_no_swap_file() call assert_equal("\nNo swap file", execute('swapname')) endfunc diff --git a/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua b/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua index 69404039ff..8eed00c973 100644 --- a/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua +++ b/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua @@ -1,12 +1,14 @@ local Screen = require('test.functional.ui.screen') local helpers = require('test.functional.helpers')(after_each) local lfs = require('lfs') +local luv = require('luv') local eq, eval, expect, exec = helpers.eq, helpers.eval, helpers.expect, helpers.exec local assert_alive = helpers.assert_alive local clear = helpers.clear local command = helpers.command local feed = helpers.feed +local funcs = helpers.funcs local nvim_prog = helpers.nvim_prog local ok = helpers.ok local rmdir = helpers.rmdir @@ -100,7 +102,7 @@ describe('swapfile detection', function() -- attempt to create a swapfile in different directory. local init = [[ set directory^=]]..swapdir:gsub([[\]], [[\\]])..[[// - set swapfile fileformat=unix undolevels=-1 hidden + set swapfile fileformat=unix nomodified undolevels=-1 nohidden ]] before_each(function() nvim0 = spawn(new_argv()) @@ -263,4 +265,79 @@ describe('swapfile detection', function() ]]) nvim2:close() end) + + -- oldtest: Test_nocatch_process_still_running() + it('allows deleting swapfile created before boot vim-patch:8.2.2586', function() + local screen = Screen.new(75, 30) + screen:set_default_attr_ids({ + [0] = {bold = true, foreground = Screen.colors.Blue}, -- NonText + [1] = {bold = true, foreground = Screen.colors.SeaGreen}, -- MoreMsg + [2] = {background = Screen.colors.Red, foreground = Screen.colors.White}, -- ErrorMsg + }) + screen:attach() + + exec(init) + command('set nohidden') + + exec([=[ + " Make a copy of the current swap file to "Xswap". + " Return the name of the swap file. + func CopySwapfile() + preserve + " get the name of the swap file + let swname = split(execute("swapname"))[0] + let swname = substitute(swname, '[[:blank:][:cntrl:]]*\(.\{-}\)[[:blank:][:cntrl:]]*$', '\1', '') + " make a copy of the swap file in Xswap + set binary + exe 'sp ' . fnameescape(swname) + w! Xswap + set nobinary + return swname + endfunc + ]=]) + + -- Edit a file and grab its swapfile. + exec([[ + edit Xswaptest + call setline(1, ['a', 'b', 'c']) + ]]) + local swname = funcs.CopySwapfile() + + -- Forget we edited this file + exec([[ + new + only! + bwipe! Xswaptest + ]]) + + os.rename('Xswap', swname) + + feed(':edit Xswaptest<CR>') + screen:expect({any = table.concat({ + pesc('{2:E325: ATTENTION}'), + 'file name: .*Xswaptest', + 'process ID: %d* %(STILL RUNNING%)', + pesc('{1:[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: }^'), + }, '.*')}) + + feed('e') + + -- Forget we edited this file + exec([[ + new + only! + bwipe! Xswaptest + ]]) + + -- pretend that the swapfile was created before boot + lfs.touch(swname, os.time() - luv.uptime() - 10) + + feed(':edit Xswaptest<CR>') + screen:expect({any = table.concat({ + pesc('{2:E325: ATTENTION}'), + pesc('{1:[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort: }^'), + }, '.*')}) + + feed('e') + end) end) diff --git a/test/functional/lua/secure_spec.lua b/test/functional/lua/secure_spec.lua new file mode 100644 index 0000000000..c348526d65 --- /dev/null +++ b/test/functional/lua/secure_spec.lua @@ -0,0 +1,171 @@ +local helpers = require('test.functional.helpers')(after_each) +local Screen = require('test.functional.ui.screen') + +local eq = helpers.eq +local clear = helpers.clear +local command = helpers.command +local pathsep = helpers.get_pathsep() +local iswin = helpers.iswin() +local curbufmeths = helpers.curbufmeths +local exec_lua = helpers.exec_lua +local feed_command = helpers.feed_command +local feed = helpers.feed +local funcs = helpers.funcs +local pcall_err = helpers.pcall_err + +describe('vim.secure', function() + describe('read()', function() + local xstate = 'Xstate' + + setup(function() + helpers.mkdir_p(xstate .. pathsep .. (iswin and 'nvim-data' or 'nvim')) + end) + + teardown(function() + helpers.rmdir(xstate) + end) + + before_each(function() + helpers.write_file('Xfile', [[ + let g:foobar = 42 + ]]) + clear{env={XDG_STATE_HOME=xstate}} + end) + + after_each(function() + os.remove('Xfile') + helpers.rmdir(xstate) + end) + + it('works', function() + local screen = Screen.new(80, 8) + screen:attach() + screen:set_default_attr_ids({ + [1] = {bold = true, foreground = Screen.colors.Blue1}, + [2] = {bold = true, reverse = true}, + [3] = {bold = true, foreground = Screen.colors.SeaGreen}, + [4] = {reverse = true}, + }) + + local cwd = funcs.getcwd() + + -- Need to use feed_command instead of exec_lua because of the confirmation prompt + feed_command([[lua vim.secure.read('Xfile')]]) + screen:expect{grid=[[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {2: }| + :lua vim.secure.read('Xfile') | + {3:]] .. cwd .. pathsep .. [[Xfile is untrusted}{MATCH:%s+}| + {3:[i]gnore, (v)iew, (d)eny, (a)llow: }^ | + ]]} + feed('d') + screen:expect{grid=[[ + ^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + | + ]]} + + local trust = helpers.read_file(funcs.stdpath('state') .. pathsep .. 'trust') + eq(string.format('! %s', cwd .. pathsep .. 'Xfile'), vim.trim(trust)) + eq(helpers.NIL, exec_lua([[return vim.secure.read('Xfile')]])) + + os.remove(funcs.stdpath('state') .. pathsep .. 'trust') + + feed_command([[lua vim.secure.read('Xfile')]]) + screen:expect{grid=[[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {2: }| + :lua vim.secure.read('Xfile') | + {3:]] .. cwd .. pathsep .. [[Xfile is untrusted}{MATCH:%s+}| + {3:[i]gnore, (v)iew, (d)eny, (a)llow: }^ | + ]]} + feed('a') + screen:expect{grid=[[ + ^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + | + ]]} + + local hash = funcs.sha256(helpers.read_file('Xfile')) + trust = helpers.read_file(funcs.stdpath('state') .. pathsep .. 'trust') + eq(string.format('%s %s', hash, cwd .. pathsep .. 'Xfile'), vim.trim(trust)) + eq(helpers.NIL, exec_lua([[vim.secure.read('Xfile')]])) + + os.remove(funcs.stdpath('state') .. pathsep .. 'trust') + + feed_command([[lua vim.secure.read('Xfile')]]) + screen:expect{grid=[[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {2: }| + :lua vim.secure.read('Xfile') | + {3:]] .. cwd .. pathsep .. [[Xfile is untrusted}{MATCH:%s+}| + {3:[i]gnore, (v)iew, (d)eny, (a)llow: }^ | + ]]} + feed('i') + screen:expect{grid=[[ + ^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + | + ]]} + + -- Trust database is not updated + trust = helpers.read_file(funcs.stdpath('state') .. pathsep .. 'trust') + eq(nil, trust) + + feed_command([[lua vim.secure.read('Xfile')]]) + screen:expect{grid=[[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {2: }| + :lua vim.secure.read('Xfile') | + {3:]] .. cwd .. pathsep .. [[Xfile is untrusted}{MATCH:%s+}| + {3:[i]gnore, (v)iew, (d)eny, (a)llow: }^ | + ]]} + feed('v') + screen:expect{grid=[[ + ^ let g:foobar = 42 | + {1:~ }| + {1:~ }| + {2:]] .. cwd .. pathsep .. [[Xfile [RO]{MATCH:%s+}| + | + {1:~ }| + {4:[No Name] }| + | + ]]} + + -- Trust database is not updated + trust = helpers.read_file(funcs.stdpath('state') .. pathsep .. 'trust') + eq(nil, trust) + + -- Cannot write file + pcall_err(command, 'write') + eq(false, curbufmeths.get_option('modifiable')) + end) + end) +end) |