From c74bd515daf92fc608b88cfb11ebd0da262e2213 Mon Sep 17 00:00:00 2001 From: zmstone Date: Thu, 17 Sep 2026 12:30:35 +0200 Subject: [PATCH 1/2] feat(handler): let a failed authorization add log meta An authorization callback can now return `{with_log_meta, LogMeta, Response}`. minirest merges `LogMeta` into the log meta in the same way as the meta of a successful authorization, and sends only `Response` to the client. `update_log_meta/1` now does nothing and returns `ok` when the calling process does not handle a minirest request. --- README.md | 24 ++++++++++++++++++++++ src/minirest_handler.erl | 26 +++++++++++++++++++++--- test/minirest_handler_SUITE.erl | 35 ++++++++++++++++++++++++++++++++- test/minirest_test_handler.erl | 4 ++++ 4 files changed, 85 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 938ba76..0cbac9d 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,30 @@ login(post, _Params) -> {200, #{<<"set-cookie">> => Cookie}, #{}}. ``` +## Add log meta to a failed authorization + +An `authorization` callback returns `{ok, AuthMeta}` to accept a request. +minirest merges `AuthMeta` into the log meta that the `log` hook receives. + +To reject a request and still add log meta, return +`{with_log_meta, LogMeta, Response}`. minirest merges `LogMeta` into the log +meta in the same way, and sends only `Response` to the client. Use it to +record an authenticated caller that is not allowed to use the endpoint. + +```erlang +authorize(Req, HandlerInfo) -> + case check(Req, HandlerInfo) of + {ok, User} -> + {ok, #{source => User}}; + {forbidden, User} -> + {with_log_meta, #{source => User}, + {403, 'FORBIDDEN', <<"Not allowed">>}} + end. +``` + +A handler can also call `minirest_handler:update_log_meta/1` to add log meta. +The call does nothing in a process that does not handle a minirest request. + ## Start your HTTP server ```erlang diff --git a/src/minirest_handler.erl b/src/minirest_handler.erl index 5072f7d..8430c3f 100644 --- a/src/minirest_handler.erl +++ b/src/minirest_handler.erl @@ -40,9 +40,17 @@ init(Request0, State) -> %% or it may be an interactive endpoint whose metadata cannot be determined in one step. %% Here, the metadata is moved from the function return to the process dictionary, %% so that the metadata in the endpoint can be updated. +%% +%% The call does nothing when the calling process does not handle a minirest +%% request, for example when a test calls an authorize callback directly. update_log_meta(New) -> - Meta = get_log_meta(), - erlang:put(?META_KEY, maps:merge(Meta, New)). + case get_log_meta() of + undefined -> + ok; + Meta -> + erlang:put(?META_KEY, maps:merge(Meta, New)), + ok + end. %%%============================================================================================== %% internal @@ -88,13 +96,25 @@ handle(Request, #{path := Path, methods := Methods} = State) -> {StatusCode, NRequest1} = reply(ParseErr, Request, Handler), {StatusCode, NRequest1} end; - AuthFailed -> + AuthFailed0 -> + AuthFailed = take_auth_log_meta(AuthFailed0), prepend_log_meta(#{failure => failed_log_meta(AuthFailed)}), {StatusCode, NRequest1} = reply(AuthFailed, Request, Handler), {StatusCode, NRequest1} end end. +%% An authorize callback returns `{with_log_meta, LogMeta, Response}' to add +%% log meta to a failed authorization, for example the authenticated caller +%% that is not allowed to use the endpoint. `LogMeta' is merged into the log +%% meta the same way as the meta of a successful authorization. Only +%% `Response' is sent to the client. +take_auth_log_meta({with_log_meta, LogMeta, Response}) when is_map(LogMeta) -> + ok = update_log_meta(LogMeta), + Response; +take_auth_log_meta(Response) -> + Response. + failed_log_meta({Code, #{} = Meta}) when is_integer(Code) -> Meta; failed_log_meta({Code, _Response}) when is_integer(Code) -> #{}; failed_log_meta({Code, _Header, #{} = Meta}) when is_integer(Code) -> Meta; diff --git a/test/minirest_handler_SUITE.erl b/test/minirest_handler_SUITE.erl index ef46d10..3cf827e 100644 --- a/test/minirest_handler_SUITE.erl +++ b/test/minirest_handler_SUITE.erl @@ -35,7 +35,9 @@ all() -> t_route_path_in_auth, t_post_large_body, t_set_cookie, - t_set_cookies + t_set_cookies, + t_auth_failure_log_meta, + t_update_log_meta_outside_request ]. init_per_suite(Config) -> @@ -56,6 +58,15 @@ init_per_testcase(t_route_path_in_auth, Config) -> #{authorization => {?HANDLER_MODULE, authorize_path}} ), Config; +init_per_testcase(t_auth_failure_log_meta, Config) -> + Self = self(), + ok = start_minirest( + #{ + authorization => {?HANDLER_MODULE, authorize_deny}, + log => fun(Meta, _Req) -> Self ! {log_meta, Meta} end + } + ), + Config; init_per_testcase(_Case, Config) -> ok = start_minirest(), Config. @@ -157,6 +168,28 @@ t_set_cookies(_Config) -> lists:sort([cookie_pair(C) || C <- set_cookie_headers(Headers)]) ). +%% An authorize callback that returns `{with_log_meta, LogMeta, Response}' adds +%% `LogMeta' to the log meta. The client gets only `Response'. +t_auth_failure_log_meta(_Config) -> + {ok, {{_Version, 403, _Status}, _Headers, Body}} = + httpc:request(address() ++ "/auth_meta_in_handler"), + ?assertEqual( + #{<<"code">> => <<"FORBIDDEN">>, <<"message">> => <<"not allowed">>}, + jsx:decode(iolist_to_binary(Body), [return_maps]) + ), + receive + {log_meta, Meta} -> + ?assertMatch(#{source := <<"denied-user">>, code := 403, failure := _}, Meta) + after 5000 -> + ct:fail(log_hook_not_called) + end. + +%% `update_log_meta/1' does nothing in a process that does not handle a +%% minirest request. +t_update_log_meta_outside_request(_Config) -> + ?assertEqual(ok, minirest_handler:update_log_meta(#{source => <<"nobody">>})), + ?assertEqual(undefined, erlang:get({minirest_handler, meta})). + %%-------------------------------------------------------------------- %% Helpers %%-------------------------------------------------------------------- diff --git a/test/minirest_test_handler.erl b/test/minirest_test_handler.erl index 41693d5..cba9a90 100644 --- a/test/minirest_test_handler.erl +++ b/test/minirest_test_handler.erl @@ -23,6 +23,7 @@ authorize1/1, authorize2/2, authorize_path/2, + authorize_deny/2, lazy_body/2, binary_body/2, flex_error/2, @@ -187,6 +188,9 @@ authorize2(_Req, #{module := Module, function := Fun}) -> authorize_path(_Req, #{path := Path}) -> {ok, #{route_path => list_to_binary(Path)}}. +authorize_deny(_Req, _HandlerInfo) -> + {with_log_meta, #{source => <<"denied-user">>}, {403, 'FORBIDDEN', <<"not allowed">>}}. + lazy_body(get, _) -> BodyQH = qlc:table(fun() -> [<<"first">>, <<"second">>] end, []), {200, #{<<"content-type">> => <<"test/plain">>}, BodyQH}. From 5be13363f2a79e988de0abc5d80bcfb262ac04e3 Mon Sep 17 00:00:00 2001 From: zmstone Date: Thu, 17 Sep 2026 14:03:51 +0200 Subject: [PATCH 2/2] refactor(handler): drop the with_log_meta authorization result `update_log_meta/1` is already the way emqx adds log meta, and it now works outside a request. Keep only that change. --- README.md | 27 +++++---------------------- src/minirest_handler.erl | 14 +------------- test/minirest_handler_SUITE.erl | 26 -------------------------- test/minirest_test_handler.erl | 4 ---- 4 files changed, 6 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index 0cbac9d..06c35e4 100644 --- a/README.md +++ b/README.md @@ -116,29 +116,12 @@ login(post, _Params) -> {200, #{<<"set-cookie">> => Cookie}, #{}}. ``` -## Add log meta to a failed authorization +## Add log meta -An `authorization` callback returns `{ok, AuthMeta}` to accept a request. -minirest merges `AuthMeta` into the log meta that the `log` hook receives. - -To reject a request and still add log meta, return -`{with_log_meta, LogMeta, Response}`. minirest merges `LogMeta` into the log -meta in the same way, and sends only `Response` to the client. Use it to -record an authenticated caller that is not allowed to use the endpoint. - -```erlang -authorize(Req, HandlerInfo) -> - case check(Req, HandlerInfo) of - {ok, User} -> - {ok, #{source => User}}; - {forbidden, User} -> - {with_log_meta, #{source => User}, - {403, 'FORBIDDEN', <<"Not allowed">>}} - end. -``` - -A handler can also call `minirest_handler:update_log_meta/1` to add log meta. -The call does nothing in a process that does not handle a minirest request. +Call `minirest_handler:update_log_meta/1` from a handler or an +`authorization` callback to add meta for the `log` hook. The call does +nothing in a process that does not handle a minirest request, for example +when a test calls the callback directly. ## Start your HTTP server diff --git a/src/minirest_handler.erl b/src/minirest_handler.erl index 8430c3f..384aff4 100644 --- a/src/minirest_handler.erl +++ b/src/minirest_handler.erl @@ -96,25 +96,13 @@ handle(Request, #{path := Path, methods := Methods} = State) -> {StatusCode, NRequest1} = reply(ParseErr, Request, Handler), {StatusCode, NRequest1} end; - AuthFailed0 -> - AuthFailed = take_auth_log_meta(AuthFailed0), + AuthFailed -> prepend_log_meta(#{failure => failed_log_meta(AuthFailed)}), {StatusCode, NRequest1} = reply(AuthFailed, Request, Handler), {StatusCode, NRequest1} end end. -%% An authorize callback returns `{with_log_meta, LogMeta, Response}' to add -%% log meta to a failed authorization, for example the authenticated caller -%% that is not allowed to use the endpoint. `LogMeta' is merged into the log -%% meta the same way as the meta of a successful authorization. Only -%% `Response' is sent to the client. -take_auth_log_meta({with_log_meta, LogMeta, Response}) when is_map(LogMeta) -> - ok = update_log_meta(LogMeta), - Response; -take_auth_log_meta(Response) -> - Response. - failed_log_meta({Code, #{} = Meta}) when is_integer(Code) -> Meta; failed_log_meta({Code, _Response}) when is_integer(Code) -> #{}; failed_log_meta({Code, _Header, #{} = Meta}) when is_integer(Code) -> Meta; diff --git a/test/minirest_handler_SUITE.erl b/test/minirest_handler_SUITE.erl index 3cf827e..bea29a3 100644 --- a/test/minirest_handler_SUITE.erl +++ b/test/minirest_handler_SUITE.erl @@ -36,7 +36,6 @@ all() -> t_post_large_body, t_set_cookie, t_set_cookies, - t_auth_failure_log_meta, t_update_log_meta_outside_request ]. @@ -58,15 +57,6 @@ init_per_testcase(t_route_path_in_auth, Config) -> #{authorization => {?HANDLER_MODULE, authorize_path}} ), Config; -init_per_testcase(t_auth_failure_log_meta, Config) -> - Self = self(), - ok = start_minirest( - #{ - authorization => {?HANDLER_MODULE, authorize_deny}, - log => fun(Meta, _Req) -> Self ! {log_meta, Meta} end - } - ), - Config; init_per_testcase(_Case, Config) -> ok = start_minirest(), Config. @@ -168,22 +158,6 @@ t_set_cookies(_Config) -> lists:sort([cookie_pair(C) || C <- set_cookie_headers(Headers)]) ). -%% An authorize callback that returns `{with_log_meta, LogMeta, Response}' adds -%% `LogMeta' to the log meta. The client gets only `Response'. -t_auth_failure_log_meta(_Config) -> - {ok, {{_Version, 403, _Status}, _Headers, Body}} = - httpc:request(address() ++ "/auth_meta_in_handler"), - ?assertEqual( - #{<<"code">> => <<"FORBIDDEN">>, <<"message">> => <<"not allowed">>}, - jsx:decode(iolist_to_binary(Body), [return_maps]) - ), - receive - {log_meta, Meta} -> - ?assertMatch(#{source := <<"denied-user">>, code := 403, failure := _}, Meta) - after 5000 -> - ct:fail(log_hook_not_called) - end. - %% `update_log_meta/1' does nothing in a process that does not handle a %% minirest request. t_update_log_meta_outside_request(_Config) -> diff --git a/test/minirest_test_handler.erl b/test/minirest_test_handler.erl index cba9a90..41693d5 100644 --- a/test/minirest_test_handler.erl +++ b/test/minirest_test_handler.erl @@ -23,7 +23,6 @@ authorize1/1, authorize2/2, authorize_path/2, - authorize_deny/2, lazy_body/2, binary_body/2, flex_error/2, @@ -188,9 +187,6 @@ authorize2(_Req, #{module := Module, function := Fun}) -> authorize_path(_Req, #{path := Path}) -> {ok, #{route_path => list_to_binary(Path)}}. -authorize_deny(_Req, _HandlerInfo) -> - {with_log_meta, #{source => <<"denied-user">>}, {403, 'FORBIDDEN', <<"not allowed">>}}. - lazy_body(get, _) -> BodyQH = qlc:table(fun() -> [<<"first">>, <<"second">>] end, []), {200, #{<<"content-type">> => <<"test/plain">>}, BodyQH}.