diff options
author | fgorski@chromium.org <fgorski@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-01-13 19:51:21 +0000 |
---|---|---|
committer | fgorski@chromium.org <fgorski@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-01-13 19:51:21 +0000 |
commit | 0362fb1f82c47e1e0acd34cf54019a16fa8b5b28 (patch) | |
tree | f276a3993e65a2cd0de6468b6e48eb4a32bc42ce /google_apis | |
parent | 96d4875837f247e9539118d7b87bc703d8123b95 (diff) | |
download | chromium_src-0362fb1f82c47e1e0acd34cf54019a16fa8b5b28.zip chromium_src-0362fb1f82c47e1e0acd34cf54019a16fa8b5b28.tar.gz chromium_src-0362fb1f82c47e1e0acd34cf54019a16fa8b5b28.tar.bz2 |
GCM Registration Request
* implementation of request creation
* implementation of response parsing
* tests for both.
BUG=284553
Review URL: https://codereview.chromium.org/126513007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@244561 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'google_apis')
-rw-r--r-- | google_apis/gcm/engine/registration_request.cc | 156 | ||||
-rw-r--r-- | google_apis/gcm/engine/registration_request.h | 86 | ||||
-rw-r--r-- | google_apis/gcm/engine/registration_request_unittest.cc | 204 | ||||
-rw-r--r-- | google_apis/gcm/gcm.gyp | 3 |
4 files changed, 449 insertions, 0 deletions
diff --git a/google_apis/gcm/engine/registration_request.cc b/google_apis/gcm/engine/registration_request.cc new file mode 100644 index 0000000..64f49a9 --- /dev/null +++ b/google_apis/gcm/engine/registration_request.cc @@ -0,0 +1,156 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "google_apis/gcm/engine/registration_request.h" + +#include "base/bind.h" +#include "base/message_loop/message_loop.h" +#include "base/strings/string_number_conversions.h" +#include "base/values.h" +#include "net/base/escape.h" +#include "net/http/http_request_headers.h" +#include "net/http/http_status_code.h" +#include "net/url_request/url_fetcher.h" +#include "net/url_request/url_request_context_getter.h" +#include "net/url_request/url_request_status.h" +#include "url/gurl.h" + +namespace gcm { + +namespace { + +const char kRegistrationURL[] = + "https://android.clients.google.com/c2dm/register3"; +const char kRegistrationRequestContentType[] = + "application/x-www-form-urlencoded"; + +// Request constants. +const char kAppIdKey[] = "app"; +const char kCertKey[] = "cert"; +const char kDeviceIdKey[] = "device"; +const char kLoginHeader[] = "AidLogin"; +const char kSenderKey[] = "sender"; +const char kUserAndroidIdKey[] = "X-GOOG.USER_AID"; +const char kUserSerialNumberKey[] = "device_user_id"; + +// Request validation constants. +const size_t kMaxSenders = 100; + +// Response constants. +const char kTokenPrefix[] = "token="; + +void BuildFormEncoding(const std::string& key, + const std::string& value, + std::string* out) { + if (!out->empty()) + out->append("&"); + out->append(key + "=" + net::EscapeUrlEncodedData(value, true)); +} + +} // namespace + +RegistrationRequest::RequestInfo::RequestInfo( + uint64 android_id, + uint64 security_token, + uint64 user_android_id, + int64 user_serial_number, + const std::string& app_id, + const std::string& cert, + const std::vector<std::string>& sender_ids) + : android_id(android_id), + security_token(security_token), + user_android_id(user_android_id), + user_serial_number(user_serial_number), + app_id(app_id), + cert(cert), + sender_ids(sender_ids) {} + +RegistrationRequest::RequestInfo::~RequestInfo() {} + +RegistrationRequest::RegistrationRequest( + const RequestInfo& request_info, + const RegistrationCallback& callback, + scoped_refptr<net::URLRequestContextGetter> request_context_getter) + : callback_(callback), + request_info_(request_info), + request_context_getter_(request_context_getter) {} + +RegistrationRequest::~RegistrationRequest() {} + +void RegistrationRequest::Start() { + DCHECK(!callback_.is_null()); + DCHECK(request_info_.android_id != 0UL); + DCHECK(request_info_.security_token != 0UL); + DCHECK(!request_info_.cert.empty()); + DCHECK(0 < request_info_.sender_ids.size() && + request_info_.sender_ids.size() <= kMaxSenders); + + DCHECK(!url_fetcher_.get()); + url_fetcher_.reset(net::URLFetcher::Create( + GURL(kRegistrationURL), net::URLFetcher::POST, this)); + url_fetcher_->SetRequestContext(request_context_getter_); + + std::string android_id = base::Uint64ToString(request_info_.android_id); + std::string auth_header = + std::string(net::HttpRequestHeaders::kAuthorization) + ": " + + kLoginHeader + " " + android_id + ":" + + base::Uint64ToString(request_info_.security_token); + url_fetcher_->SetExtraRequestHeaders(auth_header); + + std::string body; + BuildFormEncoding(kAppIdKey, request_info_.app_id, &body); + BuildFormEncoding(kCertKey, request_info_.cert, &body); + BuildFormEncoding(kDeviceIdKey, android_id, &body); + + std::string senders; + for (std::vector<std::string>::const_iterator iter = + request_info_.sender_ids.begin(); + iter != request_info_.sender_ids.end(); + ++iter) { + DCHECK(!iter->empty()); + if (!senders.empty()) + senders.append(","); + senders.append(net::EscapeUrlEncodedData(*iter, true)); + } + BuildFormEncoding(kSenderKey, senders, &body); + + if (request_info_.user_serial_number != 0) { + DCHECK(request_info_.user_android_id != 0); + BuildFormEncoding(kUserSerialNumberKey, + base::IntToString(request_info_.user_serial_number), + &body); + BuildFormEncoding(kUserAndroidIdKey, + base::Uint64ToString(request_info_.user_android_id), + &body); + } + + DVLOG(1) << "Registration request: " << body; + url_fetcher_->SetUploadData(kRegistrationRequestContentType, body); + + DVLOG(1) << "Performing registration for: " << request_info_.app_id; + url_fetcher_->Start(); +} + +void RegistrationRequest::OnURLFetchComplete(const net::URLFetcher* source) { + std::string response; + if (!source->GetStatus().is_success() || + source->GetResponseCode() != net::HTTP_OK || + !source->GetResponseAsString(&response)) { + // TODO(fgoski): Introduce retry logic. + LOG(ERROR) << "Failed to get registration response."; + callback_.Run(""); + return; + } + + DVLOG(1) << "Parsing registration response: " << response; + size_t token_pos = response.find(kTokenPrefix); + std::string token; + if (token_pos != std::string::npos) + token = response.substr(token_pos + strlen(kTokenPrefix)); + else + LOG(ERROR) << "Failed to extract token."; + callback_.Run(token); +} + +} // namespace gcm diff --git a/google_apis/gcm/engine/registration_request.h b/google_apis/gcm/engine/registration_request.h new file mode 100644 index 0000000..47cce76 --- /dev/null +++ b/google_apis/gcm/engine/registration_request.h @@ -0,0 +1,86 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef GOOGLE_APIS_GCM_ENGINE_REGISTRATION_REQUEST_H_ +#define GOOGLE_APIS_GCM_ENGINE_REGISTRATION_REQUEST_H_ + +#include <map> +#include <vector> + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "google_apis/gcm/base/gcm_export.h" +#include "net/url_request/url_fetcher_delegate.h" + +namespace net { +class URLRequestContextGetter; +} + +namespace gcm { + +// Registration request is used to obtain registration IDs for applications that +// want to use GCM. It requires a set of parameters to be specified to identify +// the Chrome instance, the user, the application and a set of senders that will +// be authorized to address the application using it's assigned registration ID. +class GCM_EXPORT RegistrationRequest : public net::URLFetcherDelegate { + public: + // Callback completing the registration request. + typedef base::Callback<void(const std::string& registration_id)> + RegistrationCallback; + + // Details of the of the Registration Request. Only user's android ID and + // its serial number are optional and can be set to 0. All other parameters + // have to be specified to successfully complete the call. + struct GCM_EXPORT RequestInfo { + RequestInfo(uint64 android_id, + uint64 security_token, + uint64 user_android_id, + int64 user_serial_number, + const std::string& app_id, + const std::string& cert, + const std::vector<std::string>& sender_ids); + ~RequestInfo(); + + // Android ID of the device. + uint64 android_id; + // Security token of the device. + uint64 security_token; + // User's android ID. (Can be omitted in a single user scenario.) + uint64 user_android_id; + // User's serial number. (Can be omitted in a single user scenario.) + int64 user_serial_number; + // Application ID. + std::string app_id; + // Certificate of the application. + std::string cert; + // List of IDs of senders. Allowed up to 100. + std::vector<std::string> sender_ids; + }; + + RegistrationRequest( + const RequestInfo& request_info, + const RegistrationCallback& callback, + scoped_refptr<net::URLRequestContextGetter> request_context_getter); + virtual ~RegistrationRequest(); + + void Start(); + + // URLFetcherDelegate implementation. + virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; + + private: + RegistrationCallback callback_; + RequestInfo request_info_; + + scoped_refptr<net::URLRequestContextGetter> request_context_getter_; + scoped_ptr<net::URLFetcher> url_fetcher_; + + DISALLOW_COPY_AND_ASSIGN(RegistrationRequest); +}; + +} // namespace gcm + +#endif // GOOGLE_APIS_GCM_ENGINE_REGISTRATION_REQUEST_H_ diff --git a/google_apis/gcm/engine/registration_request_unittest.cc b/google_apis/gcm/engine/registration_request_unittest.cc new file mode 100644 index 0000000..05f506e --- /dev/null +++ b/google_apis/gcm/engine/registration_request_unittest.cc @@ -0,0 +1,204 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <map> +#include <string> +#include <vector> + +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_tokenizer.h" +#include "google_apis/gcm/engine/registration_request.h" +#include "net/url_request/test_url_fetcher_factory.h" +#include "net/url_request/url_request_test_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace gcm { + +namespace { +const uint64 kAndroidId = 42UL; +const char kCert[] = "0DEADBEEF420"; +const char kDeveloperId[] = "Project1"; +const char kLoginHeader[] = "AidLogin"; +const char kNoRegistrationIdReturned[] = "No Registration Id returned"; +const char kAppId[] = "TestAppId"; +const uint64 kSecurityToken = 77UL; +const uint64 kUserAndroidId = 1111; +const int64 kUserSerialNumber = 1; +} // namespace + +class RegistrationRequestTest : public testing::Test { + public: + RegistrationRequestTest(); + virtual ~RegistrationRequestTest(); + + void RegistrationCallback(const std::string& registration_id); + + void CreateRequest(const std::string& sender_ids); + void SetResponseStatusAndString(net::HttpStatusCode status_code, + const std::string& response_body); + void CompleteFetch(); + + protected: + std::string registration_id_; + std::map<std::string, std::string> extras_; + scoped_ptr<RegistrationRequest> request_; + base::MessageLoop message_loop_; + net::TestURLFetcherFactory url_fetcher_factory_; + scoped_refptr<net::TestURLRequestContextGetter> url_request_context_getter_; +}; + +RegistrationRequestTest::RegistrationRequestTest() + : url_request_context_getter_(new net::TestURLRequestContextGetter( + message_loop_.message_loop_proxy())) {} + +RegistrationRequestTest::~RegistrationRequestTest() {} + +void RegistrationRequestTest::RegistrationCallback( + const std::string& registration_id) { + registration_id_ = registration_id; +} + +void RegistrationRequestTest::CreateRequest(const std::string& sender_ids) { + std::vector<std::string> senders; + base::StringTokenizer tokenizer(sender_ids, ","); + while (tokenizer.GetNext()) + senders.push_back(tokenizer.token()); + + request_.reset(new RegistrationRequest( + RegistrationRequest::RequestInfo(kAndroidId, + kSecurityToken, + kUserAndroidId, + kUserSerialNumber, + kAppId, + kCert, + senders), + base::Bind(&RegistrationRequestTest::RegistrationCallback, + base::Unretained(this)), + url_request_context_getter_.get())); +} + +void RegistrationRequestTest::SetResponseStatusAndString( + net::HttpStatusCode status_code, + const std::string& response_body) { + net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); + ASSERT_TRUE(fetcher); + fetcher->set_response_code(status_code); + fetcher->SetResponseString(response_body); +} + +void RegistrationRequestTest::CompleteFetch() { + registration_id_ = kNoRegistrationIdReturned; + net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); + ASSERT_TRUE(fetcher); + fetcher->delegate()->OnURLFetchComplete(fetcher); +} + +TEST_F(RegistrationRequestTest, RequestDataPassedToFetcher) { + CreateRequest(kDeveloperId); + request_->Start(); + + // Get data sent by request. + net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); + ASSERT_TRUE(fetcher); + + // Verify that authorization header was put together properly. + net::HttpRequestHeaders headers; + fetcher->GetExtraRequestHeaders(&headers); + std::string auth_header; + headers.GetHeader(net::HttpRequestHeaders::kAuthorization, &auth_header); + base::StringTokenizer auth_tokenizer(auth_header, " :"); + ASSERT_TRUE(auth_tokenizer.GetNext()); + EXPECT_EQ(kLoginHeader, auth_tokenizer.token()); + ASSERT_TRUE(auth_tokenizer.GetNext()); + EXPECT_EQ(base::Uint64ToString(kAndroidId), auth_tokenizer.token()); + ASSERT_TRUE(auth_tokenizer.GetNext()); + EXPECT_EQ(base::Uint64ToString(kSecurityToken), auth_tokenizer.token()); + + std::map<std::string, std::string> expected_pairs; + expected_pairs["app"] = kAppId; + expected_pairs["sender"] = kDeveloperId; + expected_pairs["cert"] = kCert; + expected_pairs["device"] = base::Uint64ToString(kAndroidId); + expected_pairs["device_user_id"] = base::Int64ToString(kUserSerialNumber); + expected_pairs["X-GOOG.USER_AID"] = base::Uint64ToString(kUserAndroidId); + + // Verify data was formatted properly. + std::string upload_data = fetcher->upload_data(); + base::StringTokenizer data_tokenizer(upload_data, "&="); + while (data_tokenizer.GetNext()) { + std::map<std::string, std::string>::iterator iter = + expected_pairs.find(data_tokenizer.token()); + ASSERT_TRUE(iter != expected_pairs.end()); + ASSERT_TRUE(data_tokenizer.GetNext()); + EXPECT_EQ(iter->second, data_tokenizer.token()); + // Ensure that none of the keys appears twice. + expected_pairs.erase(iter); + } + + EXPECT_EQ(0UL, expected_pairs.size()); +} + +TEST_F(RegistrationRequestTest, RequestRegistrationWithMultipleSenderIds) { + CreateRequest("sender1,sender2"); + request_->Start(); + + net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); + ASSERT_TRUE(fetcher); + + // Verify data was formatted properly. + std::string upload_data = fetcher->upload_data(); + base::StringTokenizer data_tokenizer(upload_data, "&="); + + // Skip all tokens until you hit entry for senders. + while (data_tokenizer.GetNext() && data_tokenizer.token() != "sender") + continue; + + ASSERT_TRUE(data_tokenizer.GetNext()); + std::string senders(data_tokenizer.token()); + base::StringTokenizer sender_tokenizer(senders, ","); + ASSERT_TRUE(sender_tokenizer.GetNext()); + EXPECT_EQ("sender1", sender_tokenizer.token()); + ASSERT_TRUE(sender_tokenizer.GetNext()); + EXPECT_EQ("sender2", sender_tokenizer.token()); +} + +TEST_F(RegistrationRequestTest, ResponseParsing) { + CreateRequest("sender1,sender2"); + request_->Start(); + + SetResponseStatusAndString(net::HTTP_OK, "token=2501"); + CompleteFetch(); + + EXPECT_EQ("2501", registration_id_); +} + +TEST_F(RegistrationRequestTest, ResponseHttpStatusNotOK) { + CreateRequest("sender1,sender2"); + request_->Start(); + + SetResponseStatusAndString(net::HTTP_UNAUTHORIZED, "token=2501"); + CompleteFetch(); + + EXPECT_EQ("", registration_id_); +} + +TEST_F(RegistrationRequestTest, ResponseMissingRegistrationId) { + CreateRequest("sender1,sender2"); + request_->Start(); + + SetResponseStatusAndString(net::HTTP_OK, ""); + CompleteFetch(); + + EXPECT_EQ("", registration_id_); + + CreateRequest("sender1,sender2"); + request_->Start(); + + SetResponseStatusAndString(net::HTTP_OK, "some error in response"); + CompleteFetch(); + + EXPECT_EQ("", registration_id_); +} + +} // namespace gcm diff --git a/google_apis/gcm/gcm.gyp b/google_apis/gcm/gcm.gyp index bff7c49..ad4989a 100644 --- a/google_apis/gcm/gcm.gyp +++ b/google_apis/gcm/gcm.gyp @@ -62,6 +62,8 @@ 'engine/heartbeat_manager.h', 'engine/mcs_client.cc', 'engine/mcs_client.h', + 'engine/registration_request.cc', + 'engine/registration_request.h', 'gcm_client.cc', 'gcm_client.h', 'gcm_client_impl.cc', @@ -130,6 +132,7 @@ 'engine/gcm_store_impl_unittest.cc', 'engine/heartbeat_manager_unittest.cc', 'engine/mcs_client_unittest.cc', + 'engine/registration_request_unittest.cc', ] }, ], |