route defined with negative lookaround matches the route despite the negative assertion

178 Views Asked by At

We want to open a DELETE endpoint that allows calls to all positive integers, but not id 1 (aka element 1 cannot be deleted)

Usually to open an endpoint that allows positive integers I configure the route like this

delete_elements:
 path: /elements/{id}
 methods: ["DELETE"]
 controller: app.elements_delete
 requirements:
  id: '\d+'

For this case I tried to change the regex to one that does not allow number 1 either

delete_elements:
 path: /elements/{id}
 methods: ["DELETE"]
 controller: app.elements_delete
 requirements:
  id: /^(?!(?:1)$)\d+/

But when I modify the requirement and I call the endpoint the response is that the endpoint does not exist.

"No route found for "DELETE /elements/59": Method Not Allowed (Allow: GET, PUT)"

What is wrong with that regex? What would be the right way to forbid certain values?

1

There are 1 best solutions below

0
On BEST ANSWER

Try with:

    id: '^(?!1/?$)\d+'

The problem is that routes are redirected to URLs ending in / in Symfony. So your original negative lookahead does not work because it's looking for 1 followed by "end of string" ($).

By adding /? to the regex you say that the negative lookahead can either be 1$ or 1/$

Although this would work, again my advise is to handle this at application level, and return a 403 when someone tries to delete something they are not allowed to delete, and not return a 404 which means something different.