total rebase
[anni] / lib / pleroma / web / web_finger.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.WebFinger do
6   alias Pleroma.HTTP
7   alias Pleroma.User
8   alias Pleroma.Web.ActivityPub.Publisher
9   alias Pleroma.Web.Endpoint
10   alias Pleroma.Web.XML
11   alias Pleroma.XmlBuilder
12   require Jason
13   require Logger
14
15   def host_meta do
16     base_url = Endpoint.url()
17
18     {
19       :XRD,
20       %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
21       {
22         :Link,
23         %{
24           rel: "lrdd",
25           type: "application/xrd+xml",
26           template: "#{base_url}/.well-known/webfinger?resource={uri}"
27         }
28       }
29     }
30     |> XmlBuilder.to_doc()
31   end
32
33   def webfinger(resource, fmt) when fmt in ["XML", "JSON"] do
34     host = Pleroma.Web.Endpoint.host()
35
36     regex =
37       if webfinger_domain = Pleroma.Config.get([__MODULE__, :domain]) do
38         ~r/(acct:)?(?<username>[a-z0-9A-Z_\.-]+)@(#{host}|#{webfinger_domain})/
39       else
40         ~r/(acct:)?(?<username>[a-z0-9A-Z_\.-]+)@#{host}/
41       end
42
43     with %{"username" => username} <- Regex.named_captures(regex, resource),
44          %User{} = user <- User.get_cached_by_nickname(username) do
45       {:ok, represent_user(user, fmt)}
46     else
47       _e ->
48         with %User{} = user <- User.get_cached_by_ap_id(resource) do
49           {:ok, represent_user(user, fmt)}
50         else
51           _e ->
52             {:error, "Couldn't find user"}
53         end
54     end
55   end
56
57   defp gather_links(%User{} = user) do
58     [
59       %{
60         "rel" => "http://webfinger.net/rel/profile-page",
61         "type" => "text/html",
62         "href" => user.ap_id
63       }
64     ] ++ Publisher.gather_webfinger_links(user)
65   end
66
67   defp gather_aliases(%User{} = user) do
68     [user.ap_id | user.also_known_as]
69   end
70
71   def represent_user(user, "JSON") do
72     %{
73       "subject" => "acct:#{user.nickname}@#{host()}",
74       "aliases" => gather_aliases(user),
75       "links" => gather_links(user)
76     }
77   end
78
79   def represent_user(user, "XML") do
80     aliases =
81       user
82       |> gather_aliases()
83       |> Enum.map(&{:Alias, &1})
84
85     links =
86       gather_links(user)
87       |> Enum.map(fn link -> {:Link, link} end)
88
89     {
90       :XRD,
91       %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
92       [
93         {:Subject, "acct:#{user.nickname}@#{host()}"}
94       ] ++ aliases ++ links
95     }
96     |> XmlBuilder.to_doc()
97   end
98
99   def host do
100     Pleroma.Config.get([__MODULE__, :domain]) || Pleroma.Web.Endpoint.host()
101   end
102
103   defp webfinger_from_xml(body) do
104     with {:ok, doc} <- XML.parse_document(body) do
105       subject = XML.string_from_xpath("//Subject", doc)
106
107       subscribe_address =
108         ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template}
109         |> XML.string_from_xpath(doc)
110
111       ap_id =
112         ~s{//Link[@rel="self" and @type="application/activity+json"]/@href}
113         |> XML.string_from_xpath(doc)
114
115       data = %{
116         "subject" => subject,
117         "subscribe_address" => subscribe_address,
118         "ap_id" => ap_id
119       }
120
121       {:ok, data}
122     end
123   end
124
125   defp webfinger_from_json(body) do
126     with {:ok, doc} <- Jason.decode(body) do
127       data =
128         Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
129           case {link["type"], link["rel"]} do
130             {"application/activity+json", "self"} ->
131               Map.put(data, "ap_id", link["href"])
132
133             {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
134               Map.put(data, "ap_id", link["href"])
135
136             {nil, "http://ostatus.org/schema/1.0/subscribe"} ->
137               Map.put(data, "subscribe_address", link["template"])
138
139             _ ->
140               Logger.debug("Unhandled type: #{inspect(link["type"])}")
141               data
142           end
143         end)
144
145       {:ok, data}
146     end
147   end
148
149   def get_template_from_xml(body) do
150     xpath = "//Link[@rel='lrdd']/@template"
151
152     with {:ok, doc} <- XML.parse_document(body),
153          template when template != nil <- XML.string_from_xpath(xpath, doc) do
154       {:ok, template}
155     end
156   end
157
158   def find_lrdd_template(domain) do
159     # WebFinger is restricted to HTTPS - https://tools.ietf.org/html/rfc7033#section-9.1
160     meta_url = "https://#{domain}/.well-known/host-meta"
161
162     with {:ok, %{status: status, body: body}} when status in 200..299 <- HTTP.get(meta_url) do
163       get_template_from_xml(body)
164     else
165       error ->
166         Logger.warning("Can't find LRDD template in #{inspect(meta_url)}: #{inspect(error)}")
167         {:error, :lrdd_not_found}
168     end
169   end
170
171   defp get_address_from_domain(domain, encoded_account) when is_binary(domain) do
172     case find_lrdd_template(domain) do
173       {:ok, template} ->
174         String.replace(template, "{uri}", encoded_account)
175
176       _ ->
177         "https://#{domain}/.well-known/webfinger?resource=#{encoded_account}"
178     end
179   end
180
181   defp get_address_from_domain(_, _), do: {:error, :webfinger_no_domain}
182
183   @spec finger(String.t()) :: {:ok, map()} | {:error, any()}
184   def finger(account) do
185     account = String.trim_leading(account, "@")
186
187     domain =
188       with [_name, domain] <- String.split(account, "@") do
189         domain
190       else
191         _e ->
192           URI.parse(account).host
193       end
194
195     encoded_account = URI.encode("acct:#{account}")
196
197     with address when is_binary(address) <- get_address_from_domain(domain, encoded_account),
198          {:ok, %{status: status, body: body, headers: headers}} when status in 200..299 <-
199            HTTP.get(
200              address,
201              [{"accept", "application/xrd+xml,application/jrd+json"}]
202            ) do
203       case List.keyfind(headers, "content-type", 0) do
204         {_, content_type} ->
205           case Plug.Conn.Utils.media_type(content_type) do
206             {:ok, "application", subtype, _} when subtype in ~w(xrd+xml xml) ->
207               webfinger_from_xml(body)
208
209             {:ok, "application", subtype, _} when subtype in ~w(jrd+json json) ->
210               webfinger_from_json(body)
211
212             _ ->
213               {:error, {:content_type, content_type}}
214           end
215
216         _ ->
217           {:error, {:content_type, nil}}
218       end
219     else
220       error ->
221         Logger.debug("Couldn't finger #{account}: #{inspect(error)}")
222         error
223     end
224   end
225 end