api-platform / core

The server component of API Platform: hypermedia and GraphQL APIs in minutes
https://api-platform.com
MIT License
2.43k stars 866 forks source link

Error 401 instead of 404 when doing a POST on a non-existent resource with a custom UriTemplate #6014

Open Dean151 opened 10 months ago

Dean151 commented 10 months ago

API Platform version(s) affected: 3.1.11+

Description

I have an endpoint like this one: POST /feeders/{id}/feed that triggers an action on a resource called feeder. This endpoint have a security setting, and a custom uriTemplate on the resource.

new Post(
    uriTemplate: '/feeders/{id}/feed',
    ...
    security: 'is_granted(\'MANAGE\', object)',
),

When sending an ID that does not exist, I expect a 404 error, and one of my tests assert that. But since version 3.1.11, I get a 401 error instead.

I can narrow down the apparition of the issue with https://github.com/api-platform/core/pull/5583, that exclude POST method from Not Found early response in ApiPlatform/Symfony/EventListener/ReadListener.php

How to reproduce

Possible Solution
Simply removing the line 106 of ApiPlatform/Symfony/EventListener/ReadListener.php fixes the problem; but it might have other implications…

Additional Context

I can reproduce this here, see the failing CI: https://github.com/Dean151/Aln-Symfony/pull/71 My Post declaration is here: https://github.com/Dean151/Aln-Symfony/blob/470033da34e5f93bacb23b03d1bad7434f994588/src/Entity/AlnFeeder.php#L112

soyuka commented 10 months ago

indeed this is a hard problem as since API Platform 2 POST is not supposed to have identifiers. Maybe that we can try to provide a flag to allow an operation to throw a not found exception when the data is null. I've added a pr with a proposal to change this behavior.

Dean151 commented 10 months ago

As discussed at SymfonyCon, I implemented the workaround of using a Provider that throws an NotFoundHttpException itself. I post it here so that any other folk impacted by this can have a reference on this. https://github.com/Dean151/Aln-Symfony/blob/be1e7b3720dc8a29521c5ad632d59ed787aa4f98/src/ApiPlatform/Provider/AlnFeederProvider.php