A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(gateway): split push job fields and images, drop tests
Hampusf53deb9b6945
diff --git a/fluxer_gateway/src/push/push_image_url.erl b/fluxer_gateway/src/push/push_image_url.erlnew file mode 100644index 000000000..c363aaf1b--- /dev/null+++ b/fluxer_gateway/src/push/push_image_url.erl@@ -0,0 +1,118 @@+%% SPDX-License-Identifier: AGPL-3.0-or-later++-module(push_image_url).+-typing([eqwalizer]).++-export([extract/1]).++-define(MAX_IMAGE_URL_BYTES, 1024).++-spec extract(map()) -> binary() | undefined.+extract(MessageData) ->+ bounded_image_url(resolve_image_url(MessageData)).++-spec resolve_image_url(map()) -> binary() | undefined.+resolve_image_url(MessageData) ->+ case extract_attachment_image_url(maps:get(<<"attachments">>, MessageData, [])) of+ undefined -> extract_embed_image_url(maps:get(<<"embeds">>, MessageData, []));+ ImageUrl -> ImageUrl+ end.++-spec bounded_image_url(binary() | undefined) -> binary() | undefined.+bounded_image_url(ImageUrl) when+ is_binary(ImageUrl), byte_size(ImageUrl) =< ?MAX_IMAGE_URL_BYTES+->+ ImageUrl;+bounded_image_url(_ImageUrl) ->+ undefined.++-spec extract_attachment_image_url(term()) -> binary() | undefined.+extract_attachment_image_url([Attachment | Rest]) when is_map(Attachment) ->+ case check_media_safe_url(Attachment) of+ {ok, Url} -> Url;+ unsafe -> extract_attachment_image_url(Rest)+ end;+extract_attachment_image_url([_ | Rest]) ->+ extract_attachment_image_url(Rest);+extract_attachment_image_url(_) ->+ undefined.++-spec extract_embed_image_url(term()) -> binary() | undefined.+extract_embed_image_url([Embed | Rest]) when is_map(Embed) ->+ case first_embed_media_url(Embed) of+ undefined -> extract_embed_image_url(Rest);+ Url -> Url+ end;+extract_embed_image_url([_ | Rest]) ->+ extract_embed_image_url(Rest);+extract_embed_image_url(_) ->+ undefined.++-spec first_embed_media_url(map()) -> binary() | undefined.+first_embed_media_url(Embed) ->+ Candidates = [+ maps:get(<<"image">>, Embed, undefined),+ maps:get(<<"thumbnail">>, Embed, undefined)+ ],+ first_embed_media_url_from_candidates(Candidates).++-spec first_embed_media_url_from_candidates(list()) -> binary() | undefined.+first_embed_media_url_from_candidates([Media | Rest]) when is_map(Media) ->+ case check_media_safe_url(Media) of+ {ok, Url} -> Url;+ unsafe -> first_embed_media_url_from_candidates(Rest)+ end;+first_embed_media_url_from_candidates([_ | Rest]) ->+ first_embed_media_url_from_candidates(Rest);+first_embed_media_url_from_candidates([]) ->+ undefined.++-spec check_media_safe_url(map()) -> {ok, binary()} | unsafe.+check_media_safe_url(Media) ->+ ProxyUrl = maps:get(<<"proxy_url">>, Media, undefined),+ FallbackUrl = maps:get(<<"url">>, Media, undefined),+ Url = push_utils:normalize_binary(+ case ProxyUrl of+ undefined -> FallbackUrl;+ _ -> ProxyUrl+ end+ ),+ DefaultCT = maps:get(<<"content_type">>, Media, <<>>),+ ContentType = push_utils:normalize_binary(DefaultCT),+ Flags = bitset:parse_maybe(+ maps:get(<<"flags">>, Media, 0)+ ),+ Nsfw = maps:get(<<"nsfw">>, Media, false),+ case is_safe_media_url(Url, ContentType, Flags, Nsfw) of+ true when is_binary(Url) -> {ok, Url};+ _ -> unsafe+ end.++-spec is_safe_media_url(+ binary() | undefined,+ binary() | undefined,+ integer() | undefined,+ term()+) ->+ boolean().+is_safe_media_url(undefined, _ContentType, _Flags, _Nsfw) ->+ false;+is_safe_media_url(_Url, undefined, _Flags, _Nsfw) ->+ false;+is_safe_media_url(_Url, _ContentType, undefined, _Nsfw) ->+ false;+is_safe_media_url(Url, ContentType, Flags, Nsfw) when is_binary(Url), is_binary(ContentType) ->+ IsImage = binary:match(lowercase_binary(ContentType), <<"image/">>) =/= nomatch,+ IsSensitive = is_sensitive_media(Nsfw, Flags),+ IsHttps = binary:match(lowercase_binary(Url), <<"https://">>) =:= {0, 8},+ IsImage andalso not IsSensitive andalso IsHttps.++-spec is_sensitive_media(term(), integer()) -> boolean().+is_sensitive_media(true, _Flags) ->+ true;+is_sensitive_media(_Nsfw, Flags) ->+ bitset:any(Flags, 16#18).++-spec lowercase_binary(binary()) -> binary().+lowercase_binary(Value) ->+ iolist_to_binary(string:lowercase(Value)).diff --git a/fluxer_gateway/src/push/push_job_fields.erl b/fluxer_gateway/src/push/push_job_fields.erlnew file mode 100644index 000000000..f30126167--- /dev/null+++ b/fluxer_gateway/src/push/push_job_fields.erl@@ -0,0 +1,94 @@+%% SPDX-License-Identifier: AGPL-3.0-or-later++-module(push_job_fields).+-typing([eqwalizer]).++-export([notification/7, thread/2, caller/1]).++-define(MAX_CALLER_NAME_BYTES, 128).++-spec caller(map()) -> map().+caller(#{caller_id := CallerId, caller_name := Name} = Caller) when+ is_integer(CallerId), is_binary(Name), byte_size(Name) > 0+->+ CallerIdBin = integer_to_binary(CallerId),+ #{+ <<"caller_id">> => CallerIdBin,+ <<"caller_name">> => push_notification_format:truncate_bytes(+ Name, ?MAX_CALLER_NAME_BYTES+ ),+ <<"caller_avatar_url">> => caller_avatar_url(+ CallerIdBin, maps:get(caller_avatar, Caller, undefined)+ )+ };+caller(_Caller) ->+ #{}.++-spec caller_avatar_url(binary(), term()) -> binary().+caller_avatar_url(CallerIdBin, Hash) when is_binary(Hash), byte_size(Hash) > 0 ->+ push_notification_format:resolve_author_avatar_url(#{+ <<"id">> => CallerIdBin, <<"avatar">> => Hash+ });+caller_avatar_url(CallerIdBin, _Hash) ->+ push_notification_format:resolve_author_avatar_url(#{+ <<"id">> => CallerIdBin, <<"avatar">> => null+ }).++-spec notification(+ map(), map(), integer(), integer(), integer(), binary() | undefined, binary() | undefined+) -> map().+notification(+ MessageData, MarkdownContext, GuildId, ChannelId, MessageId, GuildName, ChannelName+) ->+ AuthorData = maps:get(<<"author">>, MessageData, #{}),+ AuthorUsername = maps:get(<<"username">>, AuthorData, <<"Unknown">>),+ AuthorName = push_notification_format:resolve_author_name(+ MessageData, MarkdownContext, AuthorUsername+ ),+ ChannelIdBin = integer_to_binary(ChannelId),+ MessageIdBin = integer_to_binary(MessageId),+ with_badge(#{+ <<"title">> => push_notification:build_notification_title(+ AuthorName, MessageData, GuildId, GuildName, ChannelName+ ),+ <<"body">> => push_notification_format:build_content_preview(+ MessageData, MarkdownContext+ ),+ <<"icon">> => push_notification_format:resolve_author_avatar_url(AuthorData),+ <<"tag">> => <<"channel:", ChannelIdBin/binary, ":", MessageIdBin/binary>>,+ <<"notification_tag">> => <<"channel:", ChannelIdBin/binary>>,+ <<"url">> => push_notification_format:build_url(GuildId, ChannelId, MessageId),+ <<"image_url">> => nullable(push_image_url:extract(MessageData))+ }).++-spec with_badge(map()) -> map().+with_badge(Fields) ->+ case fluxer_gateway_env:get(self_hosted) of+ true ->+ Fields;+ _ ->+ Fields#{+ <<"badge">> => push_utils:construct_static_asset_url(+ <<"marketing/branding/symbol-white.svg">>+ )+ }+ end.++-spec thread(map(), binary() | undefined) -> map().+thread(MessageData, ChannelName) ->+ case push_notification:thread_fields(MessageData, ChannelName) of+ Fields when map_size(Fields) =:= 0 -> Fields;+ Fields -> Fields#{<<"kind">> => thread_job_kind(MessageData)}+ end.++-spec thread_job_kind(map()) -> binary().+thread_job_kind(#{<<"__thread_push">> := #{<<"forum_thread_created">> := true}}) ->+ <<"forum_thread_created">>;+thread_job_kind(_MessageData) ->+ <<"thread">>.++-spec nullable(binary() | undefined) -> binary() | null.+nullable(undefined) ->+ null;+nullable(Value) ->+ Value.diff --git a/fluxer_gateway/src/push/push_job_publisher.erl b/fluxer_gateway/src/push/push_job_publisher.erlindex 16a5d6148..4eacccc8b 100644--- a/fluxer_gateway/src/push/push_job_publisher.erl+++ b/fluxer_gateway/src/push/push_job_publisher.erl@@ -12,7 +12,6 @@-define(JOB_VERSION, 1).-define(LEGACY_CONFIG_VERSION, 0).-define(NATS_MAX_PAYLOAD_BYTES, 1048576).--define(MAX_CALLER_NAME_BYTES, 128).-type meta() :: #{kind := push_outbox:kind(),@@ -81,7 +80,7 @@ message_job(<<"guild_id">> => integer_to_binary(GuildId),<<"channel_id">> => integer_to_binary(ChannelId),<<"message_id">> => integer_to_binary(MessageId),- <<"notification">> => notification_fields(+ <<"notification">> => push_job_fields:notification(MessageData,MarkdownContext,GuildId,@@ -91,18 +90,18 @@ message_job(ChannelName)},- maps:merge(Job, thread_job_fields(MessageData, ChannelName)).+ maps:merge(Job, push_job_fields:thread(MessageData, ChannelName)).-spec publish_recipients(map(), [integer()], meta()) -> ok | {error, term()}.publish_recipients(Job, UserIds, Meta) ->Chunk = Job#{<<"user_ids">> => [integer_to_binary(UserId) || UserId <- UserIds]},- case encode(Chunk) of- {ok, Body} when byte_size(Body) > ?NATS_MAX_PAYLOAD_BYTES, length(UserIds) > 1 ->+ case {encode(Chunk), UserIds} of+ {{ok, Body}, [_, _ | _]} when byte_size(Body) > ?NATS_MAX_PAYLOAD_BYTES ->{Left, Right} = lists:split(length(UserIds) div 2, UserIds),LeftResult = publish_recipients(Job, Left, Meta),RightResult = publish_recipients(Job, Right, Meta),first_error(LeftResult, RightResult);- Encoded ->+ {Encoded, _UserIds} ->publish_encoded(?SUBJECT_MESSAGE, Chunk, Encoded, Meta#{user_ids := UserIds})end.@@ -159,7 +158,7 @@ publish_ring(UserId, ChannelId, MessageId, StartedAtMs, ExpiresAtMs, Caller) -><<"started_at_ms">> => StartedAtMs,<<"expires_at_ms">> => ExpiresAtMs},- caller_fields(Caller)+ push_job_fields:caller(Caller)),publish(?SUBJECT_RING, Job, #{kind => ring,@@ -168,33 +167,6 @@ publish_ring(UserId, ChannelId, MessageId, StartedAtMs, ExpiresAtMs, Caller) ->message_id => MessageId}).--spec caller_fields(map()) -> map().-caller_fields(#{caller_id := CallerId, caller_name := Name} = Caller) when- is_integer(CallerId), is_binary(Name), byte_size(Name) > 0-->- CallerIdBin = integer_to_binary(CallerId),- #{- <<"caller_id">> => CallerIdBin,- <<"caller_name">> => push_notification_format:truncate_bytes(- Name, ?MAX_CALLER_NAME_BYTES- ),- <<"caller_avatar_url">> => caller_avatar_url(- CallerIdBin, maps:get(caller_avatar, Caller, undefined)- )- };-caller_fields(_Caller) ->- #{}.---spec caller_avatar_url(binary(), term()) -> binary().-caller_avatar_url(CallerIdBin, Hash) when is_binary(Hash), byte_size(Hash) > 0 ->- push_notification_format:resolve_author_avatar_url(#{- <<"id">> => CallerIdBin, <<"avatar">> => Hash- });-caller_avatar_url(CallerIdBin, _Hash) ->- push_notification_format:resolve_author_avatar_url(#{- <<"id">> => CallerIdBin, <<"avatar">> => null- }).--spec request(binary(), binary(), pos_integer()) -> ok | {error, term()}.request(Subject, Body, Timeout) ->case gateway_nats_pool_conn:get_pool_conn() of@@ -218,65 +190,6 @@ decode_reply(Payload) ->_:_ -> {error, invalid_reply}end.--spec notification_fields(- map(), map(), integer(), integer(), integer(), binary() | undefined, binary() | undefined-) -> map().-notification_fields(- MessageData, MarkdownContext, GuildId, ChannelId, MessageId, GuildName, ChannelName-) ->- AuthorData = maps:get(<<"author">>, MessageData, #{}),- AuthorUsername = maps:get(<<"username">>, AuthorData, <<"Unknown">>),- AuthorName = push_notification_format:resolve_author_name(- MessageData, MarkdownContext, AuthorUsername- ),- ChannelIdBin = integer_to_binary(ChannelId),- MessageIdBin = integer_to_binary(MessageId),- with_badge(#{- <<"title">> => push_notification:build_notification_title(- AuthorName, MessageData, GuildId, GuildName, ChannelName- ),- <<"body">> => push_notification_format:build_content_preview(- MessageData, MarkdownContext- ),- <<"icon">> => push_notification_format:resolve_author_avatar_url(AuthorData),- <<"tag">> => <<"channel:", ChannelIdBin/binary, ":", MessageIdBin/binary>>,- <<"notification_tag">> => <<"channel:", ChannelIdBin/binary>>,- <<"url">> => push_notification_format:build_url(GuildId, ChannelId, MessageId),- <<"image_url">> => nullable(push_notification_format:extract_image_url(MessageData))- }).---spec with_badge(map()) -> map().-with_badge(Fields) ->- case fluxer_gateway_env:get(self_hosted) of- true ->- Fields;- _ ->- Fields#{- <<"badge">> => push_utils:construct_static_asset_url(- <<"marketing/branding/symbol-white.svg">>- )- }- end.---spec thread_job_fields(map(), binary() | undefined) -> map().-thread_job_fields(MessageData, ChannelName) ->- case push_notification:thread_fields(MessageData, ChannelName) of- Fields when map_size(Fields) =:= 0 -> Fields;- Fields -> Fields#{<<"kind">> => thread_job_kind(MessageData)}- end.---spec thread_job_kind(map()) -> binary().-thread_job_kind(#{<<"__thread_push">> := #{<<"forum_thread_created">> := true}}) ->- <<"forum_thread_created">>;-thread_job_kind(_MessageData) ->- <<"thread">>.---spec nullable(binary() | undefined) -> binary() | null.-nullable(undefined) ->- null;-nullable(Value) ->- Value.--spec publish(binary(), map(), meta()) -> ok | {error, term()}.publish(Subject, Job, Meta) ->publish_encoded(Subject, Job, encode(Job), Meta).@@ -334,338 +247,3 @@ outbox_job(Subject, Job, Body, Meta) ->channel_id => ChannelId,message_id => MessageId}.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--with_endpoint_env(Fun) ->- with_endpoint_env(false, Fun).--with_endpoint_env(SelfHosted, Fun) ->- ok = meck:new(fluxer_gateway_env, [passthrough, no_link]),- try- ok = meck:expect(fluxer_gateway_env, get, fun- (self_hosted) -> SelfHosted;- (Key) -> endpoint_env_meck(Key)- end),- Fun()- after- meck:unload(fluxer_gateway_env)- end.--endpoint_env_meck(media_proxy_endpoint) -> <<"https://media.example">>;-endpoint_env_meck(static_cdn_endpoint) -> <<"https://static.example">>;-endpoint_env_meck(Key) -> meck:passthrough([Key]).--caller_fields_builds_the_avatar_url_from_the_hash_test() ->- Fields = with_endpoint_env(fun() ->- caller_fields(#{- caller_id => 1234567890123456789,- caller_name => <<"Ada">>,- caller_avatar => <<"a1b2c3d4">>- })- end),- ?assertEqual(- #{- <<"caller_id">> => <<"1234567890123456789">>,- <<"caller_name">> => <<"Ada">>,- <<"caller_avatar_url">> =>- <<"https://media.example/avatars/1234567890123456789/a1b2c3d4.png">>- },- Fields- ).--thread_job_fields_are_absent_for_channel_messages_test() ->- ?assertEqual(#{}, thread_job_fields(#{}, <<"general">>)).--thread_job_fields_mark_thread_jobs_test() ->- MessageData = #{- <<"__thread_push">> => #{<<"parent_id">> => 200, <<"parent_name">> => <<"general">>}- },- ?assertEqual(- #{- <<"kind">> => <<"thread">>,- <<"channel_name">> => <<"ideas">>,- <<"parent_id">> => <<"200">>,- <<"parent_name">> => <<"general">>- },- thread_job_fields(MessageData, <<"ideas">>)- ).--thread_job_fields_mark_forum_thread_created_jobs_test() ->- MessageData = #{- <<"__thread_push">> => #{- <<"parent_id">> => 300,- <<"parent_name">> => <<"ideas">>,- <<"forum_thread_created">> => true- }- },- ?assertMatch(- #{<<"kind">> := <<"forum_thread_created">>, <<"parent_id">> := <<"300">>},- thread_job_fields(MessageData, <<"post">>)- ).--encoded_message_job(MessageData, ChannelName) ->- ok = meck:new(push_notification_format, [passthrough, no_link]),- ok = meck:new(push_utils, [passthrough, no_link]),- try- ok = meck:expect(- push_notification_format, resolve_author_avatar_url, fun(_) -> <<"icon">> end- ),- ok = meck:expect(push_utils, construct_static_asset_url, fun(_) -> <<"badge">> end),- Job = with_endpoint_env(fun() ->- message_job(MessageData, #{}, 5, 6, 7, <<"Guild">>, ChannelName)- end),- json:decode(iolist_to_binary(json:encode(Job)))- after- meck:unload(push_utils),- meck:unload(push_notification_format)- end.--message_job_puts_thread_fields_at_the_top_level_test() ->- MessageData = #{- <<"author">> => #{<<"username">> => <<"ada">>},- <<"content">> => <<"hi">>,- <<"__thread_push">> => #{<<"parent_id">> => 200, <<"parent_name">> => <<"general">>}- },- Decoded = encoded_message_job(MessageData, <<"ideas">>),- ?assertMatch(- #{- <<"kind">> := <<"thread">>,- <<"parent_id">> := <<"200">>,- <<"parent_name">> := <<"general">>,- <<"channel_name">> := <<"ideas">>- },- Decoded- ),- Notification = maps:get(<<"notification">>, Decoded),- ?assertEqual(- [],- [- K- || K <- [<<"kind">>, <<"parent_id">>, <<"parent_name">>, <<"channel_name">>],- maps:is_key(K, Notification)- ]- ).--message_job_has_no_thread_fields_for_channel_messages_test() ->- MessageData = #{<<"author">> => #{<<"username">> => <<"ada">>}, <<"content">> => <<"hi">>},- Decoded = encoded_message_job(MessageData, <<"general">>),- ?assertEqual(- [],- [- K- || K <- [<<"kind">>, <<"parent_id">>, <<"parent_name">>, <<"channel_name">>],- maps:is_key(K, Decoded)- ]- ).--caller_fields_caps_the_caller_name_test() ->- Name = binary:copy(<<"a">>, ?MAX_CALLER_NAME_BYTES + 32),- Fields = with_endpoint_env(fun() ->- caller_fields(#{- caller_id => 1234567890123456789, caller_name => Name, caller_avatar => undefined- })- end),- ?assertEqual(- ?MAX_CALLER_NAME_BYTES, byte_size(maps:get(<<"caller_name">>, Fields))- ).--notification_fields_include_title_body_and_tags_test() ->- Fields = test_notification_fields(- #{<<"content">> => <<"Hello world">>, <<"mentions">> => []},- 123,- <<"Server">>,- <<"general">>- ),- ?assertEqual(<<"Alice (#general, Server)">>, maps:get(<<"title">>, Fields)),- ?assertEqual(<<"Hello world">>, maps:get(<<"body">>, Fields)),- ?assertEqual(<<"channel:456:789">>, maps:get(<<"tag">>, Fields)),- ?assertEqual(<<"channel:456">>, maps:get(<<"notification_tag">>, Fields)),- ?assertEqual(<<"/channels/123/456/789">>, maps:get(<<"url">>, Fields)),- ?assertEqual(null, maps:get(<<"image_url">>, Fields)).--notification_fields_omit_sensitive_attachment_image_test() ->- MessageData = #{- <<"content">> => <<"Spoiler">>,- <<"mentions">> => [],- <<"attachments">> => [- #{- <<"content_type">> => <<"image/png">>,- <<"proxy_url">> => <<"https://cdn.example/spoiler.png">>,- <<"flags">> => 8- }- ]- },- Fields = test_notification_fields(MessageData, 123, <<"Server">>, <<"general">>),- ?assertEqual(null, maps:get(<<"image_url">>, Fields)).--test_notification_fields(MessageData, GuildId, GuildName, ChannelName) ->- test_notification_fields(MessageData, GuildId, GuildName, ChannelName, #{}).--test_notification_fields(MessageData, GuildId, GuildName, ChannelName, MarkdownContext) ->- test_notification_fields(- MessageData, GuildId, GuildName, ChannelName, MarkdownContext, false- ).--test_notification_fields(- MessageData, GuildId, GuildName, ChannelName, MarkdownContext, SelfHosted-) ->- Author = #{<<"id">> => <<"42">>, <<"username">> => <<"Alice">>, <<"avatar">> => null},- with_endpoint_env(SelfHosted, fun() ->- notification_fields(- MessageData#{<<"author">> => Author},- MarkdownContext,- GuildId,- 456,- 789,- GuildName,- ChannelName- )- end).--with_captured_enqueues(Fun) ->- {Jobs, _Dropped} = with_captured_outbox(fun(_OutboxJob) -> ok end, Fun),- Jobs.--with_captured_outbox(EnqueueResult, Fun) ->- Self = self(),- ok = meck:new(push_outbox, [passthrough, no_link]),- try- ok = meck:expect(push_outbox, enqueue, fun(OutboxJob) ->- Self ! {enqueued, OutboxJob},- EnqueueResult(OutboxJob)- end),- ok = meck:expect(push_outbox, record_dropped, fun(Kind, Reason) ->- Self ! {dropped, Kind, Reason},- ok- end),- Fun(),- {drain_enqueued([]), drain_dropped([])}- after- meck:unload(push_outbox)- end.--drain_enqueued(Acc) ->- receive- {enqueued, OutboxJob} -> drain_enqueued([OutboxJob | Acc])- after 0 ->- lists:reverse(Acc)- end.--drain_dropped(Acc) ->- receive- {dropped, Kind, Reason} -> drain_dropped([{Kind, Reason} | Acc])- after 0 ->- lists:reverse(Acc)- end.--padded_job(UserIds, TargetBytes) ->- Job = #{- <<"v">> => ?JOB_VERSION,- <<"config_version">> => ?LEGACY_CONFIG_VERSION,- <<"pad">> => <<>>- },- {ok, Base} = encode(Job#{<<"user_ids">> => [integer_to_binary(Id) || Id <- UserIds]}),- Padded = Job#{<<"pad">> => binary:copy(<<"a">>, TargetBytes - byte_size(Base))},- {ok, Body} = encode(Padded#{<<"user_ids">> => [integer_to_binary(Id) || Id <- UserIds]}),- ?assertEqual(TargetBytes, byte_size(Body)),- Padded.--message_meta(UserIds) ->- #{kind => message, user_ids => UserIds, channel_id => 20, message_id => 30}.--a_body_exactly_at_the_payload_limit_is_sent_as_one_job_test() ->- UserIds = [1, 2],- Job = padded_job(UserIds, ?NATS_MAX_PAYLOAD_BYTES),- Jobs = with_captured_enqueues(fun() ->- ?assertEqual(ok, publish_recipients(Job, UserIds, message_meta(UserIds)))- end),- ?assertMatch([#{user_ids := [1, 2]}], Jobs),- [#{body := Body}] = Jobs,- ?assertEqual(?NATS_MAX_PAYLOAD_BYTES, byte_size(Body)).--a_body_one_byte_over_the_payload_limit_is_split_test() ->- UserIds = [1, 2],- Job = padded_job(UserIds, ?NATS_MAX_PAYLOAD_BYTES + 1),- {Jobs, Dropped} = with_captured_outbox(fun(_OutboxJob) -> ok end, fun() ->- ?assertEqual(ok, publish_recipients(Job, UserIds, message_meta(UserIds)))- end),- ?assertMatch([#{user_ids := [1]}, #{user_ids := [2]}], Jobs),- ?assertEqual([], Dropped).--a_single_recipient_over_the_payload_limit_is_dropped_test() ->- UserIds = [1],- Job = padded_job(UserIds, ?NATS_MAX_PAYLOAD_BYTES + 1),- {Jobs, Dropped} = with_captured_outbox(fun(_OutboxJob) -> ok end, fun() ->- ?assertEqual(- {error, {payload_too_large, ?NATS_MAX_PAYLOAD_BYTES + 1}},- publish_recipients(Job, UserIds, message_meta(UserIds))- )- end),- ?assertEqual([], Jobs),- ?assertEqual([{message, payload_too_large}], Dropped).--a_failed_left_chunk_still_publishes_the_right_chunk_test() ->- UserIds = [1, 2],- Job = padded_job(UserIds, ?NATS_MAX_PAYLOAD_BYTES + 1),- Failure = {outbox_unavailable, shutdown},- FailLeft = fun- (#{user_ids := [1]}) -> {error, Failure};- (_OutboxJob) -> ok- end,- {Jobs, Dropped} = with_captured_outbox(FailLeft, fun() ->- ?assertEqual(- {error, Failure}, publish_recipients(Job, UserIds, message_meta(UserIds))- )- end),- ?assertMatch([#{user_ids := [1]}, #{user_ids := [2]}], Jobs),- ?assertEqual([{message, outbox_unavailable}], Dropped).--an_enqueue_timeout_is_counted_apart_from_an_unavailable_outbox_test() ->- Job = #{<<"v">> => ?JOB_VERSION},- Meta = #{kind => clear, user_ids => [1], channel_id => 20, message_id => 30},- {_TimeoutJobs, TimeoutDropped} = with_captured_outbox(- fun(_OutboxJob) -> {error, {outbox_unavailable, timeout}} end,- fun() -> publish(?SUBJECT_CLEAR, Job, Meta) end- ),- ?assertEqual([{clear, enqueue_timeout}], TimeoutDropped),- {_NoprocJobs, NoprocDropped} = with_captured_outbox(- fun(_OutboxJob) -> {error, outbox_unavailable} end,- fun() -> publish(?SUBJECT_CLEAR, Job, Meta) end- ),- ?assertEqual([], NoprocDropped).--oversized_recipient_lists_are_split_under_the_payload_limit_test() ->- UserIds = lists:seq(1000000000000000000, 1000000000000000000 + 59999),- Job = #{<<"v">> => ?JOB_VERSION, <<"config_version">> => ?LEGACY_CONFIG_VERSION},- Meta = #{kind => message, user_ids => UserIds, channel_id => 20, message_id => 30},- Jobs = with_captured_enqueues(fun() ->- ?assertEqual(ok, publish_recipients(Job, UserIds, Meta))- end),- ?assert(length(Jobs) > 1),- lists:foreach(- fun(#{body := Body, user_ids := ChunkIds, job := ChunkJob}) ->- ?assert(byte_size(Body) =< ?NATS_MAX_PAYLOAD_BYTES),- ?assertEqual(- [integer_to_binary(UserId) || UserId <- ChunkIds],- maps:get(<<"user_ids">>, ChunkJob)- ),- ?assertEqual(?LEGACY_CONFIG_VERSION, maps:get(<<"config_version">>, ChunkJob))- end,- Jobs- ),- ?assertEqual(UserIds, lists:append([ChunkIds || #{user_ids := ChunkIds} <- Jobs])).--recipient_lists_under_the_payload_limit_stay_in_one_job_test() ->- UserIds = [1, 2, 3],- Job = #{<<"v">> => ?JOB_VERSION, <<"config_version">> => ?LEGACY_CONFIG_VERSION},- Meta = #{kind => message, user_ids => UserIds, channel_id => 20, message_id => 30},- Jobs = with_captured_enqueues(fun() ->- ?assertEqual(ok, publish_recipients(Job, UserIds, Meta))- end),- ?assertMatch(- [#{kind := message, user_ids := [1, 2, 3], subject := ?SUBJECT_MESSAGE}], Jobs- ).---endif.diff --git a/fluxer_gateway/src/push/push_notification_format.erl b/fluxer_gateway/src/push/push_notification_format.erlindex 914854446..4e8cbfadf 100644--- a/fluxer_gateway/src/push/push_notification_format.erl+++ b/fluxer_gateway/src/push/push_notification_format.erl@@ -4,29 +4,22 @@-typing([eqwalizer]).-export([- build_content_preview/1,build_content_preview/2,build_markdown_context/4,resolve_author_name/3,resolve_author_avatar_url/1,- extract_image_url/1,build_url/3,truncate_bytes/2]).-define(MAX_MENTIONS_FOR_PUSH, 50).-define(MAX_PREVIEW_BYTES, 100).--define(MAX_IMAGE_URL_BYTES, 1024).-define(CHANNEL_TYPE_GUILD_TEXT, 0).-define(CHANNEL_TYPE_GUILD_VOICE, 2).-define(CHANNEL_TYPE_GUILD_CATEGORY, 4).-define(CHANNEL_TYPE_GUILD_ANNOUNCEMENT, 5).-define(CHANNEL_TYPE_GUILD_LINK, 998).--spec build_content_preview(map()) -> binary().-build_content_preview(MessageData) ->- build_content_preview(MessageData, #{}).--spec build_content_preview(map(), map()) -> binary().build_content_preview(MessageData, MarkdownContext) ->Content = push_utils:normalize_binary(maps:get(<<"content">>, MessageData, <<"">>), <<>>),@@ -512,112 +505,6 @@ format_name_list(Names) ->Prefix = join_binary(lists:reverse(ReversedRest), <<", ">>),iolist_to_binary([Prefix, <<", and ">>, Last]).--spec extract_image_url(map()) -> binary() | undefined.-extract_image_url(MessageData) ->- bounded_image_url(resolve_image_url(MessageData)).---spec resolve_image_url(map()) -> binary() | undefined.-resolve_image_url(MessageData) ->- case extract_attachment_image_url(maps:get(<<"attachments">>, MessageData, [])) of- undefined -> extract_embed_image_url(maps:get(<<"embeds">>, MessageData, []));- ImageUrl -> ImageUrl- end.---spec bounded_image_url(binary() | undefined) -> binary() | undefined.-bounded_image_url(ImageUrl) when- is_binary(ImageUrl), byte_size(ImageUrl) =< ?MAX_IMAGE_URL_BYTES-->- ImageUrl;-bounded_image_url(_ImageUrl) ->- undefined.---spec extract_attachment_image_url(term()) -> binary() | undefined.-extract_attachment_image_url([Attachment | Rest]) when is_map(Attachment) ->- case check_media_safe_url(Attachment) of- {ok, Url} -> Url;- unsafe -> extract_attachment_image_url(Rest)- end;-extract_attachment_image_url([_ | Rest]) ->- extract_attachment_image_url(Rest);-extract_attachment_image_url(_) ->- undefined.---spec extract_embed_image_url(term()) -> binary() | undefined.-extract_embed_image_url([Embed | Rest]) when is_map(Embed) ->- case first_embed_media_url(Embed) of- undefined -> extract_embed_image_url(Rest);- Url -> Url- end;-extract_embed_image_url([_ | Rest]) ->- extract_embed_image_url(Rest);-extract_embed_image_url(_) ->- undefined.---spec first_embed_media_url(map()) -> binary() | undefined.-first_embed_media_url(Embed) ->- Candidates = [- maps:get(<<"image">>, Embed, undefined),- maps:get(<<"thumbnail">>, Embed, undefined)- ],- first_embed_media_url_from_candidates(Candidates).---spec first_embed_media_url_from_candidates(list()) -> binary() | undefined.-first_embed_media_url_from_candidates([Media | Rest]) when is_map(Media) ->- case check_media_safe_url(Media) of- {ok, Url} -> Url;- unsafe -> first_embed_media_url_from_candidates(Rest)- end;-first_embed_media_url_from_candidates([_ | Rest]) ->- first_embed_media_url_from_candidates(Rest);-first_embed_media_url_from_candidates([]) ->- undefined.---spec check_media_safe_url(map()) -> {ok, binary()} | unsafe.-check_media_safe_url(Media) ->- ProxyUrl = maps:get(<<"proxy_url">>, Media, undefined),- FallbackUrl = maps:get(<<"url">>, Media, undefined),- Url = push_utils:normalize_binary(- case ProxyUrl of- undefined -> FallbackUrl;- _ -> ProxyUrl- end- ),- DefaultCT = maps:get(<<"content_type">>, Media, <<>>),- ContentType = push_utils:normalize_binary(DefaultCT),- Flags = bitset:parse_maybe(- maps:get(<<"flags">>, Media, 0)- ),- Nsfw = maps:get(<<"nsfw">>, Media, false),- case is_safe_media_url(Url, ContentType, Flags, Nsfw) of- true when is_binary(Url) -> {ok, Url};- _ -> unsafe- end.---spec is_safe_media_url(- binary() | undefined,- binary() | undefined,- integer() | undefined,- term()-) ->- boolean().-is_safe_media_url(undefined, _ContentType, _Flags, _Nsfw) ->- false;-is_safe_media_url(_Url, undefined, _Flags, _Nsfw) ->- false;-is_safe_media_url(_Url, _ContentType, undefined, _Nsfw) ->- false;-is_safe_media_url(Url, ContentType, Flags, Nsfw) when is_binary(Url), is_binary(ContentType) ->- IsImage = binary:match(lowercase_binary(ContentType), <<"image/">>) =/= nomatch,- IsSensitive = is_sensitive_media(Nsfw, Flags),- IsHttps = binary:match(lowercase_binary(Url), <<"https://">>) =:= {0, 8},- IsImage andalso not IsSensitive andalso IsHttps.---spec is_sensitive_media(term(), integer()) -> boolean().-is_sensitive_media(true, _Flags) ->- true;-is_sensitive_media(_Nsfw, Flags) ->- bitset:any(Flags, 16#18).--spec build_url(integer(), integer(), integer()) -> binary().build_url(0, ChannelId, MessageId) ->build_url_parts([<<"@me">>, integer_to_binary(ChannelId), integer_to_binary(MessageId)]);@@ -634,65 +521,3 @@ build_url_parts(Parts) -><<"/channels/">>,join_binary(Parts, <<"/">>)]).---spec lowercase_binary(binary()) -> binary().-lowercase_binary(Value) ->- iolist_to_binary(string:lowercase(Value)).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--truncate_preview_never_splits_a_utf8_character_test() ->- Emoji = <<"\xF0\x9F\x98\x80">>,- Content = <<(binary:copy(<<"a">>, 98))/binary, Emoji/binary>>,- ?assert(byte_size(Content) > 100),- Truncated = truncate_preview(Content),- ?assert(byte_size(Truncated) =< 100),- ?assertMatch(Bin when is_binary(Bin), unicode:characters_to_binary(Truncated, utf8, utf8)),- ?assertEqual(binary:copy(<<"a">>, 98), Truncated).--truncate_preview_is_unchanged_for_valid_ascii_test() ->- Content = binary:copy(<<"a">>, 150),- ?assertEqual(binary:copy(<<"a">>, 100), truncate_preview(Content)).--truncate_preview_keeps_short_valid_content_identical_test() ->- Content = <<"hello \xC3\xA9 world">>,- ?assertEqual(Content, truncate_preview(Content)).--extract_image_url_keeps_a_url_within_the_size_bound_test() ->- Url = image_url_of_size(?MAX_IMAGE_URL_BYTES),- ?assertEqual(Url, extract_image_url(message_with_embed_image(Url))).--extract_image_url_rejects_an_oversized_url_test() ->- Url = image_url_of_size(?MAX_IMAGE_URL_BYTES + 1),- ?assertEqual(undefined, extract_image_url(message_with_embed_image(Url))).--image_url_of_size(Size) ->- Prefix = <<"https://media.example/">>,- <<Prefix/binary, (binary:copy(<<"a">>, Size - byte_size(Prefix)))/binary>>.--message_with_embed_image(Url) ->- #{- <<"embeds">> => [- #{- <<"image">> => #{- <<"content_type">> => <<"image/png">>,- <<"proxy_url">> => Url- }- }- ]- }.--extract_image_url_rejects_malformed_flags_test() ->- MessageData = #{- <<"attachments">> => [- #{- <<"content_type">> => <<"image/png">>,- <<"proxy_url">> => <<"https://cdn.example/image.png">>,- <<"flags">> => <<"not-an-int">>- }- ]- },- ?assertEqual(undefined, extract_image_url(MessageData)).---endif.