Merge pull request #11004 from paulozulato/fix-rewrite-wildcard

fix(rewrite): avoid wildcards on destination topic on publish
This commit is contained in:
Thales Macedo Garitezi 2023-06-16 09:57:46 -03:00 committed by GitHub
commit 8801ae9e5a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 79 additions and 0 deletions

View File

@ -36,6 +36,7 @@ roots() ->
array("rewrite", #{
desc => "List of topic rewrite rules.",
importance => ?IMPORTANCE_HIDDEN,
validator => fun rewrite_validator/1,
default => []
}),
array("topic_metrics", #{
@ -45,6 +46,37 @@ roots() ->
})
].
rewrite_validator(Rules) ->
case
lists:foldl(
fun
(#{<<"action">> := subscribe}, Acc) ->
Acc;
(#{<<"dest_topic">> := DestTopic}, InvalidAcc) ->
try
true = emqx_topic:validate(name, DestTopic),
InvalidAcc
catch
_:_ ->
[DestTopic | InvalidAcc]
end
end,
[],
Rules
)
of
[] ->
ok;
InvalidTopics ->
{
error,
#{
msg => "cannot_use_wildcard_for_destination_topic",
invalid_topics => InvalidTopics
}
}
end.
fields("delayed") ->
[
{enable, ?HOCON(boolean(), #{default => true, desc => ?DESC(enable)})},

View File

@ -95,6 +95,52 @@ t_mqtt_topic_rewrite_limit(_) ->
)
).
t_mqtt_topic_rewrite_wildcard(_) ->
BadRules = [
#{
<<"source_topic">> => <<"test/#">>,
<<"re">> => <<"^test/(.+)$">>,
<<"dest_topic">> => <<"bad/test/#">>
},
#{
<<"source_topic">> => <<"test/#">>,
<<"re">> => <<"^test/(.+)$">>,
<<"dest_topic">> => <<"bad/#/test">>
},
#{
<<"source_topic">> => <<"test/#">>,
<<"re">> => <<"^test/(.+)$">>,
<<"dest_topic">> => <<"bad/test/+">>
},
#{
<<"source_topic">> => <<"test/#">>,
<<"re">> => <<"^test/(.+)$">>,
<<"dest_topic">> => <<"bad/+/test">>
}
],
Rules = lists:flatten(
lists:map(
fun(Rule) ->
[Rule#{<<"action">> => <<"publish">>}, Rule#{<<"action">> => <<"all">>}]
end,
BadRules
)
),
lists:foreach(
fun(Rule) ->
?assertMatch(
{ok, 500, _},
request(
put,
uri(["mqtt", "topic_rewrite"]),
[Rule]
)
)
end,
Rules
).
%%------------------------------------------------------------------------------
%% Helpers
%%------------------------------------------------------------------------------

View File

@ -0,0 +1 @@
Do not allow wildcards for destination topic in rewrite rules.