Merge remote-tracking branch 'upstream/develop' into restrict-domain
[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 {:swarm, :node_blacklist},
160 {:logger, :backends}
161 ]
162
163 Enum.any?(full_key_update, fn
164 {s_group, s_key} ->
165 group == s_group and ((is_list(s_key) and key in s_key) or key == s_key)
166 end)
167 end
168
169 @spec delete(ConfigDB.t() | map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
170 def delete(%ConfigDB{} = config), do: Repo.delete(config)
171
172 def delete(params) do
173 search_opts = Map.delete(params, :subkeys)
174
175 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
176 {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
177 keys <- Enum.map(sub_keys, &string_to_elixir_types(&1)),
178 {_, config, new_value} when new_value != [] <-
179 {:partial_remove, config, Keyword.drop(config.value, keys)} do
180 update(config, %{value: new_value})
181 else
182 {:partial_remove, config, []} ->
183 Repo.delete(config)
184
185 {config, nil} ->
186 Repo.delete(config)
187
188 nil ->
189 err =
190 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
191
192 {:error, err}
193 end
194 end
195
196 @spec to_json_types(term()) :: map() | list() | boolean() | String.t()
197 def to_json_types(entity) when is_list(entity) do
198 Enum.map(entity, &to_json_types/1)
199 end
200
201 def to_json_types(%Regex{} = entity), do: inspect(entity)
202
203 def to_json_types(entity) when is_map(entity) do
204 Map.new(entity, fn {k, v} -> {to_json_types(k), to_json_types(v)} end)
205 end
206
207 def to_json_types({:args, args}) when is_list(args) do
208 arguments =
209 Enum.map(args, fn
210 arg when is_tuple(arg) -> inspect(arg)
211 arg -> to_json_types(arg)
212 end)
213
214 %{"tuple" => [":args", arguments]}
215 end
216
217 def to_json_types({:proxy_url, {type, :localhost, port}}) do
218 %{"tuple" => [":proxy_url", %{"tuple" => [to_json_types(type), "localhost", port]}]}
219 end
220
221 def to_json_types({:proxy_url, {type, host, port}}) when is_tuple(host) do
222 ip =
223 host
224 |> :inet_parse.ntoa()
225 |> to_string()
226
227 %{
228 "tuple" => [
229 ":proxy_url",
230 %{"tuple" => [to_json_types(type), ip, port]}
231 ]
232 }
233 end
234
235 def to_json_types({:proxy_url, {type, host, port}}) do
236 %{
237 "tuple" => [
238 ":proxy_url",
239 %{"tuple" => [to_json_types(type), to_string(host), port]}
240 ]
241 }
242 end
243
244 def to_json_types({:partial_chain, entity}),
245 do: %{"tuple" => [":partial_chain", inspect(entity)]}
246
247 def to_json_types(entity) when is_tuple(entity) do
248 value =
249 entity
250 |> Tuple.to_list()
251 |> to_json_types()
252
253 %{"tuple" => value}
254 end
255
256 def to_json_types(entity) when is_binary(entity), do: entity
257
258 def to_json_types(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
259 entity
260 end
261
262 def to_json_types(entity) when entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
263 ":#{entity}"
264 end
265
266 def to_json_types(entity) when is_atom(entity), do: inspect(entity)
267
268 @spec to_elixir_types(boolean() | String.t() | map() | list()) :: term()
269 def to_elixir_types(%{"tuple" => [":args", args]}) when is_list(args) do
270 arguments =
271 Enum.map(args, fn arg ->
272 if String.contains?(arg, ["{", "}"]) do
273 {elem, []} = Code.eval_string(arg)
274 elem
275 else
276 to_elixir_types(arg)
277 end
278 end)
279
280 {:args, arguments}
281 end
282
283 def to_elixir_types(%{"tuple" => [":proxy_url", %{"tuple" => [type, host, port]}]}) do
284 {:proxy_url, {string_to_elixir_types(type), parse_host(host), port}}
285 end
286
287 def to_elixir_types(%{"tuple" => [":partial_chain", entity]}) do
288 {partial_chain, []} =
289 entity
290 |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
291 |> Code.eval_string()
292
293 {:partial_chain, partial_chain}
294 end
295
296 def to_elixir_types(%{"tuple" => entity}) do
297 Enum.reduce(entity, {}, &Tuple.append(&2, to_elixir_types(&1)))
298 end
299
300 def to_elixir_types(entity) when is_map(entity) do
301 Map.new(entity, fn {k, v} -> {to_elixir_types(k), to_elixir_types(v)} end)
302 end
303
304 def to_elixir_types(entity) when is_list(entity) do
305 Enum.map(entity, &to_elixir_types/1)
306 end
307
308 def to_elixir_types(entity) when is_binary(entity) do
309 entity
310 |> String.trim()
311 |> string_to_elixir_types()
312 end
313
314 def to_elixir_types(entity), do: entity
315
316 @spec string_to_elixir_types(String.t()) ::
317 atom() | Regex.t() | module() | String.t() | no_return()
318 def string_to_elixir_types("~r" <> _pattern = regex) do
319 pattern =
320 ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
321
322 delimiters = ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
323
324 with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
325 Regex.named_captures(pattern, regex),
326 {:ok, {leading, closing}} <- find_valid_delimiter(delimiters, pattern, regex_delimiter),
327 {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
328 result
329 end
330 end
331
332 def string_to_elixir_types(":" <> atom), do: String.to_atom(atom)
333
334 def string_to_elixir_types(value) do
335 if module_name?(value) do
336 String.to_existing_atom("Elixir." <> value)
337 else
338 value
339 end
340 end
341
342 defp parse_host("localhost"), do: :localhost
343
344 defp parse_host(host) do
345 charlist = to_charlist(host)
346
347 case :inet.parse_address(charlist) do
348 {:error, :einval} ->
349 charlist
350
351 {:ok, ip} ->
352 ip
353 end
354 end
355
356 defp find_valid_delimiter([], _string, _) do
357 raise(ArgumentError, message: "valid delimiter for Regex expression not found")
358 end
359
360 defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
361 when is_tuple(delimiter) do
362 if String.contains?(pattern, closing) do
363 find_valid_delimiter(others, pattern, regex_delimiter)
364 else
365 {:ok, {leading, closing}}
366 end
367 end
368
369 defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
370 if String.contains?(pattern, delimiter) do
371 find_valid_delimiter(others, pattern, regex_delimiter)
372 else
373 {:ok, {delimiter, delimiter}}
374 end
375 end
376
377 @spec module_name?(String.t()) :: boolean()
378 def module_name?(string) do
379 Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Quack|Ueberauth|Swoosh)\./, string) or
380 string in ["Oban", "Ueberauth", "ExSyslogger"]
381 end
382 end