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