Merge pull request #7996 from thalesmg/fix-import-data-outside-bkp

fix(backup): accept files outside `data/dir` when importing
This commit is contained in:
Thales Macedo Garitezi 2022-05-23 10:36:07 -03:00 committed by GitHub
commit cfd009abe1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 6 deletions

View File

@ -660,13 +660,19 @@ backup_files(Dir) ->
look_up_file(Filename) when is_binary(Filename) ->
look_up_file(binary_to_list(Filename));
look_up_file(Filename) ->
DefOnNotFound = fun(_Filename) -> {error, not_found} end,
do_look_up_file(Filename, DefOnNotFound).
do_look_up_file(Filename, OnNotFound) when is_binary(Filename) ->
do_look_up_file(binary_to_list(Filename), OnNotFound);
do_look_up_file(Filename, OnNotFound) ->
Filter =
fun(MaybeFile) ->
filename:basename(MaybeFile) == Filename
end,
case lists:filter(Filter, backup_files()) of
[] ->
{error, not_found};
OnNotFound(Filename);
List ->
{ok, hd(List)}
end.
@ -810,19 +816,26 @@ import(Filename, OverridesJson) ->
-spec(check_import_json(binary() | string()) -> {ok, map()} | {error, term()}).
check_import_json(Filename) ->
OnNotFound =
fun(F) ->
case filelib:is_file(F) of
true -> {ok, F};
false -> {error, not_found}
end
end,
FunList = [
fun look_up_file/1,
fun(F) -> do_look_up_file(F, OnNotFound) end,
fun(F) -> file:read_file(F) end,
fun check_json/1
],
check_import_json(Filename, FunList).
do_check_import_json(Filename, FunList).
check_import_json(Res, []) ->
do_check_import_json(Res, []) ->
{ok, Res};
check_import_json(Acc, [Fun | FunList]) ->
do_check_import_json(Acc, [Fun | FunList]) ->
case Fun(Acc) of
{ok, Next} ->
check_import_json(Next, FunList);
do_check_import_json(Next, FunList);
{error, Reason} ->
{error, Reason}
end.

View File

@ -72,6 +72,13 @@ init_per_testcase(t_plugins_cmd, Config) ->
meck:expect(emqx_plugins, reload, fun(_) -> ok end),
mock_print(),
Config;
init_per_testcase(t_import_outside_backup_dir, Config) ->
RandomName = emqx_guid:to_hexstr(emqx_guid:gen()),
Filepath = "/tmp/" ++ binary_to_list(RandomName) ++ ".json",
FakeData = #{version => "4.4"},
ok = file:write_file(Filepath, emqx_json:encode(FakeData)),
[ {tmp_file, Filepath}
| Config];
init_per_testcase(_Case, Config) ->
mock_print(),
Config.
@ -79,6 +86,10 @@ init_per_testcase(_Case, Config) ->
end_per_testcase(t_plugins_cmd, _Config) ->
meck:unload(emqx_plugins),
unmock_print();
end_per_testcase(t_import_outside_backup_dir, Config) ->
Filepath = ?config(tmp_file, Config),
file:delete(Filepath),
ok;
end_per_testcase(_Case, _Config) ->
unmock_print().
@ -384,6 +395,12 @@ t_backup_file(_)->
{error, not_found} = emqx_mgmt_data_backup:delete_backup_file(BadFilename),
ok.
t_import_outside_backup_dir(Config) ->
Filepath = ?config(tmp_file, Config),
Env = "{}",
?assertEqual(ok, emqx_mgmt_data_backup:import(Filepath, Env)),
ok.
mock_print() ->
ok = safe_unmeck(emqx_ctl),
meck:new(emqx_ctl, [non_strict, passthrough]),