Ready for iOS 8? So is Parse Push

In this year’s WWDC, Apple announced some great changes to iOS Notifications. First, Apple has increased the maximum payload size to two kilobytes rather than 256 bytes. This new limit is retroactive and works with all existing devices! The more subtle changes to push notifications involve security and interaction with notifications.

“Silent” pushes are push notifications that don’t create UI; they instead tell your app to fetch or react to new content available online. In iOS 8, Apple has separated out the permissions for UI and push. The push permission is auto-accepted by default too! This means your iOS 8 apps will be able to much more reliably depend on the ability to receive silent notifications in iOS 8. To migrate your app, change the following code:

// Before iOS 8:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert |
                                                                      UIRemoteNotificationTypeBadge |
                                                                      UIRemoteNotificationTypeSound];

to

// For iOS 8:
UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert |
                                                 UIUserNotificationTypeBadge |
                                                 UIUserNotificationTypeSound
                                      categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
Even if the user declines permission for creating UI, the permission to send (silent) pushes is auto-accepted for most users.

Notice the nil param for categories above? Categories unlock a whole new dimension to push notifications in iOS 8. Categories describe “actions” that should be presented in your notification in various views. Actions provide custom buttons your users can use when interacting with your push notification; your action can launch the app into the foreground or even trigger a background action, such as accepting or declining a calendar invite. To enable this feature, you must define a UIUserNotificationCategory. These categories have an identifier string and a map of UIUserNotificationActionContext to many UIUserNotificationActions. A UIUserNotificationActionContext comes in two flavors: default and minimal. The default context specifies which actions should be presented when the notification has an alert UI and supports a maximum of four actions; the minimal context specifies which actions should be presented when the notification has a banner UI or is on the lock screen and supports a maximum of two actions.  Once you’ve registered notification categories with your application, sending them via Parse Push is easy: simply pass the category identifier as the category option in your push. This feature is supported retroactively on all Parse SDKs, you don’t even need to upgrade! You may, however, want to check out the new UIApplicationDelegate method application:handleActionWithIdentifier:forRemoteNotification:completionHandler:

iOS 8 allows developers to define actions an end user can take when responding to a notification.

We look forward to seeing the great things you build with Parse and iOS 8!

Thomas Bouldin
September 15, 2014

The Dangerous World of Client Push

Push Notifications are one of the most effective ways for apps to increase user engagement and retention, notify customers of important information like sales and new products, or allow users communicate with each other. A messaging app, for example, could use push notifications to alert users to an incoming message from their friend in the app. But be careful, because the most obvious way to do this can expose you to a security risk.

One easy way to send push notifications to particular users from within an app is to send the pushes directly from the client code, for example by using PFPush on iOS. This is tempting, because you have all the information you need to send the push straight from within iOS, and the code to send the push is very simple. But as Bryan mentioned in his security series, clients can’t be trusted to send push notifications directly. Some nefarious hacker could modify the client code, changing the Objective-C or Java code to modify the push’s alert text, or to send pushes to people they shouldn’t be able to. The hacker could steal your app’s keys and send pushes himself without even using the app.

Sounds scary! Luckily, there is a simple way around this security vulnerability. In your app’s settings, under “Push Notifications”, there is a toggle that lets you disable “Client Push.” We highly recommend that you set this switch to “OFF,” and instead of sending the push notifications from the client, you should write Cloud Code functions that validate the user and the data to be pushed before sending them. Client Push is disabled by default, but this feature can still be useful for initial prototyping if you want to hook up push notifications without diving into Cloud Code as you iterate. But as you scale to a production app, you really should not have Client Push enabled.

Here is one example of how to port your pushes from the client into Cloud Code, starting with an example Client Push to a single user, stored in userObject. Here’s the old iOS code:

// WRONG WAY TO SEND PUSH - INSECURE!
PFQuery *pushQuery = [PFInstallation query];
[pushQuery whereKey:@"user" equalTo:userObject];
PFUser *user = [PFUser currentUser];
NSString *message = [NSString stringWithFormat:@"%@ says Hi!", user[@"name"]];

PFPush *push = [[PFPush alloc] init];
[push setQuery:pushQuery]; // Set our Installation query
[push setMessage:message];
[push sendPushInBackground];

And on Android:

// WRONG WAY TO SEND PUSH - INSECURE!
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereEqualTo("user", userObject);
ParseUser currentUser = ParseUser.getCurrentUser();
String message = currentUser.getString("name") + " says Hi!";

ParsePush push = new ParsePush();
push.setQuery(pushQuery); // Set our Installation query
push.setMessage(message);
push.sendInBackground();

To move these push calls to Cloud Code, first we would write a Cloud function, sendPushToUser, to verify that the user sending the push is allowed to send it and that the alert text is what it should be.

Parse.Cloud.define("sendPushToUser", function(request, response) {
  var senderUser = request.user;
  var recipientUserId = request.params.recipientId;
  var message = request.params.message;

  // Validate that the sender is allowed to send to the recipient.
  // For example each user has an array of objectIds of friends
  if (senderUser.get("friendIds").indexOf(recipientUserId) === -1) {
    response.error("The recipient is not the sender's friend, cannot send push.");
  }

  // Validate the message text.
  // For example make sure it is under 140 characters
  if (message.length > 140) {
  // Truncate and add a ...
    message = message.substring(0, 137) + "...";
  }

  // Send the push.
  // Find devices associated with the recipient user
  var recipientUser = new Parse.User();
  recipientUser.id = recipientUserId;
  var pushQuery = new Parse.Query(Parse.Installation);
  pushQuery.equalTo("user", recipientUser);
 
  // Send the push notification to results of the query
  Parse.Push.send({
    where: pushQuery,
    data: {
      alert: message
    }
  }).then(function() {
      response.success("Push was sent successfully.")
  }, function(error) {
      response.error("Push failed to send with error: " + error.message);
  });
});

 After you deploy this Cloud function, you can call the code from iOS like this:

[PFCloud callFunctionInBackground:@"sendPushToUser"
                   withParameters:@{@"recipientId": userObject.id, @"message": message}
                            block:^(NSString *success, NSError *error) {
  if (!error) {
     // Push sent successfully
  }
}];

And on Android:

HashMap<String, Object> params = new HashMap<String, Object>();
params.put("recipientId", userObject.getObjectId());
params.put("message", message);
ParseCloud.callFunctionInBackground("sendPushToUser", params, new FunctionCallback<String>() {
   void done(String success, ParseException e) {
       if (e == null) {
          // Push sent successfully
       }
   }
});

Now that you have moved the Push logic into Cloud Code, you can disable Client Push in your app settings, and spoil the hacker’s evil plan! We hope you learned how to use Cloud Code to secure your app’s push notifications, and that you will think twice before enabling Client Push for your app. As always, feel free to ask questions or let us know what you think on our new Help page.

Jamie
September 3, 2014

Open Sourcing the f8 Conference Apps

f8 App

 

As part of the f8 conference experience, we launched iOS and Android apps built entirely on Parse. The app enabled conference attendees to stay up-to-date with upcoming talks, get to know the speakers, and receive push notifications on talks they had marked as favorites.

This app grew out of the Parse Developer Day apps, and was thoroughly customized to match the f8 experience. Using Parse to build these apps was a fun experience, and it took one iOS and Android developer around two weeks to deliver the apps. Parse Data was used to store all the conference data and much of the User Interface (UI) customizations and assets, enabling quick iteration on design changes across iOS and Android. Even after the app was shipped, last minute updates were possible without touching code, simply by using the Data Browser. And, as talks were in session, the Push Console was used for ad hoc messaging to conference attendees–it’s vitally important to know when to pick up those T-shirts.

Today, we are releasing the source code for these apps so you can peek under the hood and see how they were built. The source code is available on GitHub. We hope they will serve as good guidance for how to build apps on Parse. We also hope others find them useful as a starting point for their own conference apps. We can’t wait to see what you do with them!

Christine Abernathy
August 28, 2014

Parse for PHP: A Fractal of Rad Design

Parse for PHP

Today we are very happy to release the Parse PHP SDK, which will enable Parse integration for a whole new class of apps and different use cases. This is our first SDK for a server-side language, and the first to be truly open-source.

PHP is an incredibly popular programming language and has consistently been in the top 10 on the TIOBE index for the past 15 years. Some metrics report that it is still serving the vast majority of websites on the internet. Until now, if you wanted to access Parse from PHP, the REST API was the only option. A few Parse API wrapper libraries have been released by third parties on GitHub. While we think this is awesome, many developers requested better PHP support and we decided to build a first-party SDK.

Earlier this year at Facebook’s f8 developer conference, we launched the completely re-invented Facebook SDK for PHP. In the 3 months since it was released there have been over 160 commits, with good solid contributions and enhancements from 20 passionate developers who use and care about the product. It has been a lot of fun managing the process for the Facebook SDK, and I’m looking forward to working together with the community on this Parse SDK.

For a fast overview of the SDK, check out the README file. We’ve also updated our documentation with a new PHP guide, and added a PHP Quickstart with installation instructions. We encourage you to report any issues and requests on GitHub.

Go build something awesome with Parse + PHP!

Fosco Marotto
August 5, 2014

Parse Security VI – Quiz Time

In Part VI of our five-part series on how to secure your Parse app, let’s take a quiz and see how well you know your stuff. If you can’t handle having Part VI in a five-part series, then maybe you should go read up on buffer overflow exploits. ;-)

Part I   Part II   Part III   Part IV   Part V

Bryan Klimt
August 4, 2014

Parse Security V – How to Make Friends

In the first four parts of this five-part series on how to secure your Parse app, we’ve taken a look at all of the different features that Parse has to help you secure your app and your users’ data. In Part V, let’s put it all together and take a look at a real example of how you can use these features to solve a complex use case.

Most classes in your app will fall into one of a couple of easy-to-secure categories. For fully public data, you can use class-level permissions to lock down the table to put publicly readable and writeable by no one. For fully private data, you can use ACLs to make sure that only the user who owns the data can read it. But occasionally, you’ll run into situations where you don’t want data that’s fully public or fully private. For example, you may have a social app, where you have data for a user that should be readable only to friends whom they’ve approved. For this you’ll need to use ACLs, roles, and Cloud Code together to enable exactly the sharing rules you desire.

If you aren’t clear on those features, go back and read Parts II – IV of this series. Once you’re clear on what ACLs, roles, and Cloud Code are, let’s dig into some code. The first thing you’ll need to do is set up a place for the user’s social data to live. Let’s assume you want to create a “FriendData” object for each user that stores the data that should be visible to their friends. To create this object for each new user, you can use an afterSave handler.

Parse.Cloud.afterSave(Parse.User, function(request, response) {
    var user = request.object;
    if (user.existed()) { return; }
    var roleName = "friendsOf_" + user.id;
    var friendRole = new Parse.Role(roleName, new Parse.ACL(user));
    return friendRole.save().then(function(friendRole) {
        var acl = new Parse.ACL();
        acl.setReadAccess(friendRole, true);
        acl.setReadAccess(user, true);
        acl.setWriteAccess(user, true);
        var friendData = new Parse.Object("FriendData", {
          user: user,
          ACL: acl,
          profile: "my friend profile"
        });
        return friendData.save();
    });
});

The first couple of lines just set up the request. On line 3, we check to see if the user already existed. If so, then we’ve already completed this setup, and there’s no reason to do it again. On lines 4-6, we create a new role. This role will represent the friends of the user being created. We generate a unique name for the role. The role is created with an ACL that only allows this user to read or write it. In other words, only the user themselves can decide who their friends are.

Once the role is created, lines 7-10 create an ACL that grants read permission to friends of the user. And of course the user receives read and write permission for their own social data. Once the ACL is set up, lines 11-16 actually create the object. The user is set on the object so that it can be found with a query later. The profile field is set as an example of data that will be readable only to the users friends.

So, that’s everything you need to set up an object for every user that will be readable only to people in their special friends role. Of course, that’s worthless without any way for people to get added to your friends list, so we need to address that with another function. Technically, this function could be written in any client and be secure, but for the sake of consistency, let’s make another Cloud Code function. This function will be called “friend.”  It will take one parameter: the objectId of the person to friend. This person will then be added to the friends role of the current user.

Parse.Cloud.define("friend", function(request, response) {
    var userToFriend = new Parse.User();
    userToFriend.id = request.params.friendId;

    var roleName = "friendsOf_" + request.user.id;
    var roleQuery = new Parse.Query("_Role");
    roleQuery.equalTo("name", roleName);
    roleQuery.first().then(function(role) {
        role.getUsers().add(userToFriend);
        return role.save();

    }).then(function() {
        response.success("Success!");    
    });
});

Lines 1-3 just set up the function and create a User object to represent the person being added to the friend role. Lines 5-8 fetch the Role object using its name. A Role is just a special kind of Parse object, so we need to fetch it before we can modify it. Once the role has been fetched, we add this user to it on line 9, and save it on line 10. That’s all there is to it! Now we have an easy way to store data that’s only accessible to a user’s friends.

Over the course of this five-part series on how to secure your Parse app, we’ve looked at a lot of features. You know the about the various keys used to access your app. We’ve looked at the permissions you can set to lock down a whole class. You’ve learned about ACLs and how they can secure per-user data. And we’ve even dived deep into a particular example of how you can use Cloud Code to tackle even the trickiest data models.

We hope that you’ll use these tools to do everything you can to keep your app’s data and your users’ data secure. Together, we can make the web a safer place.

Part I   Part II   Part III   Part IV

Bryan Klimt
July 28, 2014

Parse Security IV – Ahead in the Cloud

In our first three posts on how to secure your Parse app, we looked at your app’s keys, class-level permissions, and object-level ACLs. For many apps, that’s all you need to keep your app and your users’ data safe. But sometimes you’ll run into an edge case where they aren’t quite enough. For everything else, there’s Cloud Code.

With Cloud Code, you can upload JavaScript to Parse’s servers, where we will run it for you. Unlike client code running on users’ devices that may have been tampered with, Cloud Code is guaranteed to be the code that you’ve written, so it can be trusted with more responsibility. For example, if you need to validate the data that a user has entered, you should do it in Cloud Code so that you know a malicious client won’t be able to bypass the validation logic. Specifically to help you validate data, Cloud Code has beforeSave triggers. These triggers are run whenever an object is saved, and allow you to modify the object, or completely reject a save. For example, this is how you create a Cloud Code trigger to make sure every user has an email address set:

Parse.Cloud.beforeSave(Parse.User, function(request, response) {
  var user = request.object;
  if (!user.get("email")) {
    response.error("Every user must have an email address.");
  } else {
    response.success();
  }
});

To upload this trigger, follow the instructions in our guide for setting up the Parse command line tool.

You can also use your master key in Cloud Code to bypass the normal security mechanism for trusted code. For example, if you want to allow a user to “like” a “Post” object without giving them full write permissions on the object, you can do so with a Cloud Code function. Every API function in the Cloud Code JavaScript SDK that talks to Parse allows passing in a useMasterKey option. By providing this option, you will use the master key for that one request.

Parse.Cloud.define("like", function(request, response) {
  var post = new Parse.Object("Post");
  post.id = request.params.postId;
  post.increment("likes");
  post.save(null, { useMasterKey: true }).then(function() {
    response.success();
  }, function(error) {
    response.error(error);
  });
});

One very common use case for Cloud Code is sending push notifications to particular users. In general, clients can’t be trusted to send push notifications directly, because they could modify the alert text, or push to people they shouldn’t be able to. Your app’s settings will allow you to set whether “client push” is enabled or not; we recommend that you make sure it’s disabled. Instead, you should write Cloud Code functions that validate the data to be pushed before sending a push.

In this post, we’ve looked at how you can use Cloud Code to write trusted code, to keep your data secure in cases where class-level permissions and ACLs aren’t enough. In Part V, we’ll dive into a particular example of how to use ACLs, Roles, and Cloud Code to let users have data that is shared only to their friends.

Part I   Part II   Part III   Part V

Bryan Klimt
July 21, 2014

Parse Security III – Are You On the List?

In Part II, we looked at class-level permissions, which allow you to quickly set permissions for an entire class at once. But often, the different objects in a class will need to be accessible by different people. For example, a user’s private personal data should be accessible only to them. For that, you have to use an Access Control List, usually referred to as an ACL. If you have a production app and you aren’t using ACLs, you’re almost certainly doing it wrong.

An ACL specifies a set of users who can read or write an object’s data. So, before you can use ACLs, you have to have Users. There are many ways to handle users on Parse. You can have usernames and passwords, or you can use Facebook Login. If you don’t want to make your users create usernames just to log in, you can even use Parse’s automatic anonymous users feature. That allows you to create a user and log them in on a particular device in a secure way. If they later decide to set a username and password, or link the account with Facebook, then they can then log in from any other device. Setting up automatic anonymous users is easy, so you have no excuse not to protect per-user data!

[PFUser enableAutomaticUser];

Once you have a user, you can start using ACLs. To set an ACL on the current user’s data to not be publicly readable, all you have to do is:

PFUser *user = [PFUser currentUser];
user.ACL = [PFACL ACLWithUser:user];

Most apps should do this. If you store any sensitive user data, such as email addresses or phone numbers, you need to set an ACL like this so that the user’s private information isn’t visible to other users. If an object doesn’t have an ACL, it’s readable and writeable by everyone. The only exception is the _User class. We never allow users to write each other’s data, but they can read it by default. (If you as the developer need to update other _User objects, remember that your master key can provide the power to do this.) To make it super easy to create user-private ACLs for every object, we have a way to set a default ACL that will be used for every new object you create.

[PFACL setDefaultACL:[PFACL ACL] withAccessForCurrentUser:YES];

If you want the user to have some data that is public and some that is private, it’s best to have two separate objects. You can add a pointer to the private data from the public one.

PFObject *privateData = [PFObject objectWithClassName:@"PrivateUserData"];
privateData.ACL = [PFACL ACLWithUser:[PFUser currentUser]];
[privateData setObject:@"555-5309" forKey:@"phoneNumber"];

[PFUser setObject:privateData forKey:@"privateData"];

Of course, you can set different read and write permissions on an object. For example, this is how you would create an ACL for a public post by a user, where anyone can read it:

PFACL *acl = [PFACL ACL];
[acl setPublicReadAccess:true];
[acl setWriteAccess:true forUser:[PFUser currentUser]];

Sometimes, it’s inconvenient to manage permissions on a per-user basis, and you want to have groups of users who get treated the same. For example, your app may have a group of admins who are the only ones who can write data. Roles are are a special kind of object that let you create a group of users that can all be assigned to the ACL. The best thing about roles is that you can add and remove users from a role without having to update every single object that is restricted to that role. To create an object that is writeable only by admins:

PFACL *acl = [PFACL ACL];
[acl setPublicReadAccess:true];
[acl setWriteAccess:true forRoleWithName:@"admins"];

Of course, this snippet assumes you’ve already created a role called “admins”. In many cases, this is reasonable, because you have a small set of special roles you can set up while developing your app. But sometimes you will need to create roles on the fly. In a future blog post, we’ll look into how you can use ACLs and roles to manage a user’s data so that it will only be visible to their friends.

So far in this security series, we’ve covered class-level permissions and ACLs. These features are sufficient to secure the vast majority of apps. In Part IV, we’ll look at how you can use Cloud Code to secure apps even in rare edge cases.

Part I   Part II   Part IV   Part V

Bryan Klimt
July 14, 2014

Parse Security II – Class Hysteria!

In Part I, we took a look at the different keys that a Parse app has and what they mean. As we learned, your client keys are easily accessible to anybody, so you need to rely on Parse’s security features to lock down what the client key is allowed to do.

The easiest way to lock down your app is with class-level permissions. Almost every class that you create should have these permissions tweaked to some degree. For classes where every object has the same permissions, class-level settings will be most effective. For example, one common use case: having a class of static data that can be read by anyone but written by no one. If you need different objects to have different permissions, you’ll have to use ACLs–Access Control Lists–(discussed in Part III). To edit your class-level permissions, click on “Set permissions” under the “More” menu in the Data Browser for the class you want to configure.

Set permissions menu

For each setting, you can choose to either leave it open to everyone, or to restrict it to certain predefined Roles or Users. A Role is simply a set of Users and Roles who should share some of the same permissions. For example, you can set up a Role called “admins” and make a table writeable only by that role.

Class-level Permissions

Let’s go over what each permission means.

  • Get – With Get permission, users can fetch objects in this table if they know their objectIds.
  • Find – Anyone with Find permission can query all of the objects in the table, even if they don’t know their objectIds. Any table with public Find permission will be completely readable by the public, unless you put an ACL on each object.
  • Update – Anyone with Update permission can modify the fields of any object in the table that doesn’t have an ACL. For publicly readable data, such as game levels or assets, you should disable this permission.
  • Create – Like Update, anyone with Create permission can create new objects of a class. As with the Update permission, you’ll want to turn this off for publicly readable data.
  • Delete – This one should be pretty obvious. With this permission, people can delete any object in the table that doesn’t have an ACL. All they need is its objectId.
  • Add fields -This is probably the strangest permission. Parse classes have schemas that are inferred when objects are created. While you’re developing your app, this is great, because you can add a new field to your object without having to make any changes on the backend. But once you ship your app, it’s very rare to need to add new fields to your classes automatically. So you should pretty much always turn off this permission for all of your classes when you submit your app to the public.

There’s also an app-level permission to disable client class creation. You should turn this off for production app so that clients can’t create new classes. Usually this isn’t a big security risk, but it’s nice to stop malicious people from creating new tables that you’ll see in the data browser.

Client Class Creation

Class-level permissions are great for globally-shared data where permissions for each object in the class should be exactly the same. In Part III, we’ll learn about ACLs, which allow you to have different permissions for each object in a class.

Part I   Part III   Part IV   Part V

Bryan Klimt
July 7, 2014

Parse Security I – Are you the Key Master?

So, you’ve finished version 1 of your app, and you’re ready to send it out into the world. Like a child leaving the nest, you are ready to push your app out to the various app stores and wait for the glowing reviews to come streaming in. Not so fast! You wouldn’t send a child out into the world without teaching them how to protect themselves. Likewise, you shouldn’t send your app out into a user’s hands without taking some time to secure it using industry-standard best practices. After all, if your app gets compromised, it’s not only you who suffers, but potentially the users of your app as well. In this five-part series, we’ll take a look at what you can do to secure your Parse app.

Parse App Keys

Security starts with understanding your app’s keys. A Parse app has several different keys: a client key, a REST key, a .NET key, a JavaScript key, and a master key. All of the keys–other than the master key–have basically the same permissions. They are just intended for use on different platforms. So, we usually refer to any of those keys as a “client key.” The first thing you need to understand is that your client key is not a security mechanism. It’s not even intended to serve as such. Your client key is shipped as a part of your app. Anyone can decompile your app or proxy network traffic from their device and see your client key. With JavaScript, it’s even easier. One can simply “view source” in the browser and immediately know your key. That’s why Parse has many other security features to help you secure your data. The client key is given out to your users, so anything that can be done with just the client key is doable by the general public, even malicious hackers.

The master key, on the other hand, is definitely a security mechanism. Using the master key allows you to bypass all of your app’s security mechanisms, such as class-level permissions and ACLs. Having the master key is like having root access to your app’s servers. You should guard your master key with the same zeal with which you would guard your production machines’ root password. Never check your master key into source control. Never include your master key in any binary or source code you ship to customers. And above all, never, ever give your master key out to strangers in online chat rooms. Stranger danger!

In Part II, we’ll take a look at Parse’s advanced features, which allow you to control what people with your client key can do.

Part II   Part III   Part IV   Part V

Bryan Klimt
June 30, 2014