Use Logger.info for {:reject, reason}
[akkoma] / lib / pleroma / config / config_db.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.ConfigDB do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9 import Ecto.Query, only: [select: 3]
10 import Pleroma.Web.Gettext
11
12 alias __MODULE__
13 alias Pleroma.Repo
14
15 @type t :: %__MODULE__{}
16
17 @full_subkey_update [
18 {:pleroma, :assets, :mascots},
19 {:pleroma, :emoji, :groups},
20 {:pleroma, :workers, :retries},
21 {:pleroma, :mrf_subchain, :match_actor},
22 {:pleroma, :mrf_keyword, :replace}
23 ]
24
25 schema "config" do
26 field(:key, Pleroma.EctoType.Config.Atom)
27 field(:group, Pleroma.EctoType.Config.Atom)
28 field(:value, Pleroma.EctoType.Config.BinaryValue)
29 field(:db, {:array, :string}, virtual: true, default: [])
30
31 timestamps()
32 end
33
34 @spec get_all_as_keyword() :: keyword()
35 def get_all_as_keyword do
36 ConfigDB
37 |> select([c], {c.group, c.key, c.value})
38 |> Repo.all()
39 |> Enum.reduce([], fn {group, key, value}, acc ->
40 Keyword.update(acc, group, [{key, value}], &Keyword.merge(&1, [{key, value}]))
41 end)
42 end
43
44 @spec get_by_params(map()) :: ConfigDB.t() | nil
45 def get_by_params(params), do: Repo.get_by(ConfigDB, params)
46
47 @spec changeset(ConfigDB.t(), map()) :: Changeset.t()
48 def changeset(config, params \\ %{}) do
49 config
50 |> cast(params, [:key, :group, :value])
51 |> validate_required([:key, :group, :value])
52 |> unique_constraint(:key, name: :config_group_key_index)
53 end
54
55 defp create(params) do
56 %ConfigDB{}
57 |> changeset(params)
58 |> Repo.insert()
59 end
60
61 defp update(%ConfigDB{} = config, %{value: value}) do
62 config
63 |> changeset(%{value: value})
64 |> Repo.update()
65 end
66
67 @spec get_db_keys(keyword(), any()) :: [String.t()]
68 def get_db_keys(value, key) do
69 keys =
70 if Keyword.keyword?(value) do
71 Keyword.keys(value)
72 else
73 [key]
74 end
75
76 Enum.map(keys, &to_json_types(&1))
77 end
78
79 @spec merge_group(atom(), atom(), keyword(), keyword()) :: keyword()
80 def merge_group(group, key, old_value, new_value) do
81 new_keys = to_mapset(new_value)
82
83 intersect_keys = old_value |> to_mapset() |> MapSet.intersection(new_keys) |> MapSet.to_list()
84
85 merged_value = ConfigDB.merge(old_value, new_value)
86
87 @full_subkey_update
88 |> Enum.map(fn
89 {g, k, subkey} when g == group and k == key ->
90 if subkey in intersect_keys, do: subkey, else: []
91
92 _ ->
93 []
94 end)
95 |> List.flatten()
96 |> Enum.reduce(merged_value, &Keyword.put(&2, &1, new_value[&1]))
97 end
98
99 defp to_mapset(keyword) do
100 keyword
101 |> Keyword.keys()
102 |> MapSet.new()
103 end
104
105 @spec sub_key_full_update?(atom(), atom(), [Keyword.key()]) :: boolean()
106 def sub_key_full_update?(group, key, subkeys) do
107 Enum.any?(@full_subkey_update, fn {g, k, subkey} ->
108 g == group and k == key and subkey in subkeys
109 end)
110 end
111
112 @spec merge(keyword(), keyword()) :: keyword()
113 def merge(config1, config2) when is_list(config1) and is_list(config2) do
114 Keyword.merge(config1, config2, fn _, app1, app2 ->
115 if Keyword.keyword?(app1) and Keyword.keyword?(app2) do
116 Keyword.merge(app1, app2, &deep_merge/3)
117 else
118 app2
119 end
120 end)
121 end
122
123 defp deep_merge(_key, value1, value2) do
124 if Keyword.keyword?(value1) and Keyword.keyword?(value2) do
125 Keyword.merge(value1, value2, &deep_merge/3)
126 else
127 value2
128 end
129 end
130
131 @spec update_or_create(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
132 def update_or_create(params) do
133 params = Map.put(params, :value, to_elixir_types(params[:value]))
134 search_opts = Map.take(params, [:group, :key])
135
136 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
137 {_, true, config} <- {:partial_update, can_be_partially_updated?(config), config},
138 {_, true, config} <-
139 {:can_be_merged, is_list(params[:value]) and is_list(config.value), config} do
140 new_value = merge_group(config.group, config.key, config.value, params[:value])
141 update(config, %{value: new_value})
142 else
143 {reason, false, config} when reason in [:partial_update, :can_be_merged] ->
144 update(config, params)
145
146 nil ->
147 create(params)
148 end
149 end
150
151 defp can_be_partially_updated?(%ConfigDB{} = config), do: not only_full_update?(config)
152
153 defp only_full_update?(%ConfigDB{group: group, key: key}) do
154 full_key_update = [
155 {:pleroma, :ecto_repos},
156 {:quack, :meta},
157 {:mime, :types},
158 {:cors_plug, [:max_age, :methods, :expose, :headers]},
159 {:auto_linker, :opts},
160 {:swarm, :node_blacklist},
161 {:logger, :backends}
162 ]
163
164 Enum.any?(full_key_update, fn
165 {s_group, s_key} ->
166 group == s_group and ((is_list(s_key) and key in s_key) or key == s_key)
167 end)
168 end
169
170 @spec delete(ConfigDB.t() | map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
171 def delete(%ConfigDB{} = config), do: Repo.delete(config)
172
173 def delete(params) do
174 search_opts = Map.delete(params, :subkeys)
175
176 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
177 {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
178 keys <- Enum.map(sub_keys, &string_to_elixir_types(&1)),
179 {_, config, new_value} when new_value != [] <-
180 {:partial_remove, config, Keyword.drop(config.value, keys)} do
181 update(config, %{value: new_value})
182 else
183 {:partial_remove, config, []} ->
184 Repo.delete(config)
185
186 {config, nil} ->
187 Repo.delete(config)
188
189 nil ->
190 err =
191 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
192
193 {:error, err}
194 end
195 end
196
197 @spec to_json_types(term()) :: map() | list() | boolean() | String.t()
198 def to_json_types(entity) when is_list(entity) do
199 Enum.map(entity, &to_json_types/1)
200 end
201
202 def to_json_types(%Regex{} = entity), do: inspect(entity)
203
204 def to_json_types(entity) when is_map(entity) do
205 Map.new(entity, fn {k, v} -> {to_json_types(k), to_json_types(v)} end)
206 end
207
208 def to_json_types({:args, args}) when is_list(args) do
209 arguments =
210 Enum.map(args, fn
211 arg when is_tuple(arg) -> inspect(arg)
212 arg -> to_json_types(arg)
213 end)
214
215 %{"tuple" => [":args", arguments]}
216 end
217
218 def to_json_types({:proxy_url, {type, :localhost, port}}) do
219 %{"tuple" => [":proxy_url", %{"tuple" => [to_json_types(type), "localhost", port]}]}
220 end
221
222 def to_json_types({:proxy_url, {type, host, port}}) when is_tuple(host) do
223 ip =
224 host
225 |> :inet_parse.ntoa()
226 |> to_string()
227
228 %{
229 "tuple" => [
230 ":proxy_url",
231 %{"tuple" => [to_json_types(type), ip, port]}
232 ]
233 }
234 end
235
236 def to_json_types({:proxy_url, {type, host, port}}) do
237 %{
238 "tuple" => [
239 ":proxy_url",
240 %{"tuple" => [to_json_types(type), to_string(host), port]}
241 ]
242 }
243 end
244
245 def to_json_types({:partial_chain, entity}),
246 do: %{"tuple" => [":partial_chain", inspect(entity)]}
247
248 def to_json_types(entity) when is_tuple(entity) do
249 value =
250 entity
251 |> Tuple.to_list()
252 |> to_json_types()
253
254 %{"tuple" => value}
255 end
256
257 def to_json_types(entity) when is_binary(entity), do: entity
258
259 def to_json_types(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
260 entity
261 end
262
263 def to_json_types(entity) when entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
264 ":#{entity}"
265 end
266
267 def to_json_types(entity) when is_atom(entity), do: inspect(entity)
268
269 @spec to_elixir_types(boolean() | String.t() | map() | list()) :: term()
270 def to_elixir_types(%{"tuple" => [":args", args]}) when is_list(args) do
271 arguments =
272 Enum.map(args, fn arg ->
273 if String.contains?(arg, ["{", "}"]) do
274 {elem, []} = Code.eval_string(arg)
275 elem
276 else
277 to_elixir_types(arg)
278 end
279 end)
280
281 {:args, arguments}
282 end
283
284 def to_elixir_types(%{"tuple" => [":proxy_url", %{"tuple" => [type, host, port]}]}) do
285 {:proxy_url, {string_to_elixir_types(type), parse_host(host), port}}
286 end
287
288 def to_elixir_types(%{"tuple" => [":partial_chain", entity]}) do
289 {partial_chain, []} =
290 entity
291 |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
292 |> Code.eval_string()
293
294 {:partial_chain, partial_chain}
295 end
296
297 def to_elixir_types(%{"tuple" => entity}) do
298 Enum.reduce(entity, {}, &Tuple.append(&2, to_elixir_types(&1)))
299 end
300
301 def to_elixir_types(entity) when is_map(entity) do
302 Map.new(entity, fn {k, v} -> {to_elixir_types(k), to_elixir_types(v)} end)
303 end
304
305 def to_elixir_types(entity) when is_list(entity) do
306 Enum.map(entity, &to_elixir_types/1)
307 end
308
309 def to_elixir_types(entity) when is_binary(entity) do
310 entity
311 |> String.trim()
312 |> string_to_elixir_types()
313 end
314
315 def to_elixir_types(entity), do: entity
316
317 @spec string_to_elixir_types(String.t()) ::
318 atom() | Regex.t() | module() | String.t() | no_return()
319 def string_to_elixir_types("~r" <> _pattern = regex) do
320 pattern =
321 ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
322
323 delimiters = ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
324
325 with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
326 Regex.named_captures(pattern, regex),
327 {:ok, {leading, closing}} <- find_valid_delimiter(delimiters, pattern, regex_delimiter),
328 {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
329 result
330 end
331 end
332
333 def string_to_elixir_types(":" <> atom), do: String.to_atom(atom)
334
335 def string_to_elixir_types(value) do
336 if module_name?(value) do
337 String.to_existing_atom("Elixir." <> value)
338 else
339 value
340 end
341 end
342
343 defp parse_host("localhost"), do: :localhost
344
345 defp parse_host(host) do
346 charlist = to_charlist(host)
347
348 case :inet.parse_address(charlist) do
349 {:error, :einval} ->
350 charlist
351
352 {:ok, ip} ->
353 ip
354 end
355 end
356
357 defp find_valid_delimiter([], _string, _) do
358 raise(ArgumentError, message: "valid delimiter for Regex expression not found")
359 end
360
361 defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
362 when is_tuple(delimiter) do
363 if String.contains?(pattern, closing) do
364 find_valid_delimiter(others, pattern, regex_delimiter)
365 else
366 {:ok, {leading, closing}}
367 end
368 end
369
370 defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
371 if String.contains?(pattern, delimiter) do
372 find_valid_delimiter(others, pattern, regex_delimiter)
373 else
374 {:ok, {delimiter, delimiter}}
375 end
376 end
377
378 @spec module_name?(String.t()) :: boolean()
379 def module_name?(string) do
380 Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Quack|Ueberauth|Swoosh)\./, string) or
381 string in ["Oban", "Ueberauth", "ExSyslogger"]
382 end
383 end