Merge remote-tracking branch 'pleroma/develop' into feature/disable-account
[akkoma] / lib / pleroma / web / web_finger / web_finger.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.WebFinger do
6 @httpoison Application.get_env(:pleroma, :httpoison)
7
8 alias Pleroma.User
9 alias Pleroma.Web
10 alias Pleroma.Web.Federator.Publisher
11 alias Pleroma.Web.Salmon
12 alias Pleroma.Web.XML
13 alias Pleroma.XmlBuilder
14 require Jason
15 require Logger
16
17 def host_meta do
18 base_url = Web.base_url()
19
20 {
21 :XRD,
22 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
23 {
24 :Link,
25 %{
26 rel: "lrdd",
27 type: "application/xrd+xml",
28 template: "#{base_url}/.well-known/webfinger?resource={uri}"
29 }
30 }
31 }
32 |> XmlBuilder.to_doc()
33 end
34
35 def webfinger(resource, fmt) when fmt in ["XML", "JSON"] do
36 host = Pleroma.Web.Endpoint.host()
37 regex = ~r/(acct:)?(?<username>\w+)@#{host}/
38
39 with %{"username" => username} <- Regex.named_captures(regex, resource),
40 %User{} = user <- User.get_cached_by_nickname(username) do
41 {:ok, represent_user(user, fmt)}
42 else
43 _e ->
44 with %User{} = user <- User.get_cached_by_ap_id(resource) do
45 {:ok, represent_user(user, fmt)}
46 else
47 _e ->
48 {:error, "Couldn't find user"}
49 end
50 end
51 end
52
53 defp gather_links(%User{} = user) do
54 [
55 %{
56 "rel" => "http://webfinger.net/rel/profile-page",
57 "type" => "text/html",
58 "href" => user.ap_id
59 }
60 ] ++ Publisher.gather_webfinger_links(user)
61 end
62
63 def represent_user(user, "JSON") do
64 {:ok, user} = ensure_keys_present(user)
65
66 %{
67 "subject" => "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}",
68 "aliases" => [user.ap_id],
69 "links" => gather_links(user)
70 }
71 end
72
73 def represent_user(user, "XML") do
74 {:ok, user} = ensure_keys_present(user)
75
76 links =
77 gather_links(user)
78 |> Enum.map(fn link -> {:Link, link} end)
79
80 {
81 :XRD,
82 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
83 [
84 {:Subject, "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}"},
85 {:Alias, user.ap_id}
86 ] ++ links
87 }
88 |> XmlBuilder.to_doc()
89 end
90
91 # This seems a better fit in Salmon
92 def ensure_keys_present(user) do
93 info = user.info
94
95 if info.keys do
96 {:ok, user}
97 else
98 {:ok, pem} = Salmon.generate_rsa_pem()
99
100 info_cng =
101 info
102 |> Pleroma.User.Info.set_keys(pem)
103
104 cng =
105 Ecto.Changeset.change(user)
106 |> Ecto.Changeset.put_embed(:info, info_cng)
107
108 User.update_and_set_cache(cng)
109 end
110 end
111
112 defp get_magic_key(magic_key) do
113 "data:application/magic-public-key," <> magic_key = magic_key
114 {:ok, magic_key}
115 rescue
116 MatchError -> {:error, "Missing magic key data."}
117 end
118
119 defp webfinger_from_xml(doc) do
120 with magic_key <- XML.string_from_xpath(~s{//Link[@rel="magic-public-key"]/@href}, doc),
121 {:ok, magic_key} <- get_magic_key(magic_key),
122 topic <-
123 XML.string_from_xpath(
124 ~s{//Link[@rel="http://schemas.google.com/g/2010#updates-from"]/@href},
125 doc
126 ),
127 subject <- XML.string_from_xpath("//Subject", doc),
128 salmon <- XML.string_from_xpath(~s{//Link[@rel="salmon"]/@href}, doc),
129 subscribe_address <-
130 XML.string_from_xpath(
131 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template},
132 doc
133 ),
134 ap_id <-
135 XML.string_from_xpath(
136 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href},
137 doc
138 ) do
139 data = %{
140 "magic_key" => magic_key,
141 "topic" => topic,
142 "subject" => subject,
143 "salmon" => salmon,
144 "subscribe_address" => subscribe_address,
145 "ap_id" => ap_id
146 }
147
148 {:ok, data}
149 else
150 {:error, e} ->
151 {:error, e}
152
153 e ->
154 {:error, e}
155 end
156 end
157
158 defp webfinger_from_json(doc) do
159 data =
160 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
161 case {link["type"], link["rel"]} do
162 {"application/activity+json", "self"} ->
163 Map.put(data, "ap_id", link["href"])
164
165 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
166 Map.put(data, "ap_id", link["href"])
167
168 {_, "magic-public-key"} ->
169 "data:application/magic-public-key," <> magic_key = link["href"]
170 Map.put(data, "magic_key", magic_key)
171
172 {"application/atom+xml", "http://schemas.google.com/g/2010#updates-from"} ->
173 Map.put(data, "topic", link["href"])
174
175 {_, "salmon"} ->
176 Map.put(data, "salmon", link["href"])
177
178 {_, "http://ostatus.org/schema/1.0/subscribe"} ->
179 Map.put(data, "subscribe_address", link["template"])
180
181 _ ->
182 Logger.debug("Unhandled type: #{inspect(link["type"])}")
183 data
184 end
185 end)
186
187 {:ok, data}
188 end
189
190 def get_template_from_xml(body) do
191 xpath = "//Link[@rel='lrdd']/@template"
192
193 with doc when doc != :error <- XML.parse_document(body),
194 template when template != nil <- XML.string_from_xpath(xpath, doc) do
195 {:ok, template}
196 end
197 end
198
199 def find_lrdd_template(domain) do
200 with {:ok, %{status: status, body: body}} when status in 200..299 <-
201 @httpoison.get("http://#{domain}/.well-known/host-meta", []) do
202 get_template_from_xml(body)
203 else
204 _ ->
205 with {:ok, %{body: body}} <- @httpoison.get("https://#{domain}/.well-known/host-meta", []) do
206 get_template_from_xml(body)
207 else
208 e -> {:error, "Can't find LRDD template: #{inspect(e)}"}
209 end
210 end
211 end
212
213 def finger(account) do
214 account = String.trim_leading(account, "@")
215
216 domain =
217 with [_name, domain] <- String.split(account, "@") do
218 domain
219 else
220 _e ->
221 URI.parse(account).host
222 end
223
224 address =
225 case find_lrdd_template(domain) do
226 {:ok, template} ->
227 String.replace(template, "{uri}", URI.encode(account))
228
229 _ ->
230 "https://#{domain}/.well-known/webfinger?resource=acct:#{account}"
231 end
232
233 with response <-
234 @httpoison.get(
235 address,
236 Accept: "application/xrd+xml,application/jrd+json"
237 ),
238 {:ok, %{status: status, body: body}} when status in 200..299 <- response do
239 doc = XML.parse_document(body)
240
241 if doc != :error do
242 webfinger_from_xml(doc)
243 else
244 with {:ok, doc} <- Jason.decode(body) do
245 webfinger_from_json(doc)
246 else
247 {:error, e} -> e
248 end
249 end
250 else
251 e ->
252 Logger.debug(fn -> "Couldn't finger #{account}" end)
253 Logger.debug(fn -> inspect(e) end)
254 {:error, e}
255 end
256 end
257 end