• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

processone / ejabberd / 873

18 Dec 2024 03:24PM UTC coverage: 32.87% (+0.2%) from 32.698%
873

push

github

jsautret
Merge branch 'master' of github.com:processone/ejabberd

25 of 154 new or added lines in 10 files covered. (16.23%)

1847 existing lines in 9 files now uncovered.

14620 of 44478 relevant lines covered (32.87%)

618.14 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

34.58
/src/mod_http_api.erl
1
%%%----------------------------------------------------------------------
2
%%% File    : mod_http_api.erl
3
%%% Author  : Christophe romain <christophe.romain@process-one.net>
4
%%% Purpose : Implements REST API for ejabberd using JSON data
5
%%% Created : 15 Sep 2014 by Christophe Romain <christophe.romain@process-one.net>
6
%%%
7
%%%
8
%%% ejabberd, Copyright (C) 2002-2024   ProcessOne
9
%%%
10
%%% This program is free software; you can redistribute it and/or
11
%%% modify it under the terms of the GNU General Public License as
12
%%% published by the Free Software Foundation; either version 2 of the
13
%%% License, or (at your option) any later version.
14
%%%
15
%%% This program is distributed in the hope that it will be useful,
16
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
17
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
%%% General Public License for more details.
19
%%%
20
%%% You should have received a copy of the GNU General Public License along
21
%%% with this program; if not, write to the Free Software Foundation, Inc.,
22
%%% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
%%%
24
%%%----------------------------------------------------------------------
25

26
-module(mod_http_api).
27

28
-author('cromain@process-one.net').
29

30
-behaviour(gen_mod).
31

32
-export([start/2, stop/1, reload/3, process/2, depends/2,
33
         format_arg/2,
34
         mod_opt_type/1, mod_options/1, mod_doc/0]).
35

36
-include_lib("xmpp/include/xmpp.hrl").
37
-include("logger.hrl").
38
-include("ejabberd_http.hrl").
39
-include("ejabberd_stacktrace.hrl").
40
-include("translate.hrl").
41

42
-define(DEFAULT_API_VERSION, 1000000).
43

44
-define(CT_PLAIN,
45
        {<<"Content-Type">>, <<"text/plain">>}).
46

47
-define(CT_XML,
48
        {<<"Content-Type">>, <<"text/xml; charset=utf-8">>}).
49

50
-define(CT_JSON,
51
        {<<"Content-Type">>, <<"application/json">>}).
52

53
-define(AC_ALLOW_ORIGIN,
54
        {<<"Access-Control-Allow-Origin">>, <<"*">>}).
55

56
-define(AC_ALLOW_METHODS,
57
        {<<"Access-Control-Allow-Methods">>,
58
         <<"GET, POST, OPTIONS">>}).
59

60
-define(AC_ALLOW_HEADERS,
61
        {<<"Access-Control-Allow-Headers">>,
62
         <<"Content-Type, Authorization, X-Admin">>}).
63

64
-define(AC_MAX_AGE,
65
        {<<"Access-Control-Max-Age">>, <<"86400">>}).
66

67
-define(OPTIONS_HEADER,
68
        [?CT_PLAIN, ?AC_ALLOW_ORIGIN, ?AC_ALLOW_METHODS,
69
         ?AC_ALLOW_HEADERS, ?AC_MAX_AGE]).
70

71
-define(HEADER(CType),
72
        [CType, ?AC_ALLOW_ORIGIN, ?AC_ALLOW_HEADERS]).
73

74
%% -------------------
75
%% Module control
76
%% -------------------
77

78
start(_Host, _Opts) ->
79
    ok.
×
80

81
stop(_Host) ->
82
    ok.
×
83

84
reload(_Host, _NewOpts, _OldOpts) ->
85
    ok.
×
86

87
depends(_Host, _Opts) ->
88
    [].
×
89

90
%% ----------
91
%% basic auth
92
%% ----------
93

