cerebris / jsonapi-resources

A resource-focused Rails library for developing JSON:API compliant servers.
http://jsonapi-resources.com
MIT License
2.32k stars 532 forks source link

Polymorphic has_many relationships linkage data skips authorization checks added to records_for #685

Open benarmston opened 8 years ago

benarmston commented 8 years ago

I'm using a simple method of authorization which is being broken by link objects for polymorphic has many relationships.

I have a ResourceBase class derived from JSONAPI::Resource, which overrides records and records_for to only return authorized records. This was working fine until I added a polymorphic has many relationship to one of my resources. At which point a number of unauthorized link objects were appearing for the resource's polymorphic relationship.

The reason for this being that JSONAPI::ResourceSerializer#foreign_key_types_and_values makes a call directly to the resources underlying model for polymorphic relationships. This call skips the records_for call in which I have been performing my authorization.

foreign_key_types_and_values is the only place in which ResourceSerializer accesses the resource's underlying model leading me to believe that there should be a method on the JSONAPI::Resource which ResourceSerializer should be calling in this case.

A possible solution would be to:

  1. Change foreign_key_types_and_values to call a method on Resource to retrieve the foreign keys and types, for both polymorphic and non-polymorphic relationships.
  2. Change Resource::_add_relationship to create a new method on the resource for each polymorphic has many relationship. This method would return both the type and id of the related models making sure to do so by calling records_for.

I'll see if I can put together a PR for this, but thought I'd mention the bug and my suggested fix first.

benarmston commented 8 years ago

See also #683 for an issue with foreign_key_types_and_values that should be taken into account when fixing this and the PR for that issue #684.

lgebhardt commented 8 years ago

@benarmston Thanks for pointing this out. It's potentially a pretty bad bug. Have you started the PR yet?