config_db.ex 10.7 KB
Newer Older
1
# Pleroma: A lightweight social networking server
2
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3
4
# SPDX-License-Identifier: AGPL-3.0-only

Alexander Strizhakov's avatar
Alexander Strizhakov committed
5
defmodule Pleroma.ConfigDB do
6
  use Ecto.Schema
Alexander Strizhakov's avatar
Alexander Strizhakov committed
7

8
  import Ecto.Changeset
9
  import Ecto.Query, only: [select: 3]
10
  import Pleroma.Web.Gettext
Alexander Strizhakov's avatar
Alexander Strizhakov committed
11

12
13
14
15
16
  alias __MODULE__
  alias Pleroma.Repo

  @type t :: %__MODULE__{}

Alexander Strizhakov's avatar
Alexander Strizhakov committed
17
18
19
20
21
22
23
24
  @full_subkey_update [
    {:pleroma, :assets, :mascots},
    {:pleroma, :emoji, :groups},
    {:pleroma, :workers, :retries},
    {:pleroma, :mrf_subchain, :match_actor},
    {:pleroma, :mrf_keyword, :replace}
  ]

25
  schema "config" do
26
27
28
    field(:key, Pleroma.Config.Type.Atom)
    field(:group, Pleroma.Config.Type.Atom)
    field(:value, Pleroma.Config.Type.BinaryValue)
29
    field(:db, {:array, :string}, virtual: true, default: [])
30
31
32
33

    timestamps()
  end

34
35
36
37
38
39
40
41
42
43
  @spec get_all_as_keyword() :: keyword()
  def get_all_as_keyword do
    ConfigDB
    |> select([c], {c.group, c.key, c.value})
    |> Repo.all()
    |> Enum.reduce([], fn {group, key, value}, acc ->
      Keyword.update(acc, group, [{key, value}], &Keyword.merge(&1, [{key, value}]))
    end)
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
44
45
  @spec get_by_params(map()) :: ConfigDB.t() | nil
  def get_by_params(params), do: Repo.get_by(ConfigDB, params)
46

Alexander Strizhakov's avatar
Alexander Strizhakov committed
47
  @spec changeset(ConfigDB.t(), map()) :: Changeset.t()
48
49
  def changeset(config, params \\ %{}) do
    config
50
51
52
    |> cast(params, [:key, :group, :value])
    |> validate_required([:key, :group, :value])
    |> unique_constraint(:key, name: :config_group_key_index)
53
54
  end

55
  defp create(params) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
56
    %ConfigDB{}
57
    |> changeset(params)
58
59
60
    |> Repo.insert()
  end

61
  defp update(%ConfigDB{} = config, %{value: value}) do
62
    config
63
    |> changeset(%{value: value})
64
65
66
    |> Repo.update()
  end

67
  @spec get_db_keys(keyword(), any()) :: [String.t()]
68
  def get_db_keys(value, key) do
69
70
71
72
73
74
75
76
    keys =
      if Keyword.keyword?(value) do
        Keyword.keys(value)
      else
        [key]
      end

    Enum.map(keys, &to_json_types(&1))
77
78
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
79
80
  @spec merge_group(atom(), atom(), keyword(), keyword()) :: keyword()
  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

Alexander Strizhakov's avatar
Alexander Strizhakov committed
85
    merged_value = ConfigDB.merge(old_value, new_value)
86

Alexander Strizhakov's avatar
Alexander Strizhakov committed
87
88
89
90
91
92
93
94
95
    @full_subkey_update
    |> Enum.map(fn
      {g, k, subkey} when g == group and k == key ->
        if subkey in intersect_keys, do: subkey, else: []

      _ ->
        []
    end)
    |> List.flatten()
96
    |> Enum.reduce(merged_value, &Keyword.put(&2, &1, new_value[&1]))
97
98
  end

99
  defp to_mapset(keyword) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
100
101
102
103
104
    keyword
    |> Keyword.keys()
    |> MapSet.new()
  end

105
106
107
108
109
110
111
  @spec sub_key_full_update?(atom(), atom(), [Keyword.key()]) :: boolean()
  def sub_key_full_update?(group, key, subkeys) do
    Enum.any?(@full_subkey_update, fn {g, k, subkey} ->
      g == group and k == key and subkey in subkeys
    end)
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
112
  @spec merge(keyword(), keyword()) :: keyword()
