Commit 813630fa authored by Owen Min's avatar Owen Min Committed by Commit Bot

Remove CBCM reporting extension API

chrome.enterprise.reportingPrivate.uploadChromeDesktopReport is a
deprecated extension API. There is no extension using this API anymore.

Delete its definition and implementation to cleanup the code.

Bug: 1107440
Change-Id: I76fed9d69e90ebeaf459f4533ac2bdba7b0334f0
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2343622Reviewed-by: default avatarJulian Pastarmov <pastarmovj@chromium.org>
Reviewed-by: default avatarKaran Bhatia <karandeepb@chromium.org>
Commit-Queue: Owen Min <zmin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#796672}
parent 5f8b257a
...@@ -12,29 +12,11 @@ ...@@ -12,29 +12,11 @@
#include "base/base64.h" #include "base/base64.h"
#include "base/base_paths.h" #include "base/base_paths.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/json/json_writer.h" #include "base/logging.h"
#include "base/lazy_instance.h"
#include "base/path_service.h" #include "base/path_service.h"
#include "base/rand_util.h" #include "base/rand_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/api/enterprise_reporting_private/prefs.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/policy/chrome_policy_conversions_client.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/pref_names.h"
#include "components/enterprise/browser/controller/browser_dm_token_storage.h" #include "components/enterprise/browser/controller/browser_dm_token_storage.h"
#include "components/policy/core/browser/policy_conversions.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/cloud_policy_util.h"
#include "components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/prefs/pref_service.h"
#include "components/version_info/channel.h"
#include "components/version_info/version_info.h"
#if defined(OS_WIN) #if defined(OS_WIN)
#include "base/win/registry.h" #include "base/win/registry.h"
...@@ -51,194 +33,9 @@ ...@@ -51,194 +33,9 @@
#include "crypto/apple_keychain.h" #include "crypto/apple_keychain.h"
#endif #endif
namespace em = enterprise_management;
namespace extensions { namespace extensions {
namespace { namespace {
// JSON keys in the extension arguments.
const char kBrowserReport[] = "browserReport";
const char kChromeUserProfileReport[] = "chromeUserProfileReport";
const char kChromeSignInUser[] = "chromeSignInUser";
const char kExtensionData[] = "extensionData";
const char kPlugins[] = "plugins";
const char kSafeBrowsingWarnings[] = "safeBrowsingWarnings";
const char kSafeBrowsingWarningsClickThrough[] =
"safeBrowsingWarningsClickThrough";
// JSON keys in the os_info field.
const char kOS[] = "os";
const char kOSArch[] = "arch";
const char kOSVersion[] = "os_version";
const char kDefaultDictionary[] = "{}";
const char kDefaultList[] = "[]";
enum Type {
LIST,
DICTIONARY,
};
std::string GetChromePath() {
base::FilePath path;
base::PathService::Get(base::DIR_EXE, &path);
return path.AsUTF8Unsafe();
}
std::string GetProfileId(const Profile* profile) {
return profile->GetOriginalProfile()->GetPath().AsUTF8Unsafe();
}
// Returns last policy fetch timestamp of machine level user cloud policy if
// it exists. Otherwise, returns zero.
int64_t GetMachineLevelUserCloudPolicyFetchTimestamp() {
policy::MachineLevelUserCloudPolicyManager* manager =
g_browser_process->browser_policy_connector()
->machine_level_user_cloud_policy_manager();
if (!manager || !manager->IsClientRegistered())
return 0;
return manager->core()->client()->last_policy_timestamp().ToJavaTime();
}
void AppendAdditionalBrowserInformation(em::ChromeDesktopReportRequest* request,
Profile* profile) {
const PrefService* prefs = profile->GetPrefs();
// Set Chrome version number
request->mutable_browser_report()->set_browser_version(
version_info::GetVersionNumber());
// Set Chrome channel
request->mutable_browser_report()->set_channel(
policy::ConvertToProtoChannel(chrome::GetChannel()));
// Add a new profile report if extension doesn't report any profile.
if (request->browser_report().chrome_user_profile_reports_size() == 0)
request->mutable_browser_report()->add_chrome_user_profile_reports();
DCHECK_EQ(1, request->browser_report().chrome_user_profile_reports_size());
// Set Chrome executable path
request->mutable_browser_report()->set_executable_path(GetChromePath());
// Set profile ID for the first profile.
request->mutable_browser_report()
->mutable_chrome_user_profile_reports(0)
->set_id(GetProfileId(profile));
// Set the profile name
request->mutable_browser_report()
->mutable_chrome_user_profile_reports(0)
->set_name(prefs->GetString(prefs::kProfileName));
if (prefs->GetBoolean(enterprise_reporting::kReportPolicyData)) {
// Set policy data of the first profile. Extension will report this data in
// the future.
auto client =
std::make_unique<policy::ChromePolicyConversionsClient>(profile);
request->mutable_browser_report()
->mutable_chrome_user_profile_reports(0)
->set_policy_data(policy::DictionaryPolicyConversions(std::move(client))
.EnablePrettyPrint(false)
.ToJSON());
int64_t timestamp = GetMachineLevelUserCloudPolicyFetchTimestamp();
if (timestamp > 0) {
request->mutable_browser_report()
->mutable_chrome_user_profile_reports(0)
->set_policy_fetched_timestamp(timestamp);
}
}
}
bool UpdateJSONEncodedStringEntry(const base::Value& dict_value,
const char key[],
std::string* entry,
const Type type) {
if (const base::Value* value = dict_value.FindKey(key)) {
if ((type == DICTIONARY && !value->is_dict()) ||
(type == LIST && !value->is_list())) {
return false;
}
base::JSONWriter::Write(*value, entry);
} else {
if (type == DICTIONARY)
*entry = kDefaultDictionary;
else if (type == LIST)
*entry = kDefaultList;
}
return true;
}
void AppendPlatformInformation(em::ChromeDesktopReportRequest* request,
const PrefService* prefs) {
base::Value os_info = base::Value(base::Value::Type::DICTIONARY);
os_info.SetKey(kOS, base::Value(policy::GetOSPlatform()));
os_info.SetKey(kOSVersion, base::Value(policy::GetOSVersion()));
os_info.SetKey(kOSArch, base::Value(policy::GetOSArchitecture()));
base::JSONWriter::Write(os_info, request->mutable_os_info());
const char kComputerName[] = "computername";
base::Value machine_name = base::Value(base::Value::Type::DICTIONARY);
machine_name.SetKey(kComputerName, base::Value(policy::GetMachineName()));
base::JSONWriter::Write(machine_name, request->mutable_machine_name());
const char kUsername[] = "username";
base::Value os_user = base::Value(base::Value::Type::DICTIONARY);
os_user.SetKey(kUsername, base::Value(policy::GetOSUsername()));
base::JSONWriter::Write(os_user, request->mutable_os_user());
#if defined(OS_WIN)
request->set_serial_number(
policy::BrowserDMTokenStorage::Get()->RetrieveSerialNumber());
#endif
}
std::unique_ptr<em::ChromeUserProfileReport>
GenerateChromeUserProfileReportRequest(const base::Value& profile_report,
const PrefService* prefs) {
if (!profile_report.is_dict())
return nullptr;
std::unique_ptr<em::ChromeUserProfileReport> request =
std::make_unique<em::ChromeUserProfileReport>();
if (!UpdateJSONEncodedStringEntry(profile_report, kChromeSignInUser,
request->mutable_chrome_signed_in_user(),
DICTIONARY)) {
return nullptr;
}
if (prefs->GetBoolean(
enterprise_reporting::kReportExtensionsAndPluginsData)) {
if (!UpdateJSONEncodedStringEntry(profile_report, kExtensionData,
request->mutable_extension_data(),
LIST) ||
!UpdateJSONEncodedStringEntry(profile_report, kPlugins,
request->mutable_plugins(), LIST)) {
return nullptr;
}
}
if (prefs->GetBoolean(enterprise_reporting::kReportSafeBrowsingData)) {
if (const base::Value* count =
profile_report.FindKey(kSafeBrowsingWarnings)) {
if (!count->is_int())
return nullptr;
request->set_safe_browsing_warnings(count->GetInt());
}
if (const base::Value* count =
profile_report.FindKey(kSafeBrowsingWarningsClickThrough)) {
if (!count->is_int())
return nullptr;
request->set_safe_browsing_warnings_click_through(count->GetInt());
}
}
return request;
}
#if defined(OS_WIN) #if defined(OS_WIN)
const wchar_t kDefaultRegistryPath[] = const wchar_t kDefaultRegistryPath[] =
L"SOFTWARE\\Google\\Endpoint Verification"; L"SOFTWARE\\Google\\Endpoint Verification";
...@@ -429,40 +226,6 @@ base::FilePath GetEndpointVerificationDir() { ...@@ -429,40 +226,6 @@ base::FilePath GetEndpointVerificationDir() {
} // namespace } // namespace
std::unique_ptr<em::ChromeDesktopReportRequest>
GenerateChromeDesktopReportRequest(const base::DictionaryValue& report,
Profile* profile) {
std::unique_ptr<em::ChromeDesktopReportRequest> request =
std::make_unique<em::ChromeDesktopReportRequest>();
const PrefService* prefs = profile->GetPrefs();
AppendPlatformInformation(request.get(), prefs);
if (const base::Value* browser_report =
report.FindKeyOfType(kBrowserReport, base::Value::Type::DICTIONARY)) {
if (const base::Value* profile_reports = browser_report->FindKeyOfType(
kChromeUserProfileReport, base::Value::Type::LIST)) {
if (!profile_reports->GetList().empty()) {
DCHECK_EQ(1u, profile_reports->GetList().size());
// Currently, profile send their browser reports individually.
std::unique_ptr<em::ChromeUserProfileReport> profile_report_request =
GenerateChromeUserProfileReportRequest(
profile_reports->GetList()[0], prefs);
if (!profile_report_request)
return nullptr;
request->mutable_browser_report()
->mutable_chrome_user_profile_reports()
->AddAllocated(profile_report_request.release());
}
}
}
AppendAdditionalBrowserInformation(request.get(), profile);
return request;
}
// Sets the path used to store Endpoint Verification data for tests. // Sets the path used to store Endpoint Verification data for tests.
void OverrideEndpointVerificationDirForTesting(const base::FilePath& path) { void OverrideEndpointVerificationDirForTesting(const base::FilePath& path) {
*GetEndpointVerificationDirOverride() = path; *GetEndpointVerificationDirOverride() = path;
......
...@@ -11,13 +11,6 @@ ...@@ -11,13 +11,6 @@
#include "base/callback.h" #include "base/callback.h"
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "components/policy/proto/device_management_backend.pb.h"
class Profile;
namespace base {
class DictionaryValue;
} // namespace base
namespace extensions { namespace extensions {
...@@ -33,12 +26,6 @@ enum class RetrieveDeviceDataStatus { ...@@ -33,12 +26,6 @@ enum class RetrieveDeviceDataStatus {
kDataRecordRetrievalError, kDataRecordRetrievalError,
}; };
// Transfer the input from Json file to protobuf. Return nullptr if the input
// is not valid.
std::unique_ptr<enterprise_management::ChromeDesktopReportRequest>
GenerateChromeDesktopReportRequest(const base::DictionaryValue& report,
Profile* profile);
// Override the path where Endpoint Verification data is stored for tests. // Override the path where Endpoint Verification data is stored for tests.
void OverrideEndpointVerificationDirForTesting(const base::FilePath& path); void OverrideEndpointVerificationDirForTesting(const base::FilePath& path);
......
...@@ -6,46 +6,20 @@ ...@@ -6,46 +6,20 @@
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <vector>
#include "base/bind.h" #include "base/bind.h"
#include "base/json/json_writer.h" #include "base/strings/stringprintf.h"
#include "base/location.h"
#include "base/task/post_task.h" #include "base/task/post_task.h"
#include "base/task/thread_pool.h" #include "base/task/thread_pool.h"
#include "base/values.h" #include "base/values.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/api/enterprise_reporting_private/device_info_fetcher.h" #include "chrome/browser/extensions/api/enterprise_reporting_private/device_info_fetcher.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "components/enterprise/browser/controller/browser_dm_token_storage.h" #include "components/enterprise/browser/controller/browser_dm_token_storage.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/device_management_service.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace em = enterprise_management;
namespace extensions { namespace extensions {
namespace {
void LogReportError(const std::string& reason) {
VLOG(1) << "Enterprise report is not uploaded: " << reason;
}
void LogReportErrorCode(const std::string& reason, long int code) {
VLOG(1) << "Enterprise report is not uploaded: " << reason
<< " code: " << code;
}
} // namespace
namespace enterprise_reporting { namespace enterprise_reporting {
const char kInvalidInputErrorMessage[] = "The report is not valid.";
const char kUploadFailed[] = "Failed to upload the report.";
const char kDeviceNotEnrolled[] = "This device has not been enrolled yet.";
const char kDeviceIdNotFound[] = "Failed to retrieve the device id."; const char kDeviceIdNotFound[] = "Failed to retrieve the device id.";
const char kEndpointVerificationRetrievalFailed[] = const char kEndpointVerificationRetrievalFailed[] =
"Failed to retrieve the endpoint verification data."; "Failed to retrieve the endpoint verification data.";
...@@ -55,105 +29,6 @@ const char kEndpointVerificationSecretRetrievalFailed[] = "%ld"; ...@@ -55,105 +29,6 @@ const char kEndpointVerificationSecretRetrievalFailed[] = "%ld";
} // namespace enterprise_reporting } // namespace enterprise_reporting
// UploadDesktopReport
EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
EnterpriseReportingPrivateUploadChromeDesktopReportFunction()
: EnterpriseReportingPrivateUploadChromeDesktopReportFunction(
g_browser_process->system_network_context_manager()
->GetSharedURLLoaderFactory()) {}
EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
EnterpriseReportingPrivateUploadChromeDesktopReportFunction(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
policy::DeviceManagementService* device_management_service =
g_browser_process->browser_policy_connector()
->device_management_service();
// Initial the DeviceManagementService if it exist and hasn't been initialized
if (device_management_service)
device_management_service->ScheduleInitialization(0);
cloud_policy_client_ = std::make_unique<policy::CloudPolicyClient>(
device_management_service, std::move(url_loader_factory),
policy::CloudPolicyClient::DeviceDMTokenCallback());
dm_token_ = policy::BrowserDMTokenStorage::Get()->RetrieveDMToken();
client_id_ = policy::BrowserDMTokenStorage::Get()->RetrieveClientId();
}
EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
~EnterpriseReportingPrivateUploadChromeDesktopReportFunction() {}
// static
EnterpriseReportingPrivateUploadChromeDesktopReportFunction*
EnterpriseReportingPrivateUploadChromeDesktopReportFunction::CreateForTesting(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
return new EnterpriseReportingPrivateUploadChromeDesktopReportFunction(
url_loader_factory);
}
ExtensionFunction::ResponseAction
EnterpriseReportingPrivateUploadChromeDesktopReportFunction::Run() {
VLOG(1) << "Uploading enterprise report";
if (!dm_token_.is_valid() || client_id_.empty()) {
LogReportError("Device is not enrolled.");
return RespondNow(Error(enterprise_reporting::kDeviceNotEnrolled));
}
std::unique_ptr<
api::enterprise_reporting_private::UploadChromeDesktopReport::Params>
params(api::enterprise_reporting_private::UploadChromeDesktopReport::
Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
std::unique_ptr<em::ChromeDesktopReportRequest> request =
GenerateChromeDesktopReportRequest(
params->report.additional_properties,
Profile::FromBrowserContext(browser_context()));
if (!request) {
LogReportError("The input from extension is not valid.");
return RespondNow(Error(enterprise_reporting::kInvalidInputErrorMessage));
}
if (!cloud_policy_client_->is_registered())
cloud_policy_client_->SetupRegistration(dm_token_.value(), client_id_,
std::vector<std::string>());
cloud_policy_client_->UploadChromeDesktopReport(
std::move(request),
base::BindOnce(
&EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
OnReportUploaded,
this));
return RespondLater();
}
void EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
SetCloudPolicyClientForTesting(
std::unique_ptr<policy::CloudPolicyClient> client) {
cloud_policy_client_ = std::move(client);
}
void EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
SetRegistrationInfoForTesting(const policy::DMToken& dm_token,
const std::string& client_id) {
dm_token_ = dm_token;
client_id_ = client_id;
}
void EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
OnReportUploaded(bool status) {
// Schedule to delete |cloud_policy_client_| later, as we'll be deleted right
// after calling Respond but |cloud_policy_client_| is not done yet.
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
FROM_HERE, cloud_policy_client_.release());
if (status) {
VLOG(1) << "The enterprise report has been uploaded.";
Respond(NoArguments());
} else {
LogReportError("Server error.");
Respond(Error(enterprise_reporting::kUploadFailed));
}
}
// GetDeviceId // GetDeviceId
EnterpriseReportingPrivateGetDeviceIdFunction:: EnterpriseReportingPrivateGetDeviceIdFunction::
...@@ -207,7 +82,7 @@ void EnterpriseReportingPrivateGetPersistentSecretFunction::OnDataRetrieved( ...@@ -207,7 +82,7 @@ void EnterpriseReportingPrivateGetPersistentSecretFunction::OnDataRetrieved(
reinterpret_cast<const uint8_t*>(data.data()), reinterpret_cast<const uint8_t*>(data.data()),
reinterpret_cast<const uint8_t*>(data.data() + data.size()))))); reinterpret_cast<const uint8_t*>(data.data() + data.size())))));
} else { } else {
LogReportErrorCode("Endpoint Verification secret retrieval error.", status); VLOG(1) << "Endpoint Verification secret retrieval error: " << status;
Respond(Error(base::StringPrintf( Respond(Error(base::StringPrintf(
enterprise_reporting::kEndpointVerificationSecretRetrievalFailed, enterprise_reporting::kEndpointVerificationSecretRetrievalFailed,
static_cast<long int>(status)))); static_cast<long int>(status))));
...@@ -254,8 +129,8 @@ void EnterpriseReportingPrivateGetDeviceDataFunction::OnDataRetrieved( ...@@ -254,8 +129,8 @@ void EnterpriseReportingPrivateGetDeviceDataFunction::OnDataRetrieved(
Respond(NoArguments()); Respond(NoArguments());
return; return;
default: default:
LogReportErrorCode("Endpoint Verification data retrieval error.", VLOG(1) << "Endpoint Verification data retrieval error: "
static_cast<long int>(status)); << static_cast<long int>(status);
Respond( Respond(
Error(enterprise_reporting::kEndpointVerificationRetrievalFailed)); Error(enterprise_reporting::kEndpointVerificationRetrievalFailed));
} }
...@@ -291,7 +166,7 @@ void EnterpriseReportingPrivateSetDeviceDataFunction::OnDataStored( ...@@ -291,7 +166,7 @@ void EnterpriseReportingPrivateSetDeviceDataFunction::OnDataStored(
VLOG(1) << "The Endpoint Verification data was stored."; VLOG(1) << "The Endpoint Verification data was stored.";
Respond(NoArguments()); Respond(NoArguments());
} else { } else {
LogReportError("Endpoint Verification data storage error."); VLOG(1) << "Endpoint Verification data storage error.";
Respond(Error(enterprise_reporting::kEndpointVerificationStoreFailed)); Respond(Error(enterprise_reporting::kEndpointVerificationStoreFailed));
} }
} }
......
...@@ -8,68 +8,17 @@ ...@@ -8,68 +8,17 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include "base/memory/ref_counted.h"
#include "chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h" #include "chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h"
#include "chrome/common/extensions/api/enterprise_reporting_private.h" #include "chrome/common/extensions/api/enterprise_reporting_private.h"
#include "components/policy/core/common/cloud/dm_token.h"
#include "extensions/browser/extension_function.h" #include "extensions/browser/extension_function.h"
namespace policy {
class CloudPolicyClient;
}
namespace network {
class SharedURLLoaderFactory;
}
namespace extensions { namespace extensions {
namespace enterprise_reporting { namespace enterprise_reporting {
extern const char kInvalidInputErrorMessage[];
extern const char kUploadFailed[];
extern const char kDeviceNotEnrolled[];
extern const char kDeviceIdNotFound[]; extern const char kDeviceIdNotFound[];
} // namespace enterprise_reporting } // namespace enterprise_reporting
class EnterpriseReportingPrivateUploadChromeDesktopReportFunction
: public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION(
"enterprise.reportingPrivate.uploadChromeDesktopReport",
ENTERPRISEREPORTINGPRIVATE_UPLOADCHROMEDESKTOPREPORT)
EnterpriseReportingPrivateUploadChromeDesktopReportFunction();
// ExtensionFunction
ExtensionFunction::ResponseAction Run() override;
void SetCloudPolicyClientForTesting(
std::unique_ptr<policy::CloudPolicyClient> client);
void SetRegistrationInfoForTesting(const policy::DMToken& dm_token,
const std::string& client_id);
// Used by tests that want to overrode the URLLoaderFactory used to simulate
// network requests.
static EnterpriseReportingPrivateUploadChromeDesktopReportFunction*
CreateForTesting(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);
private:
explicit EnterpriseReportingPrivateUploadChromeDesktopReportFunction(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);
~EnterpriseReportingPrivateUploadChromeDesktopReportFunction() override;
// Callback once Chrome get the response from the DM Server.
void OnReportUploaded(bool status);
std::unique_ptr<policy::CloudPolicyClient> cloud_policy_client_;
policy::DMToken dm_token_;
std::string client_id_;
DISALLOW_COPY_AND_ASSIGN(
EnterpriseReportingPrivateUploadChromeDesktopReportFunction);
};
class EnterpriseReportingPrivateGetDeviceIdFunction : public ExtensionFunction { class EnterpriseReportingPrivateGetDeviceIdFunction : public ExtensionFunction {
public: public:
......
...@@ -4,131 +4,30 @@ ...@@ -4,131 +4,30 @@
#include "chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h" #include "chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h"
#include "base/bind.h"
#include "base/files/scoped_temp_dir.h" #include "base/files/scoped_temp_dir.h"
#include "base/macros.h" #include "base/macros.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h" #include "chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h"
#include "chrome/browser/extensions/extension_api_unittest.h" #include "chrome/browser/extensions/extension_api_unittest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/common/extensions/api/enterprise_reporting_private.h" #include "chrome/common/extensions/api/enterprise_reporting_private.h"
#include "components/enterprise/browser/controller/fake_browser_dm_token_storage.h" #include "components/enterprise/browser/controller/fake_browser_dm_token_storage.h"
#include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "testing/gtest/include/gtest/gtest.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#if defined(OS_WIN) #if defined(OS_WIN)
#include "base/test/test_reg_util_win.h" #include "base/test/test_reg_util_win.h"
#endif #endif
using ::testing::_;
using ::testing::Invoke;
using ::testing::WithArgs;
namespace enterprise_reporting_private = namespace enterprise_reporting_private =
::extensions::api::enterprise_reporting_private; ::extensions::api::enterprise_reporting_private;
namespace extensions { namespace extensions {
namespace { namespace {
const char kFakeDMToken[] = "fake-dm-token";
const char kFakeClientId[] = "fake-client-id"; const char kFakeClientId[] = "fake-client-id";
const char kFakeMachineNameReport[] = "{\"computername\":\"name\"}";
} // namespace } // namespace
// Test for API enterprise.reportingPrivate.uploadChromeDesktopReport
class EnterpriseReportingPrivateUploadChromeDesktopReportTest
: public ExtensionApiUnittest {
public:
EnterpriseReportingPrivateUploadChromeDesktopReportTest() {}
ExtensionFunction* CreateChromeDesktopReportingFunction(
const std::string& dm_token) {
EnterpriseReportingPrivateUploadChromeDesktopReportFunction* function =
EnterpriseReportingPrivateUploadChromeDesktopReportFunction::
CreateForTesting(test_url_loader_factory_.GetSafeWeakWrapper());
auto client = std::make_unique<policy::MockCloudPolicyClient>(
test_url_loader_factory_.GetSafeWeakWrapper());
client_ = client.get();
function->SetCloudPolicyClientForTesting(std::move(client));
if (dm_token.empty()) {
function->SetRegistrationInfoForTesting(
policy::DMToken::CreateEmptyTokenForTesting(), kFakeClientId);
} else {
function->SetRegistrationInfoForTesting(
policy::DMToken::CreateValidTokenForTesting(dm_token), kFakeClientId);
}
return function;
}
std::string GenerateArgs(const char* name) {
return base::StringPrintf("[{\"machineName\":%s}]", name);
}
std::string GenerateInvalidReport() {
// This report is invalid as the chromeSignInUser dictionary should not be
// wrapped in a list.
return std::string(
"[{\"browserReport\": "
"{\"chromeUserProfileReport\":[{\"chromeSignInUser\":\"Name\"}]}}]");
}
policy::MockCloudPolicyClient* client_;
private:
network::TestURLLoaderFactory test_url_loader_factory_;
policy::FakeBrowserDMTokenStorage storage_;
DISALLOW_COPY_AND_ASSIGN(
EnterpriseReportingPrivateUploadChromeDesktopReportTest);
};
TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest,
DeviceIsNotEnrolled) {
ASSERT_EQ(enterprise_reporting::kDeviceNotEnrolled,
RunFunctionAndReturnError(
CreateChromeDesktopReportingFunction(std::string()),
GenerateArgs(kFakeMachineNameReport)));
}
TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest,
ReportIsNotValid) {
ASSERT_EQ(enterprise_reporting::kInvalidInputErrorMessage,
RunFunctionAndReturnError(
CreateChromeDesktopReportingFunction(kFakeDMToken),
GenerateInvalidReport()));
}
TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, UploadFailed) {
ExtensionFunction* function =
CreateChromeDesktopReportingFunction(kFakeDMToken);
EXPECT_CALL(*client_, SetupRegistration(kFakeDMToken, kFakeClientId, _))
.Times(1);
EXPECT_CALL(*client_, UploadChromeDesktopReportProxy(_, _))
.WillOnce(WithArgs<1>(policy::ScheduleStatusCallback(false)));
ASSERT_EQ(enterprise_reporting::kUploadFailed,
RunFunctionAndReturnError(function,
GenerateArgs(kFakeMachineNameReport)));
::testing::Mock::VerifyAndClearExpectations(client_);
}
TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest,
UploadSucceeded) {
ExtensionFunction* function =
CreateChromeDesktopReportingFunction(kFakeDMToken);
EXPECT_CALL(*client_, SetupRegistration(kFakeDMToken, kFakeClientId, _))
.Times(1);
EXPECT_CALL(*client_, UploadChromeDesktopReportProxy(_, _))
.WillOnce(WithArgs<1>(policy::ScheduleStatusCallback(true)));
ASSERT_EQ(nullptr, RunFunctionAndReturnValue(
function, GenerateArgs(kFakeMachineNameReport)));
::testing::Mock::VerifyAndClearExpectations(client_);
}
// Test for API enterprise.reportingPrivate.getDeviceId // Test for API enterprise.reportingPrivate.getDeviceId
class EnterpriseReportingPrivateGetDeviceIdTest : public ExtensionApiUnittest { class EnterpriseReportingPrivateGetDeviceIdTest : public ExtensionApiUnittest {
public: public:
......
...@@ -38,13 +38,6 @@ namespace enterprise.reportingPrivate { ...@@ -38,13 +38,6 @@ namespace enterprise.reportingPrivate {
callback GetDeviceInfoCallback = void(DeviceInfo deviceInfo); callback GetDeviceInfoCallback = void(DeviceInfo deviceInfo);
interface Functions { interface Functions {
// Uploads the status of Chrome browser to the admin console by sending
// request to the DMServer. Sets $(ref:runtime.lastError) on failure.
static void uploadChromeDesktopReport(
object report,
optional DoneCallback callback);
// Gets the identity of device that Chrome browser is running on. The ID is // Gets the identity of device that Chrome browser is running on. The ID is
// retrieved from the local device and used by the Google admin console. // retrieved from the local device and used by the Google admin console.
static void getDeviceId(optional GetDeviceIdCallback callback); static void getDeviceId(optional GetDeviceIdCallback callback);
......
...@@ -5101,7 +5101,6 @@ test("unit_tests") { ...@@ -5101,7 +5101,6 @@ test("unit_tests") {
] ]
} else { } else {
sources += [ sources += [
"../browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc",
"../browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc", "../browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc",
"../browser/extensions/api/messaging/native_message_process_host_unittest.cc", "../browser/extensions/api/messaging/native_message_process_host_unittest.cc",
"../browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc", "../browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc",
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment