Don't crypt raw iolists.
[akkoma] / lib / pleroma / web / websub / websub.ex
1 defmodule Pleroma.Web.Websub do
2 alias Pleroma.Repo
3 alias Pleroma.Web.Websub.{WebsubServerSubscription, WebsubClientSubscription}
4 alias Pleroma.Web.OStatus.FeedRepresenter
5 alias Pleroma.Web.{XML, Endpoint, OStatus}
6 alias Pleroma.Web.Router.Helpers
7 require Logger
8
9 import Ecto.Query
10
11 def verify(subscription, getter \\ &HTTPoison.get/3 ) do
12 challenge = Base.encode16(:crypto.strong_rand_bytes(8))
13 lease_seconds = NaiveDateTime.diff(subscription.valid_until, subscription.updated_at) |> to_string
14
15 params = %{
16 "hub.challenge": challenge,
17 "hub.lease_seconds": lease_seconds,
18 "hub.topic": subscription.topic,
19 "hub.mode": "subscribe"
20 }
21
22 url = hd(String.split(subscription.callback, "?"))
23 query = URI.parse(subscription.callback).query || ""
24 params = Map.merge(params, URI.decode_query(query))
25 with {:ok, response} <- getter.(url, [], [params: params]),
26 ^challenge <- response.body
27 do
28 changeset = Ecto.Changeset.change(subscription, %{state: "active"})
29 Repo.update(changeset)
30 else _e ->
31 changeset = Ecto.Changeset.change(subscription, %{state: "rejected"})
32 {:ok, subscription } = Repo.update(changeset)
33 {:error, subscription}
34 end
35 end
36
37 def publish(topic, user, activity) do
38 query = from sub in WebsubServerSubscription,
39 where: sub.topic == ^topic and sub.state == "active"
40 subscriptions = Repo.all(query)
41 Enum.each(subscriptions, fn(sub) ->
42 response = FeedRepresenter.to_simple_form(user, [activity], [user])
43 |> :xmerl.export_simple(:xmerl_xml)
44 |> to_string
45
46 signature = sign(sub.secret, response)
47 HTTPoison.post(sub.callback, response, [
48 {"Content-Type", "application/atom+xml"},
49 {"X-Hub-Signature", "sha1=#{signature}"}
50 ])
51 end)
52 end
53
54 def sign(secret, doc) do
55 :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16
56 end
57
58 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
59 with {:ok, topic} <- valid_topic(params, user),
60 {:ok, lease_time} <- lease_time(params),
61 secret <- params["hub.secret"],
62 callback <- params["hub.callback"]
63 do
64 subscription = get_subscription(topic, callback)
65 data = %{
66 state: subscription.state || "requested",
67 topic: topic,
68 secret: secret,
69 callback: callback
70 }
71
72 change = Ecto.Changeset.change(subscription, data)
73 websub = Repo.insert_or_update!(change)
74
75 change = Ecto.Changeset.change(websub, %{valid_until: NaiveDateTime.add(websub.updated_at, lease_time)})
76 websub = Repo.update!(change)
77
78 Pleroma.Web.Federator.enqueue(:verify_websub, websub)
79
80 {:ok, websub}
81 else {:error, reason} ->
82 Logger.debug("Couldn't create subscription.")
83 Logger.debug(inspect(reason))
84
85 {:error, reason}
86 end
87 end
88
89 defp get_subscription(topic, callback) do
90 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) || %WebsubServerSubscription{}
91 end
92
93 # Temp hack for mastodon.
94 defp lease_time(%{"hub.lease_seconds" => ""}) do
95 {:ok, 60 * 60 * 24 * 3} # three days
96 end
97
98 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
99 {:ok, String.to_integer(lease_seconds)}
100 end
101
102 defp lease_time(_) do
103 {:ok, 60 * 60 * 24 * 3} # three days
104 end
105
106 defp valid_topic(%{"hub.topic" => topic}, user) do
107 if topic == OStatus.feed_path(user) do
108 {:ok, OStatus.feed_path(user)}
109 else
110 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
111 end
112 end
113
114 def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
115 topic = subscribed.info["topic"]
116 # FIXME: Race condition, use transactions
117 {:ok, subscription} = with subscription when not is_nil(subscription) <- Repo.get_by(WebsubClientSubscription, topic: topic) do
118 subscribers = [subscriber.ap_id, subscription.subscribers] |> Enum.uniq
119 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
120 Repo.update(change)
121 else _e ->
122 subscription = %WebsubClientSubscription{
123 topic: topic,
124 hub: subscribed.info["hub"],
125 subscribers: [subscriber.ap_id],
126 state: "requested",
127 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64,
128 user: subscribed
129 }
130 Repo.insert(subscription)
131 end
132 requester.(subscription)
133 end
134
135 def gather_feed_data(topic, getter \\ &HTTPoison.get/1) do
136 with {:ok, response} <- getter.(topic),
137 status_code when status_code in 200..299 <- response.status_code,
138 body <- response.body,
139 doc <- XML.parse_document(body),
140 uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
141 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
142
143 name = XML.string_from_xpath("/feed/author[1]/name", doc)
144 preferredUsername = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
145 displayName = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
146 avatar = OStatus.make_avatar_object(doc)
147
148 {:ok, %{
149 uri: uri,
150 hub: hub,
151 nickname: preferredUsername || name,
152 name: displayName || name,
153 host: URI.parse(uri).host,
154 avatar: avatar
155 }}
156 else e ->
157 {:error, e}
158 end
159 end
160
161 def request_subscription(websub, poster \\ &HTTPoison.post/3, timeout \\ 10_000) do
162 data = [
163 "hub.mode": "subscribe",
164 "hub.topic": websub.topic,
165 "hub.secret": websub.secret,
166 "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
167 ]
168
169 # This checks once a second if we are confirmed yet
170 websub_checker = fn ->
171 helper = fn (helper) ->
172 :timer.sleep(1000)
173 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
174 if websub, do: websub, else: helper.(helper)
175 end
176 helper.(helper)
177 end
178
179 task = Task.async(websub_checker)
180
181 with {:ok, %{status_code: 202}} <- poster.(websub.hub, {:form, data}, ["Content-type": "application/x-www-form-urlencoded"]),
182 {:ok, websub} <- Task.yield(task, timeout) do
183 {:ok, websub}
184 else e ->
185 Task.shutdown(task)
186
187 change = Ecto.Changeset.change(websub, %{state: "rejected"})
188 {:ok, websub} = Repo.update(change)
189
190 Logger.debug("Couldn't confirm subscription: #{inspect(websub)}")
191 Logger.debug("error: #{inspect(e)}")
192
193 {:error, websub}
194 end
195 end
196 end