94
extract_auth(#request{auth = HTTPAuth, ip = {IP, _}, opts = Opts}) ->
95
    Info = case HTTPAuth of
26✔
96
               {SJID, Pass} ->
97
                   try jid:decode(SJID) of
×
98
                       #jid{luser = User, lserver = Server} ->
99
                           case ejabberd_auth:check_password(User, <<"">>, Server, Pass) of
×
100
                               true ->
101
                                   #{usr => {User, Server, <<"">>}, caller_server => Server};
×
102
                               false ->
103
                                   {error, invalid_auth}
×
104
                           end
105
                   catch _:{bad_jid, _} ->
106
                       {error, invalid_auth}
×
107
                   end;
108
               {oauth, Token, _} ->
109
                   case ejabberd_oauth:check_token(Token) of
×
110
                       {ok, {U, S}, Scope} ->
111
                           #{usr => {U, S, <<"">>}, oauth_scope => Scope, caller_server => S};
×
112
                       {false, Reason} ->
113
                           {error, Reason}
×
114
                   end;
115
               invalid ->
116
                   {error, invalid_auth};
×
117
               _ ->
118
                   #{}
26✔
119
           end,
120
    case Info of
26✔
121
        Map when is_map(Map) ->
122
            Tag = proplists:get_value(tag, Opts, <<>>),
26✔
123
            Map#{caller_module => ?MODULE, ip => IP, tag => Tag};
26✔
124
        _ ->
125
            ?DEBUG("Invalid auth data: ~p", [Info]),
×
126
            Info
×
127
    end.
128

129
%% ------------------
130
%% command processing
131
%% ------------------
132

133
%process(Call, Request) ->
134
%    ?DEBUG("~p~n~p", [Call, Request]), ok;
135
process(_, #request{method = 'POST', data = <<>>}) ->
136
    ?DEBUG("Bad Request: no data", []),
×
137
    badrequest_response(<<"Missing POST data">>);
×
138
process([Call | _], #request{method = 'POST', data = Data, ip = IPPort} = Req) ->
139
    Version = get_api_version(Req),
26✔
140
    try
26✔
141
        Args = extract_args(Data),
26✔
142
        log(Call, Args, IPPort),
26✔
143
        perform_call(Call, Args, Req, Version)
26✔
144
    catch
145
        %% TODO We need to refactor to remove redundant error return formatting
146
        throw:{error, unknown_command} ->
147
            json_format({404, 44, <<"Command not found.">>});
×
148
        _:{error,{_,invalid_json}} = _Err ->
149
            ?DEBUG("Bad Request: ~p", [_Err]),
×
150
            badrequest_response(<<"Invalid JSON input">>);
×
151
        ?EX_RULE(_Class, _Error, Stack) ->
152
            StackTrace = ?EX_STACK(Stack),
×
153
            ?DEBUG("Bad Request: ~p ~p", [_Error, StackTrace]),
×
154
            badrequest_response()
×
155
    end;
156
process([Call | _], #request{method = 'GET', q = Data, ip = {IP, _}} = Req) ->
157
    Version = get_api_version(Req),
×
158
    try
×
159
        Args = case Data of
×
160
                   [{nokey, <<>>}] -> [];
×
161
                   _ -> Data
×
162
               end,
163
        log(Call, Args, IP),
×
164
        perform_call(Call, Args, Req, Version)
×
165
    catch
166
        %% TODO We need to refactor to remove redundant error return formatting
167
        throw:{error, unknown_command} ->
168
            json_format({404, 44, <<"Command not found.">>});
×
169
        ?EX_RULE(_, _Error, Stack) ->
170
            StackTrace = ?EX_STACK(Stack),
×
171
            ?DEBUG("Bad Request: ~p ~p", [_Error, StackTrace]),
×
172
            badrequest_response()
×
173
    end;
174
process([_Call], #request{method = 'OPTIONS', data = <<>>}) ->
175
    {200, ?OPTIONS_HEADER, []};
×
176
process(_, #request{method = 'OPTIONS'}) ->
177
    {400, ?OPTIONS_HEADER, []};
×
178
process(_Path, Request) ->
179
    ?DEBUG("Bad Request: no handler ~p", [Request]),
×
180
    json_error(400, 40, <<"Missing command name.">>).
×
181

182
perform_call(Command, Args, Req, Version) ->
183
    case catch binary_to_existing_atom(Command, utf8) of
26✔
184
        Call when is_atom(Call) ->
185
            case extract_auth(Req) of
26✔
186
                {error, expired} -> invalid_token_response();
×
187
                {error, not_found} -> invalid_token_response();
×
188
                {error, invalid_auth} -> unauthorized_response();
×
189
                Auth when is_map(Auth) ->
190
                    Result = handle(Call, Auth, Args, Version),
26✔
191
                    json_format(Result)
26✔
192
            end;
193
        _ ->
194
            json_error(404, 40, <<"Endpoint not found.">>)
×
195
    end.
196

197
%% Be tolerant to make API more easily usable from command-line pipe.
198
extract_args(<<"\n">>) -> [];
×
199
extract_args(Data) ->
200
    Maps = misc:json_decode(Data),
26✔
201
    maps:to_list(Maps).
26✔
202

203
% get API version N from last "vN" element in URL path
204
get_api_version(#request{path = Path, host = Host}) ->
205
    get_api_version(lists:reverse(Path), Host).
26✔
206

207
get_api_version([<<"v", String/binary>> | Tail], Host) ->
208
    case catch binary_to_integer(String) of
×
209
        N when is_integer(N) ->
UNCOV
210
            N;
×
211
        _ ->
NEW
212
            get_api_version(Tail, Host)
×
213
    end;
214
get_api_version([_Head | Tail], Host) ->
215
    get_api_version(Tail, Host);
52✔
216
get_api_version([], Host) ->
217
    try mod_http_api_opt:default_version(Host)
26✔
218
    catch error:{module_not_loaded, ?MODULE, Host} ->
219
        ?WARNING_MSG("Using module ~p for host ~s, but it isn't configured "
26✔
220
                     "in the configuration file", [?MODULE, Host]),
26✔
221
        ?DEFAULT_API_VERSION
26✔
222
    end.
223

224
%% ----------------
225
%% command handlers
226
%% ----------------
227

228
%% TODO Check accept types of request before decided format of reply.
229

230
% generic ejabberd command handler
231
handle(Call, Auth, Args, Version) when is_atom(Call), is_list(Args) ->
232
    Args2 = [{misc:binary_to_atom(Key), Value} || {Key, Value} <- Args],
26✔
233
    try handle2(Call, Auth, Args2, Version)
26✔
234
    catch throw:not_found ->
UNCOV
235
            {404, <<"not_found">>};
×
236
          throw:{not_found, Why} when is_atom(Why) ->
UNCOV
237
            {404, misc:atom_to_binary(Why)};
×
238
          throw:{not_found, Msg} ->
UNCOV
239
            {404, iolist_to_binary(Msg)};
×
240
          throw:not_allowed ->
241
            {401, <<"not_allowed">>};
×
242
          throw:{not_allowed, Why} when is_atom(Why) ->
243
            {401, misc:atom_to_binary(Why)};
×
244
          throw:{not_allowed, Msg} ->
245
            {401, iolist_to_binary(Msg)};
×
246
          throw:{error, account_unprivileged} ->
247
            {403, 31, <<"Command need to be run with admin privilege.">>};
×
248
          throw:{error, access_rules_unauthorized} ->
249
            {403, 32, <<"AccessRules: Account does not have the right to perform the operation.">>};
×
250
          throw:{invalid_parameter, Msg} ->
251
            {400, iolist_to_binary(Msg)};
×
252
          throw:{error, Why} when is_atom(Why) ->
253
            {400, misc:atom_to_binary(Why)};
×
254
          throw:{error, Msg} ->
255
            {400, iolist_to_binary(Msg)};
×
256
          throw:Error when is_atom(Error) ->
257
            {400, misc:atom_to_binary(Error)};
×
258
          throw:Msg when is_list(Msg); is_binary(Msg) ->
259
            {400, iolist_to_binary(Msg)};
×
260
          ?EX_RULE(Class, Error, Stack) ->
261
            StackTrace = ?EX_STACK(Stack),
×
UNCOV
262
            ?ERROR_MSG("REST API Error: "
×
263
                       "~ts(~p) -> ~p:~p ~p",
264
                       [Call, hide_sensitive_args(Args),
265
                        Class, Error, StackTrace]),
×
UNCOV
266
            {500, <<"internal_error">>}
×
267
    end.
268

269
handle2(Call, Auth, Args, Version) when is_atom(Call), is_list(Args) ->
270
    {ArgsF, ArgsR, _ResultF} = ejabberd_commands:get_command_format(Call, Auth, Version),
26✔
271
    ArgsFormatted = format_args(Call, rename_old_args(Args, ArgsR), ArgsF),
26✔
272
    case ejabberd_commands:execute_command2(Call, ArgsFormatted, Auth, Version) of
26✔
273
        {error, Error} ->
UNCOV
274
            throw(Error);
×
275
        Res ->
276
            format_command_result(Call, Auth, Res, Version)
26✔
277
    end.
278

279
rename_old_args(Args, []) ->
280
    Args;
26✔
281
rename_old_args(Args, [{OldName, NewName} | ArgsR]) ->
UNCOV
282
    Args2 = case lists:keytake(OldName, 1, Args) of
×
283
        {value, {OldName, Value}, ArgsTail} ->
UNCOV
284
            [{NewName, Value} | ArgsTail];
×
285
        false ->
UNCOV
286
            Args
×
287
    end,
288
    rename_old_args(Args2, ArgsR).
×
289

290
get_elem_delete(Call, A, L, F) ->
291
    case proplists:get_all_values(A, L) of
52✔
292
      [Value] -> {Value, proplists:delete(A, L)};
52✔
293
      [_, _ | _] ->
294
          ?INFO_MSG("Command ~ts call rejected, it has duplicate attribute ~w",
×
UNCOV
295
                    [Call, A]),
×
UNCOV
296
          throw({invalid_parameter,
×
297
                 io_lib:format("Request have duplicate argument: ~w", [A])});
298
      [] ->
UNCOV
299
          case F of
×
300
              {list, _} ->
301
                  {[], L};
×
302
              _ ->
UNCOV
303
                  ?INFO_MSG("Command ~ts call rejected, missing attribute ~w",
×
UNCOV
304
                            [Call, A]),
×
305
                  throw({invalid_parameter,
×
306
                         io_lib:format("Request have missing argument: ~w", [A])})
307
          end
308
    end.
309

310
format_args(Call, Args, ArgsFormat) ->
311
    {ArgsRemaining, R} = lists:foldl(fun ({ArgName,
26✔
312
                                           ArgFormat},
313
                                          {Args1, Res}) ->
314
                                             {ArgValue, Args2} =
52✔
315
                                                 get_elem_delete(Call, ArgName,
316
                                                                 Args1, ArgFormat),
317
                                             Formatted = format_arg(ArgValue,
52✔
318
                                                                    ArgFormat),
319
                                             {Args2, Res ++ [Formatted]}
52✔
320
                                     end,
321
                                     {Args, []}, ArgsFormat),
322
    case ArgsRemaining of
26✔
323
      [] -> R;
26✔
324
      L when is_list(L) ->
UNCOV
325
          ExtraArgs = [N || {N, _} <- L],
×
UNCOV
326
          ?INFO_MSG("Command ~ts call rejected, it has unknown arguments ~w",
×
UNCOV
327
              [Call, ExtraArgs]),
×
UNCOV
328
          throw({invalid_parameter,
×
329
                 io_lib:format("Request have unknown arguments: ~w", [ExtraArgs])})
330
    end.
331

332
format_arg({Elements},
333
           {list, {_ElementDefName, {tuple, [{_Tuple1N, Tuple1S}, {_Tuple2N, Tuple2S}]} = Tuple}})
334
    when is_list(Elements) andalso
335
         (Tuple1S == binary orelse Tuple1S == string) ->
UNCOV
336
    lists:map(fun({F1, F2}) ->
×
UNCOV
337
                      {format_arg(F1, Tuple1S), format_arg(F2, Tuple2S)};
×
338
                 ({Val}) when is_list(Val) ->
UNCOV
339
                      format_arg({Val}, Tuple)
×
340
              end, Elements);
341
format_arg(Map,
342
           {list, {_ElementDefName, {tuple, [{_Tuple1N, Tuple1S}, {_Tuple2N, Tuple2S}]}}})
343
    when is_map(Map) andalso
344
         (Tuple1S == binary orelse Tuple1S == string) ->
345
    maps:fold(
1✔
346
        fun(K, V, Acc) ->
347
            [{format_arg(K, Tuple1S), format_arg(V, Tuple2S)} | Acc]
3✔
348
        end, [], Map);
349
format_arg(Elements,
350
           {list, {_ElementDefName, {list, _} = ElementDefFormat}})
351
    when is_list(Elements) ->
UNCOV
352
    [{format_arg(Element, ElementDefFormat)}
×
UNCOV
353
     || Element <- Elements];
×
354

355
%% Covered by command_test_list and command_test_list_tuple
356
format_arg(Elements,
357
           {list, {_ElementDefName, ElementDefFormat}})
358
    when is_list(Elements) ->
359
    [format_arg(Element, ElementDefFormat)
4✔
360
     || Element <- Elements];
4✔
361

362
format_arg({[{Name, Value}]},
363
           {tuple, [{_Tuple1N, Tuple1S}, {_Tuple2N, Tuple2S}]})
364
  when Tuple1S == binary;
365
       Tuple1S == string ->
UNCOV
366
    {format_arg(Name, Tuple1S), format_arg(Value, Tuple2S)};
×
367

368
%% Covered by command_test_tuple and command_test_list_tuple
369
format_arg(Elements,
370
           {tuple, ElementsDef})
371
  when is_map(Elements) ->
372
    list_to_tuple([element(2, maps:find(atom_to_binary(Name, latin1), Elements))
8✔
373
                   || {Name, _Format} <- ElementsDef]);
8✔
374

375
format_arg({Elements},
376
           {tuple, ElementsDef})
377
    when is_list(Elements) ->
UNCOV
378
    F = lists:map(fun({TElName, TElDef}) ->
×
UNCOV
379
                          case lists:keyfind(atom_to_binary(TElName, latin1), 1, Elements) of
×
380
                              {_, Value} ->
UNCOV
381
                                  format_arg(Value, TElDef);
×
382
                              _ when TElDef == binary; TElDef == string ->
UNCOV
383
                                  <<"">>;
×
384
                              _ ->
385
                                  ?ERROR_MSG("Missing field ~p in tuple ~p", [TElName, Elements]),
×
UNCOV
386
                                  throw({invalid_parameter,
×
387
                                         io_lib:format("Missing field ~w in tuple ~w", [TElName, Elements])})
388
                          end
389
                  end, ElementsDef),
UNCOV
390
    list_to_tuple(F);
×
391

392
format_arg(Elements, {list, ElementsDef})
393
    when is_list(Elements) and is_atom(ElementsDef) ->
UNCOV
394
    [format_arg(Element, ElementsDef)
×
UNCOV
395
     || Element <- Elements];
×
396

397
format_arg(Arg, integer) when is_integer(Arg) -> Arg;
2✔
UNCOV
398
format_arg(Arg, binary) when is_list(Arg) -> process_unicode_codepoints(Arg);
×
399
format_arg(Arg, binary) when is_binary(Arg) -> Arg;
31✔
400
format_arg(Arg, string) when is_list(Arg) -> Arg;
13✔
401
format_arg(Arg, string) when is_binary(Arg) -> binary_to_list(Arg);
11✔
UNCOV
402
format_arg(undefined, binary) -> <<>>;
×
UNCOV
403
format_arg(undefined, string) -> "";
×
404
format_arg(Arg, Format) ->
UNCOV
405
    ?ERROR_MSG("Don't know how to format Arg ~p for format ~p", [Arg, Format]),
×
UNCOV
406
    throw({invalid_parameter,
×
407
           io_lib:format("Arg ~w is not in format ~w",
408
                         [Arg, Format])}).
409

410
process_unicode_codepoints(Str) ->
411
    iolist_to_binary(lists:map(fun(X) when X > 255 -> unicode:characters_to_binary([X]);
×
412
                                  (Y) -> Y
×
413
                               end, Str)).
414

415
%% ----------------
416
%% internal helpers
417
%% ----------------
418

419
format_command_result(Cmd, Auth, Result, Version) ->
420
    {_, _, ResultFormat} = ejabberd_commands:get_command_format(Cmd, Auth, Version),
26✔
421
    case {ResultFormat, Result} of
26✔
422
        {{_, rescode}, V} when V == true; V == ok ->
423
            {200, 0};
8✔
424
        {{_, rescode}, _} ->
425
            {200, 1};
2✔
426
        {_, {error, ErrorAtom, Code, Msg}} ->
UNCOV
427
            format_error_result(ErrorAtom, Code, Msg);
×
428
        {{_, restuple}, {V, Text}} when V == true; V == ok ->
429
            {200, iolist_to_binary(Text)};
3✔
430
        {{_, restuple}, {ErrorAtom, Msg}} ->
UNCOV
431
            format_error_result(ErrorAtom, 0, Msg);
×
432
        {{_, {list, _}}, _V} ->
433
            {_, L} = format_result(Result, ResultFormat),
5✔
434
            {200, L};
5✔
435
        {{_, {tuple, _}}, _V} ->
436
            {_, T} = format_result(Result, ResultFormat),
2✔
437
            {200, T};
2✔
438
        _ ->
439
            OtherResult1 = format_result(Result, ResultFormat),
6✔
440
            OtherResult2 = case Version of
6✔
441
                               0 ->
UNCOV
442
                                   {[OtherResult1]};
×
443
                               _ ->
444
                                   {_, Other3} = OtherResult1,
6✔
445
                                   Other3
6✔
446
                           end,
447
            {200, OtherResult2}
6✔
448
    end.
449

450
format_result(Atom, {Name, atom}) ->
451
    {misc:atom_to_binary(Name), misc:atom_to_binary(Atom)};
2✔
452

453
format_result(Int, {Name, integer}) ->
454
    {misc:atom_to_binary(Name), Int};
1✔
455

456
format_result([String | _] = StringList, {Name, string}) when is_list(String) ->
UNCOV
457
    Binarized = iolist_to_binary(string:join(StringList, "\n")),
×
UNCOV
458
    {misc:atom_to_binary(Name), Binarized};
×
459

460
format_result(String, {Name, string}) ->
461
    {misc:atom_to_binary(Name), iolist_to_binary(String)};
33✔
462

463
format_result(Code, {Name, rescode}) ->
464
    {misc:atom_to_binary(Name), Code == true orelse Code == ok};
×
465

466
format_result({Code, Text}, {Name, restuple}) ->
UNCOV
467
    {misc:atom_to_binary(Name),
×
UNCOV
468
     {[{<<"res">>, Code == true orelse Code == ok},
×
469
       {<<"text">>, iolist_to_binary(Text)}]}};
470

471
format_result(Code, {Name, restuple}) ->
UNCOV
472
    {misc:atom_to_binary(Name),
×
473
     {[{<<"res">>, Code == true orelse Code == ok},
×
474
       {<<"text">>, <<"">>}]}};
475

476
format_result(Els, {Name, {list, {_, {tuple, [{_, atom}, _]}} = Fmt}}) ->
UNCOV
477
    {misc:atom_to_binary(Name), {[format_result(El, Fmt) || El <- Els]}};
×
478

479
format_result(Els, {Name, {list, {_, {tuple, [{name, string}, {value, _}]}} = Fmt}}) ->
UNCOV
480
    {misc:atom_to_binary(Name), {[format_result(El, Fmt) || El <- Els]}};
×
481

482
%% Covered by command_test_list and command_test_list_tuple
483
format_result(Els, {Name, {list, Def}}) ->
484
    {misc:atom_to_binary(Name), [element(2, format_result(El, Def)) || El <- Els]};
5✔
485

486
format_result(Tuple, {_Name, {tuple, [{_, atom}, ValFmt]}}) ->
UNCOV
487
    {Name2, Val} = Tuple,
×
UNCOV
488
    {_, Val2} = format_result(Val, ValFmt),
×
UNCOV
489
    {misc:atom_to_binary(Name2), Val2};
×
490

491
format_result(Tuple, {_Name, {tuple, [{name, string}, {value, _} = ValFmt]}}) ->
UNCOV
492
    {Name2, Val} = Tuple,
×
493
    {_, Val2} = format_result(Val, ValFmt),
×
494
    {iolist_to_binary(Name2), Val2};
×
495

496
%% Covered by command_test_tuple and command_test_list_tuple
497
format_result(Tuple, {Name, {tuple, Def}}) ->
498
    Els = lists:zip(tuple_to_list(Tuple), Def),
11✔
499
    Els2 = [format_result(El, ElDef) || {El, ElDef} <- Els],
11✔
500
    {misc:atom_to_binary(Name), maps:from_list(Els2)};
11✔
501

502
format_result(404, {_Name, _}) ->
UNCOV
503
    "not_found".
×
504

505

506
format_error_result(conflict, Code, Msg) ->
UNCOV
507
    {409, Code, iolist_to_binary(Msg)};
×
508
format_error_result(not_exists, Code, Msg) ->
509
    {404, Code, iolist_to_binary(Msg)};
×
510
format_error_result(_ErrorAtom, Code, Msg) ->
UNCOV
511
    {500, Code, iolist_to_binary(Msg)}.
×
512

513
unauthorized_response() ->
UNCOV
514
    json_error(401, 10, <<"You are not authorized to call this command.">>).
×
515

516
invalid_token_response() ->
517
    json_error(401, 10, <<"Oauth Token is invalid or expired.">>).
×
518

519
%% outofscope_response() ->
520
%%     json_error(401, 11, <<"Token does not grant usage to command required scope.">>).
521

522
badrequest_response() ->
523
    badrequest_response(<<"400 Bad Request">>).
×
524
badrequest_response(Body) ->
UNCOV
525
    json_response(400, misc:json_encode(Body)).
×
526

527
json_format({Code, Result}) ->
528
    json_response(Code, misc:json_encode(Result));
26✔
529
json_format({HTMLCode, JSONErrorCode, Message}) ->
UNCOV
530
    json_error(HTMLCode, JSONErrorCode, Message).
×
531

532
json_response(Code, Body) when is_integer(Code) ->
533
    {Code, ?HEADER(?CT_JSON), Body}.
26✔
534

535
%% HTTPCode, JSONCode = integers
536
%% message is binary
537
json_error(HTTPCode, JSONCode, Message) ->
UNCOV
538
    {HTTPCode, ?HEADER(?CT_JSON),
×
539
     misc:json_encode(#{<<"status">> => <<"error">>,
540
                    <<"code">> =>  JSONCode,
541
                    <<"message">> => Message})
542
    }.
543

544
log(Call, Args, {Addr, Port}) ->
545
    AddrS = misc:ip_to_list({Addr, Port}),
26✔
546
    ?INFO_MSG("API call ~ts ~p from ~ts:~p", [Call, hide_sensitive_args(Args), AddrS, Port]);
26✔
547
log(Call, Args, IP) ->
UNCOV
548
    ?INFO_MSG("API call ~ts ~p (~p)", [Call, hide_sensitive_args(Args), IP]).
×
549

550
hide_sensitive_args(Args=[_H|_T]) ->
551
    lists:map(fun({<<"password">>, Password}) -> {<<"password">>, ejabberd_config:may_hide_data(Password)};
26✔
UNCOV
552
         ({<<"newpass">>,NewPassword}) -> {<<"newpass">>, ejabberd_config:may_hide_data(NewPassword)};
×
553
         (E) -> E end,
52✔
554
         Args);
555
hide_sensitive_args(NonListArgs) ->
UNCOV
556
    NonListArgs.
×
557

558
mod_opt_type(default_version) ->
NEW
559
    econf:either(
×
560
        econf:int(0, 3),
561
        econf:and_then(
562
            econf:binary(),
563
            fun(Binary) ->
NEW
564
               case binary_to_list(Binary) of
×
565
                   F when F >= "24.06" ->
NEW
566
                       2;
×
567
                   F when (F > "23.10") and (F < "24.06") ->
NEW
568
                       1;
×
569
                   F when F =< "23.10" ->
NEW
570
                       0
×
571
               end
572
            end)).
573

574
mod_options(_) ->
NEW
575
    [{default_version, ?DEFAULT_API_VERSION}].
×
576

577
mod_doc() ->
578
    #{desc =>
×
579
          [?T("This module provides a ReST interface to call "
580
              "_`../../developer/ejabberd-api/index.md|ejabberd API`_ "
581
              "commands using JSON data."), "",
582
           ?T("To use this module, in addition to adding it to the 'modules' "
583
              "section, you must also enable it in 'listen' -> 'ejabberd_http' -> "
584
              "_`listen-options.md#request_handlers|request_handlers`_."), "",
585
           ?T("To use a specific API version N, when defining the URL path "
586
              "in the request_handlers, add a vN. "
587
              "For example: '/api/v2: mod_http_api'."), "",
588
           ?T("To run a command, send a POST request to the corresponding "
589
              "URL: 'http://localhost:5280/api/COMMAND-NAME'")],
590
     opts =>
591
          [{default_version,
592
            #{value => "integer() | string()",
593
              desc =>
594
                  ?T("What API version to use when none is specified in the URL path. "
595
                     "If setting an ejabberd version, it will use the latest API "
596
                     "version that was available in that ejabberd version. "
597
                     "For example, setting '\"24.06\"' in this option implies '2'. "
598
                     "The default value is the latest version.")}}],
599
     example =>
600
         ["listen:",
601
          "  -",
602
          "    port: 5280",
603
          "    module: ejabberd_http",
604
          "    request_handlers:",
605
          "      /api: mod_http_api",
606
          "",
607
          "modules:",
608
          "  mod_http_api:",
609
          "    default_version: 2"]}.
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc