Checking Arguments

Below you'll find a sample chapter from Secure Meteor; a guide to help you learn the ins and outs of securing your Meteor application from a Meteor security professional. If you like what you read and you're interested in securing your Meteor application, be sure to read the entire book!

Most Meteor methods and publications accept user-provided arguments. Arguments to Meteor methods and publications can be passed as any JSON-serializable data such as numbers, strings, booleans, arrays, objects, or any combination of those primitive types. Let’s consider an example:

We’ve created a method called sayHello that takes a name as a parameter and returns a greeting. We’ll use this method to greet new users to our shopping application.

While we’re expecting that this method would be used exclusively by the client-side portion of our Meteor application, a curious user could call this Meteor method manually from their browser’s console:

Eventually, "Hello, Pete." would be returned and logged to their console, just as we’d expect.

In this example, we’re assuming that the provided name argument is a string. But as we mentioned, this isn’t necessarily the case. The user can pass any JSON-serializable value to the server through the name parameter:

In this case, the user passed up an object rather than a string. Our server handily coerces the object into a string and drops it into our greeting. Eventually the client receives their greeting: "Hello, [object Object]."

Instead of making assumptions about the type of the name argument, we should explicitly state what we’re expecting. We can easily do that with Meteor’s Check library:

By adding a call to check at the head of our method, we’re asserting our expectations. In this case, we’re asserting that name should be a String. If name is any other type of value, like an object, an exception will be thrown and our Meteor method will immediately return. When we use check in this way, we say that we’re “checking our arguments.”

Instead of making assumptions, we should explicitly state what we’re expecting.

Now if our curious user calls our sayHello method with an object, they’ll receive an error instead of the expected greeting:

We’ve successfully checked the type of our name argument. Any arguments of an unexpected type will result in a similar error, and prevent the code following the call to check from having to deal with a potentially unsafe value.

It’s the client’s responsibility to ensure that they’re passing the expected arguments to a Meteor method. As we’ll see, it’s important that the server be extremely strict in enforcing assertions about the expected types and shapes of its arguments.