fix tests
[akkoma] / lib / pleroma / web / websub / websub.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.Websub do
6 alias Ecto.Changeset
7 alias Pleroma.Repo
8 alias Pleroma.Instances
9 alias Pleroma.Web.Websub.{WebsubServerSubscription, WebsubClientSubscription}
10 alias Pleroma.Web.OStatus.FeedRepresenter
11 alias Pleroma.Web.{XML, Endpoint, OStatus, Federator}
12 alias Pleroma.Web.Router.Helpers
13 require Logger
14
15 import Ecto.Query
16
17 @httpoison Application.get_env(:pleroma, :httpoison)
18
19 def verify(subscription, getter \\ &@httpoison.get/3) do
20 challenge = Base.encode16(:crypto.strong_rand_bytes(8))
21 lease_seconds = NaiveDateTime.diff(subscription.valid_until, subscription.updated_at)
22 lease_seconds = lease_seconds |> to_string
23
24 params = %{
25 "hub.challenge": challenge,
26 "hub.lease_seconds": lease_seconds,
27 "hub.topic": subscription.topic,
28 "hub.mode": "subscribe"
29 }
30
31 url = hd(String.split(subscription.callback, "?"))
32 query = URI.parse(subscription.callback).query || ""
33 params = Map.merge(params, URI.decode_query(query))
34
35 with {:ok, response} <- getter.(url, [], params: params),
36 ^challenge <- response.body do
37 changeset = Changeset.change(subscription, %{state: "active"})
38 Repo.update(changeset)
39 else
40 e ->
41 Logger.debug("Couldn't verify subscription")
42 Logger.debug(inspect(e))
43 {:error, subscription}
44 end
45 end
46
47 @supported_activities [
48 "Create",
49 "Follow",
50 "Like",
51 "Announce",
52 "Undo",
53 "Delete"
54 ]
55 def publish(topic, user, %{data: %{"type" => type}} = activity)
56 when type in @supported_activities do
57 response =
58 user
59 |> FeedRepresenter.to_simple_form([activity], [user])
60 |> :xmerl.export_simple(:xmerl_xml)
61 |> to_string
62
63 query =
64 from(
65 sub in WebsubServerSubscription,
66 where: sub.topic == ^topic and sub.state == "active",
67 where: fragment("? > (NOW() at time zone 'UTC')", sub.valid_until)
68 )
69
70 subscriptions = Repo.all(query)
71
72 callbacks = Enum.map(subscriptions, & &1.callback)
73 reachable_callbacks_metadata = Instances.filter_reachable(callbacks)
74 reachable_callbacks = Map.keys(reachable_callbacks_metadata)
75
76 subscriptions
77 |> Enum.filter(&(&1.callback in reachable_callbacks))
78 |> Enum.each(fn sub ->
79 data = %{
80 xml: response,
81 topic: topic,
82 callback: sub.callback,
83 secret: sub.secret,
84 unreachable_since: reachable_callbacks_metadata[sub.callback]
85 }
86
87 Federator.publish_single_websub(data)
88 end)
89 end
90
91 def publish(_, _, _), do: ""
92
93 def sign(secret, doc) do
94 :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16() |> String.downcase()
95 end
96
97 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
98 with {:ok, topic} <- valid_topic(params, user),
99 {:ok, lease_time} <- lease_time(params),
100 secret <- params["hub.secret"],
101 callback <- params["hub.callback"] do
102 subscription = get_subscription(topic, callback)
103
104 data = %{
105 state: subscription.state || "requested",
106 topic: topic,
107 secret: secret,
108 callback: callback
109 }
110
111 change = Changeset.change(subscription, data)
112 websub = Repo.insert_or_update!(change)
113
114 change =
115 Changeset.change(websub, %{valid_until: NaiveDateTime.add(websub.updated_at, lease_time)})
116
117 websub = Repo.update!(change)
118
119 Federator.verify_websub(websub)
120
121 {:ok, websub}
122 else
123 {:error, reason} ->
124 Logger.debug("Couldn't create subscription")
125 Logger.debug(inspect(reason))
126
127 {:error, reason}
128 end
129 end
130
131 def incoming_subscription_request(user, params) do
132 Logger.info("Unhandled WebSub request for #{user.nickname}: #{inspect(params)}")
133
134 {:error, "Invalid WebSub request"}
135 end
136
137 defp get_subscription(topic, callback) do
138 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) ||
139 %WebsubServerSubscription{}
140 end
141
142 # Temp hack for mastodon.
143 defp lease_time(%{"hub.lease_seconds" => ""}) do
144 # three days
145 {:ok, 60 * 60 * 24 * 3}
146 end
147
148 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
149 {:ok, String.to_integer(lease_seconds)}
150 end
151
152 defp lease_time(_) do
153 # three days
154 {:ok, 60 * 60 * 24 * 3}
155 end
156
157 defp valid_topic(%{"hub.topic" => topic}, user) do
158 if topic == OStatus.feed_path(user) do
159 {:ok, OStatus.feed_path(user)}
160 else
161 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
162 end
163 end
164
165 def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
166 topic = subscribed.info.topic
167 # FIXME: Race condition, use transactions
168 {:ok, subscription} =
169 with subscription when not is_nil(subscription) <-
170 Repo.get_by(WebsubClientSubscription, topic: topic) do
171 subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq()
172 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
173 Repo.update(change)
174 else
175 _e ->
176 subscription = %WebsubClientSubscription{
177 topic: topic,
178 hub: subscribed.info.hub,
179 subscribers: [subscriber.ap_id],
180 state: "requested",
181 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64(),
182 user: subscribed
183 }
184
185 Repo.insert(subscription)
186 end
187
188 requester.(subscription)
189 end
190
191 def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
192 with {:ok, response} <- getter.(topic),
193 status when status in 200..299 <- response.status,
194 body <- response.body,
195 doc <- XML.parse_document(body),
196 uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
197 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
198 name = XML.string_from_xpath("/feed/author[1]/name", doc)
199 preferredUsername = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
200 displayName = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
201 avatar = OStatus.make_avatar_object(doc)
202 bio = XML.string_from_xpath("/feed/author[1]/summary", doc)
203
204 {:ok,
205 %{
206 "uri" => uri,
207 "hub" => hub,
208 "nickname" => preferredUsername || name,
209 "name" => displayName || name,
210 "host" => URI.parse(uri).host,
211 "avatar" => avatar,
212 "bio" => bio
213 }}
214 else
215 e ->
216 {:error, e}
217 end
218 end
219
220 def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
221 data = [
222 "hub.mode": "subscribe",
223 "hub.topic": websub.topic,
224 "hub.secret": websub.secret,
225 "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
226 ]
227
228 # This checks once a second if we are confirmed yet
229 websub_checker = fn ->
230 helper = fn helper ->
231 :timer.sleep(1000)
232 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
233 if websub, do: websub, else: helper.(helper)
234 end
235
236 helper.(helper)
237 end
238
239 task = Task.async(websub_checker)
240
241 with {:ok, %{status: 202}} <-
242 poster.(websub.hub, {:form, data}, "Content-type": "application/x-www-form-urlencoded"),
243 {:ok, websub} <- Task.yield(task, timeout) do
244 {:ok, websub}
245 else
246 e ->
247 Task.shutdown(task)
248
249 change = Ecto.Changeset.change(websub, %{state: "rejected"})
250 {:ok, websub} = Repo.update(change)
251
252 Logger.debug(fn -> "Couldn't confirm subscription: #{inspect(websub)}" end)
253 Logger.debug(fn -> "error: #{inspect(e)}" end)
254
255 {:error, websub}
256 end
257 end
258
259 def refresh_subscriptions(delta \\ 60 * 60 * 24) do
260 Logger.debug("Refreshing subscriptions")
261
262 cut_off = NaiveDateTime.add(NaiveDateTime.utc_now(), delta)
263
264 query = from(sub in WebsubClientSubscription, where: sub.valid_until < ^cut_off)
265
266 subs = Repo.all(query)
267
268 Enum.each(subs, fn sub ->
269 Federator.request_subscription(sub)
270 end)
271 end
272
273 def publish_one(%{xml: xml, topic: topic, callback: callback, secret: secret} = params) do
274 signature = sign(secret || "", xml)
275 Logger.info(fn -> "Pushing #{topic} to #{callback}" end)
276
277 with {:ok, %{status: code}} when code in 200..299 <-
278 @httpoison.post(
279 callback,
280 xml,
281 [
282 {"Content-Type", "application/atom+xml"},
283 {"X-Hub-Signature", "sha1=#{signature}"}
284 ]
285 ) do
286 if !Map.has_key?(params, :unreachable_since) || params[:unreachable_since],
287 do: Instances.set_reachable(callback)
288
289 Logger.info(fn -> "Pushed to #{callback}, code #{code}" end)
290 {:ok, code}
291 else
292 {_post_result, response} ->
293 unless params[:unreachable_since], do: Instances.set_reachable(callback)
294 Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(response)}" end)
295 {:error, response}
296 end
297 end
298 end