diff --git a/.formatter.exs b/.formatter.exs new file mode 100644 index 0000000..eba5b9d --- /dev/null +++ b/.formatter.exs @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"], + line_length: 80 +] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77ff62b --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where third-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +aww-*.tar + +# Temporary files, for example, from tests. +/tmp/ diff --git a/LICENSES/MPL-2.0.txt b/LICENSES/MPL-2.0.txt new file mode 100644 index 0000000..ee6256c --- /dev/null +++ b/LICENSES/MPL-2.0.txt @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3dfc2c6 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ + + +# Aww + +Generate URL for avatars using: + +- [Gravatar](https://gravatar.com) +- [Libravatar](https://libravatar.org) + +## Installation + +```elixir +def deps do + [ + {:aww, "~> 1.0"} + ] +end +``` + +## Usage + +Just pass the e-mail (or, in case of Libravatar, you can also use OpenID URL) to +the `Aww.avatar_url/1` function and you will receive `URI` struct which points +to avatar for given user. + +```elixir +Aww.avatar_url("~@hauleth.dev") +# => %URI{ +# scheme: "https", +# userinfo: nil, +# host: "seccdn.libravatar.org", +# port: nil, +# path: "/avatar/ac3c4f9061d8e8252d03301685433aa8f943d4d6540caa232ccfb227b38aaa6c", +# query: "", +# fragment: nil +# } +``` diff --git a/config/config.exs b/config/config.exs new file mode 100644 index 0000000..4bbaee9 --- /dev/null +++ b/config/config.exs @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +import Config + +if Mix.env() == :test do + config :aww, :default, "avatar.example.com" +end diff --git a/lib/aww.ex b/lib/aww.ex new file mode 100644 index 0000000..f4c8d46 --- /dev/null +++ b/lib/aww.ex @@ -0,0 +1,237 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule Aww do + alias Aww.Cache + + require Logger + + @default_cache Aww.Cache + + @type host() :: + :gravatar + | :libravatar + | (String.t(), opts() -> String.t() | {String.t(), integer()}) + | {module(), atom(), [term()]} + + @type avatar_opt() :: + {:size, integer()} + | {:default, String.t()} + | {:robohash, String.t()} + | {:forcedefault?, boolean()} + | {:rating, String.t()} + + @type service_opt() :: + {:host, host()} + | {:secure?, boolean()} + | {:resolv_opts, [:inet_res.res_option()]} + | {:timeout, pos_integer()} + | {atom(), term()} + + @type opts() :: [avatar_opt() | {:service_opts, [service_opt()]}] + + @doc """ + Generate URL for avatar using given service. + + ## Options + + Gravatar options supported are: + + - `:size` - pixel size of the resulting image. As returned avatars are always + squares, only one side is needed. + - `:default` - fallback image and/or implementation for image generation. + Check out your implementation documentation for list of supported values. + - `:robohash` - Libravatar and Gravatar support using additional option for + `default: :robohash`. + - `:forcedefault?` - force using default image (useful for testing) + - `:rating` - require image of this rating or lower. Used for explicit image + filtering. Ignored by Libravatar (that service requires all images to be + `PG` rated). + + ### Service options + + It is possible to configure used service via options under `:service_opts` + configuration key. Recognised options are: + + - `:host` - implementation that will be used for generating avatar. Possible + options are: + + `:gravatar` - [Gravatar](https://gravatar.com) + + `:libravatar` - [Libravatar](https://www.libravatar.org) - federated + and open source service providing Gravatar-compatible API + + 2-ary function passed either as a capture or `{m, f, a}` tuple. + In case of MFA tuple the arguments will be prepended to passed list. + Arguments appended are: domain of the `email` and `opts` passed to this + function. + Defaults to `Application.get_env(:aww, :default, :libravatar)`. + - `:secure?` - whether to use secure (HTTPS) connection to the service. + Defaults to `true`. + - `:resolv_opts` - used by `host: :libravatar` - additional opts passed to DNS + resolver. See `t::inet_res.res_option/0` for details. + - `:timeout` - DNS query timeout in milliseconds. Defaults to `5000` (5 seconds). + """ + @spec avatar_url(String.t(), keyword()) :: URI.t() + def avatar_url(email, opts \\ []) do + {service_opts, avatar_opts} = Keyword.pop(opts, :service_opts, []) + default_host = Application.fetch_env!(:aww, :default) + secure? = Keyword.get(service_opts, :secure?, true) + {domain, normalized} = normalize(email) + + {host, port} = + case host(service_opts[:host] || default_host, domain, service_opts) do + {host, port} -> {host, port} + host when is_binary(host) -> {host, nil} + end + + hash = :crypto.hash(:sha256, normalized) + + %URI{ + scheme: if(secure?, do: "https", else: "http"), + host: host, + port: port, + path: "/avatar/#{Base.encode16(hash, case: :lower)}", + query: query(avatar_opts) + } + end + + defp host(kind, domain, opts) + + defp host(:gravatar, _domain, opts) do + if Keyword.get(opts, :secure?, true) do + "secure.gravatar.com" + else + "gravatar.com" + end + end + + defp host(host, _domain, _opts) when is_binary(host), do: {host, nil} + defp host(%URI{host: host, port: port}, _domain, _opts), do: {host, port} + + defp host(:libravatar, "", opts) do + if Keyword.get(opts, :secure?, true) do + "seccdn.libravatar.org" + else + "cdn.libravatar.org" + end + end + + defp host(:libravatar, domain, opts) do + secure? = Keyword.get(opts, :secure?, true) + cache = Keyword.get(opts, :cache, @default_cache) + + {fallback, query} = + if secure? do + {"seccdn.libravatar.org", "_avatars-sec._tcp.#{domain}"} + else + { + "cdn.libravatar.org", + "_avatars._tcp.#{domain}" + } + end + + Cache.get_or_store(cache, query, fn _ -> + resolv_opts = opts[:resolv_opts] || [] + timeout = opts[:timeout] || 5000 + + defederated = + opts[:defederated] || Application.fetch_env!(:aww, :defederated) + + case dns_resp(query, resolv_opts, timeout) do + {:ok, ttl, {host, _} = result} -> + if host in defederated do + Logger.debug( + "Ignoring avatar from #{host}, because it was defederated" + ) + + {fallback, 60_000} + else + {result, :timer.seconds(ttl)} + end + + _ -> + {fallback, 60_000} + end + end) + end + + defp host({m, f, a}, domain, opts) + when is_atom(m) and is_atom(f) and is_list(a) do + apply(m, f, [domain, opts | a]) + end + + defp host(func, domain, opts) when is_function(func, 2) do + func.(domain, opts) + end + + defp query(opts) do + size = opts[:size] || opts[:s] + default = opts[:default] || opts[:d] + robohash = opts[:robohash] + force = (opts[:forcedefault?] || opts[:f]) && "y" + rating = opts[:rating] || opts[:r] + + [ + s: size, + d: default, + f: force, + r: rating, + robohash: robohash + ] + |> Enum.filter(&elem(&1, 1)) + |> Map.new() + |> URI.encode_query() + end + + defp normalize(input) do + trimmed = String.trim(input) + + case String.downcase(trimmed) do + "http://" <> _ -> + normalize_oauth(trimmed) + + "https://" <> _ -> + normalize_oauth(trimmed) + + other -> + domain = split_last(other, "@") + {domain, other} + end + end + + defp normalize_oauth(input) do + uri = URI.parse(input) + host = String.downcase(uri.host) + + {host, URI.to_string(%URI{uri | host: host})} + end + + defp split_last(input, pattern) when is_binary(input) do + case :string.find(input, pattern, :trailing) do + ^pattern <> rest -> rest + _ -> "" + end + end + + defp dns_resp(host, opts, timeout) do + with {:ok, msg} <- + :inet_res.resolve( + to_charlist(host), + :in, + :srv, + opts, + timeout + ), + [rr | _] <- :inet_dns.msg(msg, :anlist) do + ttl = :inet_dns.rr(rr, :ttl) + {_, _, port, host} = :inet_dns.rr(rr, :data) + + {:ok, ttl, {to_string(host), port}} + else + _ -> + :error + end + catch + _, _ -> + :error + end +end diff --git a/lib/aww/application.ex b/lib/aww/application.ex new file mode 100644 index 0000000..d5de48c --- /dev/null +++ b/lib/aww/application.ex @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule Aww.Application do + @moduledoc false + + use Application + + @impl true + def start(_mode, _opts) do + children = [ + {Aww.Cache, name: Aww.Cache} + ] + + opts = [ + strategy: :one_for_one + ] + + Supervisor.start_link(children, opts) + end +end diff --git a/lib/aww/cache.ex b/lib/aww/cache.ex new file mode 100644 index 0000000..042e8ae --- /dev/null +++ b/lib/aww/cache.ex @@ -0,0 +1,87 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule Aww.Cache do + @moduledoc false + + # Super simple cache used for resolving DNS queries, to not wait on each + # single name resolution. + + use GenServer + + require Logger + + def start_link(opts) do + opts = %{ + name: Keyword.fetch!(opts, :name), + cleanup: opts[:cleanup] || 60_000 + } + + GenServer.start_link(__MODULE__, opts) + end + + def get_or_store(cache, key, fun) do + case get(cache, key) do + {:ok, value} -> + value + + :error -> + {value, ttl} = fun.(key) + store(cache, key, value, ttl) + + value + end + end + + def store(cache, key, result, ttl) do + timestamp = + System.monotonic_time() + + :erlang.convert_time_unit(ttl, :millisecond, :native) + + :ets.insert(cache, {key, result, timestamp}) + end + + def get(cache, key) do + timestamp = System.monotonic_time() + + case :ets.lookup(cache, key) do + [{_, result, ttl}] when ttl > timestamp -> + {:ok, result} + + _ -> + :error + end + end + + def clean(cache) do + :ets.delete_all_objects(cache) + end + + @impl true + def init(opts) do + state = opts + + _tid = :ets.new(state.name, [:named_table, :public]) + + Process.send_after(self(), :cleanup, state.cleanup) + + {:ok, state} + end + + @impl true + def handle_info(:cleanup, state) do + timestamp = System.monotonic_time() + + count = + :ets.select_delete(state.name, [ + {{:_, :_, :"$1"}, [{:"=<", :"$1", timestamp}], [true]} + ]) + + Logger.debug("Deleted #{count} cached entries") + + Process.send_after(self(), :cleanup, state.cleanup) + + {:noreply, state} + end +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..86b21d0 --- /dev/null +++ b/mix.exs @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule Aww.MixProject do + use Mix.Project + + def project do + [ + app: :aww, + version: "1.0.0", + elixir: "~> 1.16", + start_permanent: Mix.env() == :prod, + elixirc_paths: elixirc_paths(Mix.env()), + test_coverage: [ + ignore_modules: [ + AwwTest.Dns + ] + ], + docs: [ + formatters: ~w[html], + extras: [ + "README.md" + ], + main: "readme" + ], + deps: deps() + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + # Run "mix help compile.app" to learn about applications. + def application do + [ + extra_applications: [:logger], + mod: {Aww.Application, []}, + env: [ + default: :libravatar, + defederated: [] + ] + ] + end + + # Run "mix help deps" to learn about dependencies. + defp deps do + [ + {:ex_doc, ">= 0.0.0", only: [:dev, :test]}, + {:stream_data, "~> 1.1", only: [:test]} + ] + end +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..570d867 --- /dev/null +++ b/mix.lock @@ -0,0 +1,9 @@ +%{ + "earmark_parser": {:hex, :earmark_parser, "1.4.41", "ab34711c9dc6212dda44fcd20ecb87ac3f3fce6f0ca2f28d4a00e4154f8cd599", [:mix], [], "hexpm", "a81a04c7e34b6617c2792e291b5a2e57ab316365c2644ddc553bb9ed863ebefa"}, + "ex_doc": {:hex, :ex_doc, "0.34.2", "13eedf3844ccdce25cfd837b99bea9ad92c4e511233199440488d217c92571e8", [:mix], [{:earmark_parser, "~> 1.4.39", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "5ce5f16b41208a50106afed3de6a2ed34f4acfd65715b82a0b84b49d995f95c1"}, + "makeup": {:hex, :makeup, "1.1.2", "9ba8837913bdf757787e71c1581c21f9d2455f4dd04cfca785c70bbfff1a76a3", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "cce1566b81fbcbd21eca8ffe808f33b221f9eee2cbc7a1706fc3da9ff18e6cac"}, + "makeup_elixir": {:hex, :makeup_elixir, "0.16.2", "627e84b8e8bf22e60a2579dad15067c755531fea049ae26ef1020cad58fe9578", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "41193978704763f6bbe6cc2758b84909e62984c7752b3784bd3c218bb341706b"}, + "makeup_erlang": {:hex, :makeup_erlang, "1.0.1", "c7f58c120b2b5aa5fd80d540a89fdf866ed42f1f3994e4fe189abebeab610839", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "8a89a1eeccc2d798d6ea15496a6e4870b75e014d1af514b1b71fa33134f57814"}, + "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, + "stream_data": {:hex, :stream_data, "1.1.1", "fd515ca95619cca83ba08b20f5e814aaf1e5ebff114659dc9731f966c9226246", [:mix], [], "hexpm", "45d0cd46bd06738463fd53f22b70042dbb58c384bb99ef4e7576e7bb7d3b8c8c"}, +} diff --git a/mix.lock.license b/mix.lock.license new file mode 100644 index 0000000..761c9ff --- /dev/null +++ b/mix.lock.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> + +SPDX-License-Identifier: MPL-2.0 diff --git a/test/aww/cache_test.exs b/test/aww/cache_test.exs new file mode 100644 index 0000000..0df70ae --- /dev/null +++ b/test/aww/cache_test.exs @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule Aww.CacheTest do + use ExUnit.Case, async: true + use ExUnitProperties + + @subject Aww.Cache + + doctest @subject + + setup ctx do + opts = + Keyword.merge( + [ + name: ctx.test, + cleanup: 300 + ], + ctx[:cache_opts] || [] + ) + + start_supervised!({@subject, opts}) + + {:ok, cache: ctx.test} + end + + property "stored value can be retrieved", ctx do + check all( + key <- string(:ascii), + value <- string(:ascii) + ) do + @subject.store(ctx.cache, key, value, 5000) + + assert {:ok, value} == @subject.get(ctx.cache, key) + end + end + + test "after TTL duration value is no longer returned", ctx do + key = "foo" + value = "bar" + + @subject.store(ctx.cache, key, value, 100) + + assert {:ok, value} == @subject.get(ctx.cache, key) + + Process.sleep(111) + + assert :error == @subject.get(ctx.cache, key) + end + + describe "get_or_store/3" do + test "function is called only once if repeatedly called with the same key", + ctx do + this = self() + + fun = fn _key -> + send(this, :called) + + {1, 200} + end + + key = "foo" + + @subject.get_or_store(ctx.cache, key, fun) + @subject.get_or_store(ctx.cache, key, fun) + @subject.get_or_store(ctx.cache, key, fun) + + assert_received :called + refute_received :called + end + end + + describe "eviction" do + test "after cleanup timeout old entries are removed from cache", ctx do + @subject.store(ctx.cache, "foo", "bar", 100) + + refute [] == :ets.tab2list(ctx.cache) + + Process.sleep(310) + + assert [] == :ets.tab2list(ctx.cache) + end + end +end diff --git a/test/aww/gravatar_test.exs b/test/aww/gravatar_test.exs new file mode 100644 index 0000000..7844671 --- /dev/null +++ b/test/aww/gravatar_test.exs @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule Aww.GravatarTest do + use ExUnit.Case, async: true + + @subject Aww + + test "Gravatar implementation points to secure.gravatar.com" do + url = + @subject.avatar_url("foo@example.com", service_opts: [host: :gravatar]) + + assert url.host =~ "secure.gravatar.com" + end + + test "Gravatar implementation points to gravatar.com (insecure)" do + url = + @subject.avatar_url("foo@example.com", + service_opts: [host: :gravatar, secure?: false] + ) + + assert url.host =~ "gravatar.com" + end +end diff --git a/test/aww/libravatar_test.exs b/test/aww/libravatar_test.exs new file mode 100644 index 0000000..2cc8435 --- /dev/null +++ b/test/aww/libravatar_test.exs @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule Aww.LibravatarTest do + use ExUnit.Case, async: true + + @subject Aww + + defmodule Dns do + @behaviour AwwTest.Dns + + @impl true + def handle_query("_avatars-sec._tcp.evil.test", :in, :srv) do + %{ + ttl: 3600, + data: {0, 0, 0xBEEF, ~c"defederated.example"} + } + end + + def handle_query("_avatars-sec._tcp.example.test", :in, :srv) do + %{ + ttl: 3600, + data: {0, 0, 0xBEEF, ~c"secure.example"} + } + end + + def handle_query("_avatars._tcp.example.test", :in, :srv) do + %{ + ttl: 3600, + data: {0, 0, 0xDEAD, ~c"insecure.example"} + } + end + end + + setup do + assert {:ok, pid, ns} = start_supervised({AwwTest.Dns, module: Dns}) + + on_exit(fn -> + Aww.Cache.clean(Aww.Cache) + end) + + {:ok, pid: pid, ns: ns} + end + + test "uses secure SRV data", %{ns: ns} do + url = + @subject.avatar_url("foo@example.test", + service_opts: [ + host: :libravatar, + resolv_opts: [nameservers: [ns]] + ] + ) + + assert url.host == "secure.example" + assert url.port == 0xBEEF + end + + test "uses insecure SRV data", %{ns: ns} do + url = + @subject.avatar_url("foo@example.test", + service_opts: [ + secure?: false, + host: :libravatar, + resolv_opts: [nameservers: [ns]] + ] + ) + + assert url.host == "insecure.example" + assert url.port == 0xDEAD + end + + test "defederated host results in fallback", %{ns: ns} do + url = + @subject.avatar_url("foo@evil.test", + service_opts: [ + host: :libravatar, + defederated: ["defederated.example"], + resolv_opts: [nameservers: [ns]] + ] + ) + + assert url.host == "seccdn.libravatar.org" + end + + test "with no response uses secure fallback", %{ns: ns} do + url = + @subject.avatar_url("foo@example.invalid", + service_opts: [ + host: :libravatar, + resolv_opts: [nameservers: [ns]] + ] + ) + + assert url.host == "seccdn.libravatar.org" + end + + test "with no response uses insecure fallback", %{ns: ns} do + url = + @subject.avatar_url("foo@example.invalid", + service_opts: [ + secure?: false, + host: :libravatar, + resolv_opts: [nameservers: [ns]] + ] + ) + + assert url.host == "cdn.libravatar.org" + end +end diff --git a/test/aww_test.exs b/test/aww_test.exs new file mode 100644 index 0000000..e050caf --- /dev/null +++ b/test/aww_test.exs @@ -0,0 +1,155 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule AwwTest do + use ExUnit.Case, async: true + use ExUnitProperties + + @subject Aww + + doctest @subject + + test "by default there is no query" do + url = @subject.avatar_url("foo@example.com") + + assert "" == url.query + end + + test "by default HTTPS is used" do + url = @subject.avatar_url("foo@example.com") + + assert "https" == url.scheme + end + + test "can opt out to insecure HTTP query" do + url = @subject.avatar_url("foo@example.com", service_opts: [secure?: false]) + + assert "http" == url.scheme + end + + test "default can be changed" do + url = @subject.avatar_url("foo@example.com", default: "monster") + + assert url.query =~ "d=monster" + end + + test "size can be defined" do + url = @subject.avatar_url("foo@example.com", size: 2137) + + assert url.query =~ "s=2137" + end + + test "enforce default" do + url = @subject.avatar_url("foo@example.com", forcedefault?: true) + + assert url.query =~ "f=y" + end + + test "select rating" do + url = @subject.avatar_url("foo@example.com", rating: "R") + + assert url.query =~ "r=R" + end + + property "email is case insensitive" do + check all( + local_part <- string(:ascii, min_length: 1), + domain <- string(:ascii, min_length: 1) + ) do + input = "#{local_part}@#{domain}" + downcased = String.downcase(input) + + assert @subject.avatar_url(input) == @subject.avatar_url(downcased) + end + end + + property "custom host contains that host" do + check all(host <- string(:ascii, min_lenght: 1)) do + url = @subject.avatar_url("foo@example.com", service_opts: [host: host]) + + assert host == url.host + end + end + + property "custom host as URI contains that host" do + check all(host <- string(:ascii, min_lenght: 1), port <- integer(0..0xFFFF)) do + uri = %URI{ + host: host, + port: port + } + + url = @subject.avatar_url("foo@example.com", service_opts: [host: uri]) + + assert host == url.host + assert port == url.port + end + end + + defp domain do + part = string([?a..?z, ?A..?Z, ?0..?9, ?-], min_length: 1, max_length: 10) + + gen( + all( + parts <- list_of(part, min_length: 1, max_length: 4), + do: Enum.join(parts, ".") + ) + ) + end + + defp open_id_uri do + gen all( + scheme <- one_of([constant("http"), constant("https")]), + host <- domain(), + port <- integer(0..0xFFFF), + segment = string(:alphanumeric, min_length: 1), + path <- list_of(segment), + user <- string(:alphanumeric, min_lenght: 1), + pass <- string(:alphanumeric, min_length: 1) + ) do + %URI{ + scheme: scheme, + host: host, + port: port, + path: "/" <> Enum.join(path, "/"), + userinfo: "#{user}:#{pass}" + } + end + end + + property "normalizes OpenID addresses" do + check all(url <- open_id_uri()) do + input = URI.to_string(url) + + downcased = + URI.to_string(%URI{ + url + | host: String.downcase(url.host) + }) + + assert @subject.avatar_url(input) == @subject.avatar_url(downcased) + end + end + + describe "function as a host provider" do + def host_func(host, _opts), do: "test.#{host}" + + test "passed as MFA" do + url = + @subject.avatar_url("hello@example.com", + service_opts: [host: {__MODULE__, :host_func, []}] + ) + + assert url.host == "test.example.com" + end + + test "passed as capture" do + url = + @subject.avatar_url("hello@example.com", + service_opts: [host: &host_func/2] + ) + + assert url.host == "test.example.com" + end + end +end diff --git a/test/support/dns.ex b/test/support/dns.ex new file mode 100644 index 0000000..02e3461 --- /dev/null +++ b/test/support/dns.ex @@ -0,0 +1,87 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +defmodule AwwTest.Dns do + use GenServer + + @callback handle_query( + String.t(), + :inet_req.dns_class(), + :inet_req.dns_rr_type() + ) :: map() + + def start_link(module: mod) do + with {:ok, pid} <- GenServer.start_link(__MODULE__, mod) do + {:ok, pid, ns(pid)} + end + end + + def ns(pid), do: GenServer.call(pid, :name) + + def init(mod) do + {:ok, sock} = :gen_udp.open(0, mode: :binary) + + {:ok, %{sock: sock, mod: mod}} + end + + def handle_call(:name, _ref, state) do + {:ok, name} = :inet.sockname(state.sock) + + {:reply, name, state} + end + + def handle_info({:udp, sock, from_ip, from_port, data}, %{sock: sock} = state) do + with {:ok, req} <- :inet_dns.decode(data) do + req = :inet_dns.msg(req) + header = :inet_dns.header(req[:header]) + questions = req[:qdlist] + + answers = + for q <- questions, + query = :inet_dns.dns_query(q), + answer <- handle(state, query) do + :inet_dns.make_rr(answer) + end + + resp_header = + :inet_dns.make_header( + id: header[:id], + aa: false, + qr: true, + rd: true, + ra: true, + opcode: :query, + rcode: 0 + ) + + resp = + :inet_dns.make_msg( + header: resp_header, + qdlist: questions, + anlist: answers + ) + + :gen_udp.send(sock, from_ip, from_port, :inet_dns.encode(resp)) + end + + {:noreply, state} + end + + defp handle(%{mod: mod}, query) do + domain = query[:domain] + class = query[:class] + type = query[:type] + + resp = + try do + mod.handle_query(List.to_string(domain), class, type) + catch + _, _ -> [] + end + + for %{ttl: ttl, data: data} <- List.wrap(resp) do + [domain: domain, type: type, class: class, ttl: ttl, data: data] + end + end +end diff --git a/test/test_helper.exs b/test/test_helper.exs new file mode 100644 index 0000000..02b2070 --- /dev/null +++ b/test/test_helper.exs @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2024 Łukasz Niemier <#@hauleth.dev> +# +# SPDX-License-Identifier: MPL-2.0 + +ExUnit.start()