vendredi 19 novembre 2021

Is mass assignment protection needed when properly using validation?

I've been using Laravel (5.4) and PHP both for the very first time in a legacy app I've been tasked to maintain, and over the past couple of months I have noticed a pain point, which is mass assignment.

I believe I have a well-enough grasp of what is is, but I am not sure if I am really utilizing it correctly. The official documentation illustrates the problem using a (good, but extreme) example of a user's role. I understand the significance of this and why I should guard such variables. However, I don't think I really have a solid understanding of determining what fields to guard or not (if at all), in general.

It seems that a lot of the nice features of Laravel don't seem to have mass-assignment in mind, which is the main source of my frustration. For example, if I had an endpoint that had some optional fields (i.e. you could just not specify them in the request), then doing a mymodel->update(request->all()) would only update the fields that you provided. If many of the fields were guarded, I would have to have many repeated isset() checks if I wanted to achieve the same behaviour, which seems unnecessary. I also know that request->all() shouldn't really be used like this, but I am just trying to illustrate a point.

It becomes more cumbersome when you consider that you're probably going to use robust validation alongside something like request->only([...]) to make sure your data is correct and filtered to only what you expect.

So ultimately what I am asking is:

In the presence of robust validation and input-shaping methods, is mass-assigning nearly anything still worth doing? In general it seems that I am jumping through so many more hoops for no reason, when it seems that my validation steps already took care of the problem. If it is still worth doing, what am I missing? Should mass-assignment protection only be delegated to super-important fields, like a user's role, and nothing else?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire