DRY when validating calculations made client side (Javascript) on the server (PHP) - javascript

I'm looking to DRY when I am validating a calculation made by the client (javascript) back on the server (PHP). I'm validating on the server to prevent a malicious user from duping the javascript, but I am calculating on the client to avoid the delay and server strain in AJAXing back to the server for the validation.
My question: is there any way to do this DRY, or do I have to write the code out in both languages? If it has to be written out, is it better to AJAX back to the server for DRY purposes, or should I write out the same validation code in both languages?
This question is exactly what I am looking for an answer to, but it was never satisfactorily answered.
EDIT (1/25/15): Although the accepted answer stands, particularly because my original question specified that the server was running on PHP, I think its worth pointing out that server side validation could be done using Node.js, which allows javascript code to run on the backend server. I have subsequently moved to this approach, and it does allow for reuse of code on both the client and the server, which would allow the kind of write once validation described above. In retrospect #slebetman's comment below identified the best approach for me.

Client-side validation is all about saving the user time. By not having to send bad data to the server and then having the request rejected, we can save loading time.
Server-side validation is about security. We need to make sure that the data we get on the server is valid and not going to cause us any problems.
So in my opinion, it's best to write the code twice and not to use AJAX requests to validate data unless you have to

Related

How to prevent form hacking in client-side code

This is a general question more than a specific problem I have with code. The question came up discussing the pros & cons of using frameworks such as VueJS and performing say form validation on the client vs. submitting the data to the server where a controller does the data validation.
His argument was that since the code (i.e JS code) and the data reside on the client there is always the possibility of someone tampering with the data/code then submitting the data to the server therefor bypassing validation. I'm new to VueJS coming to it from PHP + CodeIgniter and would like to hear your thoughts on the subject.
How valid is this argument?
thank you,
Yes, a malicious user can tamper with client-side code and remove all the security and validation checks. Trying to stop them is a waste of time and effort. Instead, move all such checks out of the client-side code and into your server-side code.
How Valid? Very Valid.
Client side validation are extremely easy to bypass. Which is why you need to check the inputs even at the server side.
That being said client side validation are still useful for a number of reasons. For instance if your password has to be alphanumeric you want to check that at the client side first. Its not fun having bottlenecks in your server just because your password requirement is too hard to reach. In essence without your client side validation, every time somebody enters a less than strong password it goes to your server then comes back which is a delay and unnecessary network traffic.
That being said you should still validate if they are alphanumeric at the server side.

Ruby on Rails: Is it better to apply validations on model or through JavaScript? [duplicate]

Which is better to do client side or server side validation?
In our situation we are using
jQuery and MVC.
JSON data to pass between our View and Controller.
A lot of the validation I do is validating data as users enter it.
For example I use the the keypress event to prevent letters in a text box, set a max number of characters and that a number is with in a range.
I guess the better question would be, Are there any benefits to doing server side validation over client side?
Awesome answers everyone. The website that we have is password protected and for a small user base(<50). If they are not running JavaScript we will send ninjas. But if we were designing a site for everyone one I'd agree to do validation on both sides.
As others have said, you should do both. Here's why:
Client Side
You want to validate input on the client side first because you can give better feedback to the average user. For example, if they enter an invalid email address and move to the next field, you can show an error message immediately. That way the user can correct every field before they submit the form.
If you only validate on the server, they have to submit the form, get an error message, and try to hunt down the problem.
(This pain can be eased by having the server re-render the form with the user's original input filled in, but client-side validation is still faster.)
Server Side
You want to validate on the server side because you can protect against the malicious user, who can easily bypass your JavaScript and submit dangerous input to the server.
It is very dangerous to trust your UI. Not only can they abuse your UI, but they may not be using your UI at all, or even a browser. What if the user manually edits the URL, or runs their own Javascript, or tweaks their HTTP requests with another tool? What if they send custom HTTP requests from curl or from a script, for example?
(This is not theoretical; eg, I worked on a travel search engine that re-submitted the user's search to many partner airlines, bus companies, etc, by sending POST requests as if the user had filled each company's search form, then gathered and sorted all the results. Those companies' form JS was never executed, and it was crucial for us that they provide error messages in the returned HTML. Of course, an API would have been nice, but this was what we had to do.)
Not allowing for that is not only naive from a security standpoint, but also non-standard: a client should be allowed to send HTTP by whatever means they wish, and you should respond correctly. That includes validation.
Server side validation is also important for compatibility - not all users, even if they're using a browser, will have JavaScript enabled.
Addendum - December 2016
There are some validations that can't even be properly done in server-side application code, and are utterly impossible in client-side code, because they depend on the current state of the database. For example, "nobody else has registered that username", or "the blog post you're commenting on still exists", or "no existing reservation overlaps the dates you requested", or "your account balance still has enough to cover that purchase." Only the database can reliably validate data which depends on related data. Developers regularly screw this up, but PostgreSQL provides some good solutions.
Yes, client side validation can be totally bypassed, always. You need to do both, client side to provide a better user experience, and server side to be sure that the input you get is actually validated and not just supposedly validated by the client.
I am just going to repeat it, because it is quite important:
Always validate on the server
and add JavaScript for user-responsiveness.
The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:
The end user could have javascript switched off
The data could be sent directly to your server by someone who's not even using your site, with a custom app designed to do so
A Javascript error on your page (caused by any number of things) could result in some, but not all, of your validation running
In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.
You must always validate on the server.
Also having validation on the client is nice for users, but is utterly insecure.
Well, I still find some room to answer.
In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:
Client-Side
Must use client-side validations in order to filter genuine requests coming from genuine users at your website.
The client-side validation should be used to reduce the errors that might occure during server side processing.
Client-side validation should be used to minimize the server-side round-trips so that you save bandwidth and the requests per user.
Server-Side
You SHOULD NOT assume the validation successfully done at client side is 100% perfect. No matter even if it serves less than 50 users. You never know which of your user/emplyee turn into an "evil" and do some harmful activity knowing you dont have proper validations in place.
Even if its perfect in terms of validating email address, phone numbers or checking some valid inputs it might contain very harmful data. Which needs to be filtered at server-side no matter if its correct or incorrect.
If client-side validation is bypassed, your server-side validations comes to rescue you from any potential damage to your server-side processing. In recent times, we have already heard lot of stories of SQL Injections and other sort of techniques that might be applied in order to gain some evil benefits.
Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.
You can do Server side validation and send back a JSON object with the validation results for each field, keeping client Javascript to a minimum (just displaying results) and still having a user friendly experience without having to repeat yourself on both client and server.
Client side should use a basic validation via HTML5 input types and pattern attributes and as these are only used for progressive enhancements for better user experience (Even if they are not supported on < IE9 and safari, but we don't rely on them). But the main validation should happen on the server side..
I will suggest to implement both client and server validation it keeps project more secure......if i have to choose one i will go with server side validation.
You can find some relevant information here
https://web.archive.org/web/20131210085944/http://www.webexpertlabs.com/server-side-form-validation-using-regular-expression/
I came across an interesting link that makes a distinction between gross, systematic, random errors.
Client-Side validation suits perfectly for preventing gross and random errors. Typically a max length for any input. Do not mimic the server-side validation rule; provide your own gross, rule of thumb validation rule (ex. 200 characters on client-side; a specific n chars less than 200 on server-side dictated by a strong business rule).
Server-side validation suits perfectly for preventing systematic errors; it will enforce business rules.
In a project I'm involved in, the validation is done on the server through ajax requests. On the client I display error messages accordingly.
Further reading: gross, systematic, random errors:
https://answers.yahoo.com/question/index?qid=20080918203131AAEt6GO
JavaScript can be modified at runtime.
I suggest a pattern of creating a validation structure on the server, and sharing this with the client.
You'll need separate validation logic on both ends, ex:
"required" attributes on inputs client-side
field.length > 0 server-side.
But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.
Client side data validation can be useful for a better user experience: for example, I a user who types wrongly his email address, should not wait til his request is processed by a remote server to learn about the typo he did.
Nevertheless, as an attacker can bypass client side validation (and may even not use the browser at all), server side validation is required, and must be the real gate to protect your backend from nefarious users.
If you are doing light validation, it is best to do it on the client. It will save the network traffic which will help your server perform better. If if it complicated validation that involves pulling data from a database or something, like passwords, then it best to do it on the server where the data can be securely checked.

Securing pure Ajax/Javascript client

We are creating an online service divided like that:
- an API, of course
- full JS/AJAX client, no MVC, it is pure JS
We are experienced developers and we do know that we can't secure the JS client code, however, we are trying to figure way to prevent 3rd parties from creating their own client by analyzing our JS API Call and this way restrict access only from our own client.
Thanks in advance!
We are experienced developers and we do know that we can't secure the
JS client code, however, we are trying to figure way to prevent 3rd
parties from creating their own client by analyzing our JS API Call
and this way only restreint access from our own client.
That is contradiction in terms. If you know that client-side ECMAscript code can never be hidden, it will always be possible for any somewhat experienced developer to analyse your code. Even if heavily obfuscated, minified and uglified.
Use a server-side authentication, by password. Its the only secure way. You just can not prevent that somebody will clone/copy your script.
I don't think you can. Perhaps generate a key or something to authorize requests.
For you and anyone with a similar question, take heed; it is impossible. If you send a user working code that will communicate with your API, there is nothing you can do to stop then modifying or re-writing that code. The only area you can keep secure is the back-end.
Oh, this is the wrong question to ask.
The question you need to ask is "why do I care if someone accesses my server without my client?"
You obviously have a reason. I can think of one reason only - your server trusts the client to behave nicely. Don't do that. Make sure the server can handle any kind of zany client request. It doesn't have to handle it nicely (throwing a 500 Server Error is OK) - as long as rogue clients can't mess with your data or kill your server entirely.
You could try to obfuscate your javascript code to make it hard readable:
a link to an obfuscator
you can find outhers
If you have authentification, you can pass session id to your API to keep user logged in, so if user is not authentificated he won't be able to get data from your API.

Is it ok to not display an error when server side verification fails when JavaScript is required?

We have a form that absolutely requires JavaScript to function, and validation is done client side. Validation is also performed server side, but it would be an extreme amount of work to get it to show errors when server side verification fails.
Since there is no chance for the user to not have JavaScript, is it OK to just fail with an HTTP error? The only way they would fail server side verification was if they either are a malicious user, or can't use JavaScript, in which case they wouldn't be using the form anyway.
Thanks
I say this is fine, except for a certain class of errors.
Some validation errors are not a result of malice but simply cannot be checked and discovered at any other time than when the form is actually processed. This can be because of a scarce resource that needs to be reserved but cannot be ("this username is already in use"), or because of some server-side recoverable error ("The upstream Credit Card processor is not responding. Please try again later"). For these kinds of errors, you absolutely should have some kind of error message communicated back to the user. It's hard to envision a design where sending these kinds of errors back would not be possible. At the very least you can do this:
Send your HTTP error response (4xx or 5xx depending on the nature of the error)
In the body of your response, package an error message in some data structure your javascript can understand easily. (JSON or XML, or even text/plain! Remember to set the mime type.)
Have the error-handler for the javascript request insert the text of the error at a visible place in your form (e.g. at the top or near the submit button).
The most important thing, however, is to have server-side validation and not trust the client. You are already doing this, so if you want to do anything further it is a matter of polish and making for the best possible user experience. Sometimes that requires a disproportionate amount of effort and that's ok.
I personally think it is fine.
Especially if a previous step in using the site would also not work at all without Javascript, so the user couldn't have proceeded to the page in question without Javascript, then going to the huge expense of making it work without Javascript is wasted effort. For example, in .Net webforms, logging in requires Javascript, so any pages inside the secured area of the site can, to my mind, assume Javascript is available.
I'm curious what other people think, though.
If the only expected use case for failing the http request is when someone has bypassed the browser, then just failing the http request seems perfectly fine. You aren't impacting any expected user scenario, yet you are still protecting the server-side integrity with server-side validation. There's no point in doing more work than that. Seems fine to me.
What would make it worth it to do more work to show error UI from the server would be if there are actual legitimate user scenarios where bad data would get through to the server. But, since you think that is unlikely or impossible for a legitimate scenario to go there, then there's no reason do do that extra work.
It is ok so long as you are certain that the client side validation and server-side validation are equivalent. On that note, I find it hassle some to keep the client-side validation code and server-side validation code in sync (Especially if they are written in different languages, which is always the case if you are not using node.js or GWt). If anyone has any solution that it would be great.
However, if there are certain validation that can only be performed on server-side (database uniqueness constraint, for instance), then it is important to show user that their client-side actions have failed. That depends on the application itself though.

Javascript form validation on client side without server side - is it safe?

Supose I have some form with javascript client side validation and no server side validation.
If user disable javascript in his browser there will no be submit button so he can not send me any data without js enabled.
But I do not know is there any way to change my validation instructions from client browser so he could send me untrusted data and make some damage to my database.
Thanks in advance and sorry for my (possibly) obvious question!!!
No. it is not safe. Use server side validation.
For example, even without the browser, I can read your source code. Then simply use CURL to send a post request with malicious data.
Never, ever trust the client.
No, it's not safe. For example, I could just open up the JavaScript debugger in my browser and override your validation.
Anyone who is capable of disabling javascript on their own is probably also capable of making arbitrary POST requests on their own as well. Ok I might be exaggerating but it's still not safe as someone can do the POST requests without using browser, let alone your form, at all.
I would suggest use both client side and server side validation.
Benifit of client side validation is it's fast, we never hit server until user enter correct input. This saves time and avoid user flustration. This is really helpful in large forms.
However demerit is a bad guy can override the client side validation, Hence to avoid such case we should validate in serverside also before processing data.

Categories

Resources