Alexander Strizhakov's avatar
Alexander Strizhakov committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  def merge(config1, config2) when is_list(config1) and is_list(config2) do
    Keyword.merge(config1, config2, fn _, app1, app2 ->
      if Keyword.keyword?(app1) and Keyword.keyword?(app2) do
        Keyword.merge(app1, app2, &deep_merge/3)
      else
        app2
      end
    end)
  end

  defp deep_merge(_key, value1, value2) do
    if Keyword.keyword?(value1) and Keyword.keyword?(value2) do
      Keyword.merge(value1, value2, &deep_merge/3)
    else
      value2
    end
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
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
135
    search_opts = Map.take(params, [:group, :key])

Alexander Strizhakov's avatar
Alexander Strizhakov committed
136
    with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
137
         {_, true, config} <- {:partial_update, can_be_partially_updated?(config), config},
138
139
         {_, true, config} <-
           {:can_be_merged, is_list(params[:value]) and is_list(config.value), config} do
140
141
      new_value = merge_group(config.group, config.key, config.value, params[:value])
      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
149
150
    end
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
151
152
  defp can_be_partially_updated?(%ConfigDB{} = config), do: not only_full_update?(config)

153
154
155
156
157
158
159
160
161
162
163
164
165
166
  defp only_full_update?(%ConfigDB{group: group, key: key}) do
    full_key_update = [
      {:pleroma, :ecto_repos},
      {:quack, :meta},
      {:mime, :types},
      {:cors_plug, [:max_age, :methods, :expose, :headers]},
      {:auto_linker, :opts},
      {:swarm, :node_blacklist},
      {:logger, :backends}
    ]

    Enum.any?(full_key_update, fn
      {s_group, s_key} ->
        group == s_group and ((is_list(s_key) and key in s_key) or key == s_key)
Alexander Strizhakov's avatar
Alexander Strizhakov committed
167
168
169
    end)
  end

170
  @spec delete(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
171
  def delete(params) do
172
173
    search_opts = Map.delete(params, :subkeys)

Alexander Strizhakov's avatar
Alexander Strizhakov committed
174
    with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
175
         {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
176
177
178
179
         keys <- Enum.map(sub_keys, &string_to_elixir_types(&1)),
         {_, config, new_value} when new_value != [] <-
           {:partial_remove, config, Keyword.drop(config.value, keys)} do
      update(config, %{value: new_value})
180
    else
Alexander Strizhakov's avatar
Alexander Strizhakov committed
181
182
183
      {:partial_remove, config, []} ->
        Repo.delete(config)

184
      {config, nil} ->
Alexander Strizhakov's avatar
Alexander Strizhakov committed
185
        Repo.delete(config)
186

187
188
189
190
191
      nil ->
        err =
          dgettext("errors", "Config with params %{params} not found", params: inspect(params))

        {:error, err}
192
193
194
    end
  end

195
196
197
  @spec to_json_types(term()) :: map() | list() | boolean() | String.t()
  def to_json_types(entity) when is_list(entity) do
    Enum.map(entity, &to_json_types/1)
198
199
  end

200
  def to_json_types(%Regex{} = entity), do: inspect(entity)
201

202
203
  def to_json_types(entity) when is_map(entity) do
    Map.new(entity, fn {k, v} -> {to_json_types(k), to_json_types(v)} end)
204
  end
205

206
207
208
209
210
211
  def to_json_types({:args, args}) when is_list(args) do
    arguments =
      Enum.map(args, fn
        arg when is_tuple(arg) -> inspect(arg)
        arg -> to_json_types(arg)
      end)
212

213
    %{"tuple" => [":args", arguments]}
214
  end
215

216
217
  def to_json_types({:proxy_url, {type, :localhost, port}}) do
    %{"tuple" => [":proxy_url", %{"tuple" => [to_json_types(type), "localhost", port]}]}
218
219
  end

220
  def to_json_types({:proxy_url, {type, host, port}}) when is_tuple(host) do
221
222
223
224
225
226
227
228
    ip =
      host
      |> :inet_parse.ntoa()
      |> to_string()

    %{
      "tuple" => [
        ":proxy_url",
229
        %{"tuple" => [to_json_types(type), ip, port]}
230
231
232
233
      ]
    }
  end

234
  def to_json_types({:proxy_url, {type, host, port}}) do
235
236
237
    %{
      "tuple" => [
        ":proxy_url",
238
        %{"tuple" => [to_json_types(type), to_string(host), port]}
239
240
241
242
      ]
    }
  end

243
244
  def to_json_types({:partial_chain, entity}),
    do: %{"tuple" => [":partial_chain", inspect(entity)]}
Alexander Strizhakov's avatar
Alexander Strizhakov committed
245

246
  def to_json_types(entity) when is_tuple(entity) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
247
248
249
    value =
      entity
      |> Tuple.to_list()
250
      |> to_json_types()
Alexander Strizhakov's avatar
Alexander Strizhakov committed
251
252
253

    %{"tuple" => value}
  end
254

255
256
257
  def to_json_types(entity) when is_binary(entity), do: entity

  def to_json_types(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
258
259
    entity
  end
Alexander Strizhakov's avatar
Alexander Strizhakov committed
260

261
  def to_json_types(entity) when entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
262
    ":#{entity}"
263
264
  end

265
  def to_json_types(entity) when is_atom(entity), do: inspect(entity)
266

267
268
269
270
271
272
273
274
275
276
277
  @spec to_elixir_types(boolean() | String.t() | map() | list()) :: term()
  def to_elixir_types(%{"tuple" => [":args", args]}) when is_list(args) do
    arguments =
      Enum.map(args, fn arg ->
        if String.contains?(arg, ["{", "}"]) do
          {elem, []} = Code.eval_string(arg)
          elem
        else
          to_elixir_types(arg)
        end
      end)
278

279
    {:args, arguments}
280
281
  end

282
283
  def to_elixir_types(%{"tuple" => [":proxy_url", %{"tuple" => [type, host, port]}]}) do
    {:proxy_url, {string_to_elixir_types(type), parse_host(host), port}}
284
285
  end

286
  def to_elixir_types(%{"tuple" => [":partial_chain", entity]}) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
287
288
289
290
291
292
293
294
    {partial_chain, []} =
      entity
      |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
      |> Code.eval_string()

    {:partial_chain, partial_chain}
  end

295
296
  def to_elixir_types(%{"tuple" => entity}) do
    Enum.reduce(entity, {}, &Tuple.append(&2, to_elixir_types(&1)))
297
298
  end

299
300
  def to_elixir_types(entity) when is_map(entity) do
    Map.new(entity, fn {k, v} -> {to_elixir_types(k), to_elixir_types(v)} end)
301
302
  end

303
304
  def to_elixir_types(entity) when is_list(entity) do
    Enum.map(entity, &to_elixir_types/1)
305
306
  end

307
  def to_elixir_types(entity) when is_binary(entity) do
308
309
    entity
    |> String.trim()
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    |> string_to_elixir_types()
  end

  def to_elixir_types(entity), do: entity

  @spec string_to_elixir_types(String.t()) ::
          atom() | Regex.t() | module() | String.t() | no_return()
  def string_to_elixir_types("~r" <> _pattern = regex) do
    pattern =
      ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u

    delimiters = ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]

    with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
           Regex.named_captures(pattern, regex),
         {:ok, {leading, closing}} <- find_valid_delimiter(delimiters, pattern, regex_delimiter),
         {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
      result
    end
329
330
  end

331
332
333
  def string_to_elixir_types(":" <> atom), do: String.to_atom(atom)

  def string_to_elixir_types(value) do
Alexander Strizhakov's avatar
naming    
Alexander Strizhakov committed
334
    if module_name?(value) do
335
336
337
338
339
      String.to_existing_atom("Elixir." <> value)
    else
      value
    end
  end
340

341
342
343
344
345
346
347
348
349
350
351
352
353
354
  defp parse_host("localhost"), do: :localhost

  defp parse_host(host) do
    charlist = to_charlist(host)

    case :inet.parse_address(charlist) do
      {:error, :einval} ->
        charlist

      {:ok, ip} ->
        ip
    end
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
355
356
357
  defp find_valid_delimiter([], _string, _) do
    raise(ArgumentError, message: "valid delimiter for Regex expression not found")
  end
358

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
  defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
       when is_tuple(delimiter) do
    if String.contains?(pattern, closing) do
      find_valid_delimiter(others, pattern, regex_delimiter)
    else
      {:ok, {leading, closing}}
    end
  end

  defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
    if String.contains?(pattern, delimiter) do
      find_valid_delimiter(others, pattern, regex_delimiter)
    else
      {:ok, {delimiter, delimiter}}
    end
  end

Alexander Strizhakov's avatar
naming    
Alexander Strizhakov committed
376
377
  @spec module_name?(String.t()) :: boolean()
  def module_name?(string) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
378
    Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Quack|Ueberauth|Swoosh)\./, string) or
379
      string in ["Oban", "Ueberauth", "ExSyslogger"]
380
381
  end
end