From 4f31109bd9fd4a2f95e9c78657ff68fa4cf1d4e3 Mon Sep 17 00:00:00 2001 From: Zach Daniel Date: Sat, 7 Sep 2024 07:50:47 -0400 Subject: [PATCH] fix: support passing a forbidden error to policies per the docs fixes #1443 --- lib/ash/error/forbidden/policy.ex | 6 ++++++ test/policy/simple_test.exs | 13 +++++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/ash/error/forbidden/policy.ex b/lib/ash/error/forbidden/policy.ex index 63d4e9c7..81397f8c 100644 --- a/lib/ash/error/forbidden/policy.ex +++ b/lib/ash/error/forbidden/policy.ex @@ -70,6 +70,12 @@ defmodule Ash.Error.Forbidden.Policy do - `:help_text?`: Defaults to true. Displays help text at the top of the policy breakdown. """ + def report(%Ash.Error.Forbidden{errors: errors}) do + errors + |> Enum.filter(&(&1.__struct__ == __MODULE__)) + |> Enum.map_join("\n\n", &report/1) + end + def report(error, opts \\ []) do error |> get_errors() diff --git a/test/policy/simple_test.exs b/test/policy/simple_test.exs index aa072c58..734f038c 100644 --- a/test/policy/simple_test.exs +++ b/test/policy/simple_test.exs @@ -190,6 +190,19 @@ defmodule Ash.Test.Policy.SimpleTest do end end + test "breakdowns can be shown for all policy errors in a forbidden error" do + res = + assert_raise Ash.Error.Forbidden, + ~r/No policy conditions applied to this request/, + fn -> + ResourceWithAPolicyThatDoesntApply + |> Ash.read!() + end + + assert Ash.Error.Forbidden.Policy.report(res) =~ + ~r/No policy conditions applied to this request/ + end + test "an impossible create policy shows the correct error message" do assert_raise Ash.Error.Forbidden, ~r/Cannot use a filter to authorize a create/, fn -> ResourceWithAnImpossibleCreatePolicy