test: replicate forbidden error on update (#1276)

This commit is contained in:
Robert Timis 2024-07-03 16:54:12 +02:00 committed by GitHub
parent 0e5587552c
commit a06bf364ac
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 49 additions and 3 deletions

View file

@ -203,11 +203,27 @@ defmodule Ash.Test.Policy.SimpleTest do
test "checking context using expr works" do
%{id: id} =
context =
Context
|> Ash.Changeset.for_create(:create, %{name: "Foo"})
|> Ash.create!()
assert [%{id: ^id}] = Ash.read!(Context, context: %{name: "Foo"}, authorize?: true)
assert %{name: "Bar"} =
context
|> Ash.Changeset.for_update(:update, %{name: "Bar"},
context: %{name: "Foo"},
authorize?: true
)
|> Ash.update!()
assert {:ok, %{name: "Foo"}} =
Domain.update_context(id, "Foo",
context: %{name: "Bar"},
actor: nil,
authorize?: true
)
end
test "a final always policy with a forbid if always is properly applied" do

View file

@ -11,7 +11,11 @@ defmodule Ash.Test.Support.PolicySimple.Domain do
resource(Ash.Test.Support.PolicySimple.Trip)
resource(Ash.Test.Support.PolicySimple.Tweet)
resource(Ash.Test.Support.PolicySimple.Foo)
resource(Ash.Test.Support.PolicySimple.Context)
resource(Ash.Test.Support.PolicySimple.Context) do
define :update_context, action: :update, args: [:name]
end
resource(Ash.Test.Support.PolicySimple.Always)
resource(Ash.Test.Support.PolicySimple.TwoFilters)
end

View file

@ -7,13 +7,16 @@ defmodule Ash.Test.Support.PolicySimple.Context do
Ash.Policy.Authorizer
]
alias Ash.Test.Support.PolicySimple.Context.Changes.DoChange
policies do
policy action_type(:create) do
authorize_if always()
end
policy action_type(:read) do
policy action_type([:read, :update]) do
authorize_if(expr(^context(:name) == name))
authorize_if relates_to_actor_via(:user)
end
end
@ -21,6 +24,10 @@ defmodule Ash.Test.Support.PolicySimple.Context do
private?(true)
end
relationships do
belongs_to(:user, Ash.Test.Support.PolicySimple.User, public?: true)
end
attributes do
uuid_primary_key(:id)
attribute(:name, :string, public?: true)
@ -28,6 +35,12 @@ defmodule Ash.Test.Support.PolicySimple.Context do
actions do
default_accept :*
defaults [:read, :destroy, create: :*, update: :*]
defaults [:read, :destroy, create: :*]
update :update do
require_atomic? false
argument :name, :string
change DoChange
end
end
end

View file

@ -0,0 +1,13 @@
defmodule Ash.Test.Support.PolicySimple.Context.Changes.DoChange do
@moduledoc false
use Ash.Resource.Change
@impl true
def change(changeset, _opts, _context) do
Ash.Changeset.before_action(changeset, fn changeset ->
name = Ash.Changeset.get_argument(changeset, :name)
Ash.Changeset.force_change_attribute(changeset, :name, name)
end)
end
end