Skip to content

Commit

Permalink
Only return extensions for known structured syntax suffixes (#76)
Browse files Browse the repository at this point in the history
Prevents return of arbitrary extension if input MIME type from unsafe source.
  • Loading branch information
MullPointer committed May 31, 2023
1 parent 87c160c commit 37da333
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/mime.ex
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,14 @@ defmodule MIME do
"video/x-msvideo" => ["avi"]
}

#selected from https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml
suffixes = %{
"gzip" => ["gz"],
"json" => ["json"],
"xml" => ["xml"],
"zip" => ["zip"]
}

require Application
custom_types = Application.compile_env(:mime, :types, %{})

Expand Down Expand Up @@ -177,7 +185,7 @@ defmodule MIME do

defp suffix(type) do
case String.split(type, "+") do
[_type_subtype_without_suffix, suffix] -> [suffix]
[_type_subtype_without_suffix, suffix] -> suffix_to_ext(suffix)
_ -> nil
end
end
Expand Down Expand Up @@ -265,4 +273,13 @@ defmodule MIME do
end

defp mime_to_ext(_type), do: nil

@spec suffix_to_ext(String.t()) :: list(String.t()) | nil
defp suffix_to_ext(suffix)

for {suffix, exts} <- suffixes do
defp suffix_to_ext(unquote(suffix)), do: unquote(List.wrap(exts))
end

defp suffix_to_ext(_suffix), do: nil
end
2 changes: 2 additions & 0 deletions test/mime_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ defmodule MIMETest do
assert extensions("application/xml") == ["xml"]
assert extensions("application/vnd.custom+xml") == ["xml"]
assert extensions("application/vnd.custom+xml+xml") == []
assert extensions("application/vnd.custom+inexist") == []
assert extensions("application/vnd.custom+xml/extrainvalid") == []
end

test "type/1" do
Expand Down

0 comments on commit 37da333

Please sign in to comment.