File: user_remote_commands_service_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (291 lines) | stat: -rw-r--r-- 11,753 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/enterprise/remote_commands/user_remote_commands_service.h"

#include <stdint.h>

#include <utility>

#include "base/command_line.h"
#include "base/memory/raw_ptr.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/enterprise/remote_commands/user_remote_commands_service_factory.h"
#include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/policy/cloud/cloud_policy_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "chrome/test/base/platform_browser_test.h"
#include "components/invalidation/impl/fake_invalidation_service.h"
#include "components/invalidation/invalidation_factory.h"
#include "components/invalidation/profile_invalidation_provider.h"
#include "components/invalidation/test_support/fake_invalidation_listener.h"
#include "components/policy/core/browser/cloud/user_policy_signin_service_base.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "components/policy/core/common/policy_switches.h"
#include "components/policy/core/common/remote_commands/remote_commands_constants.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/policy/test_support/embedded_policy_test_server.h"
#include "components/policy/test_support/policy_storage.h"
#include "components/policy/test_support/remote_commands_result_waiter.h"
#include "components/policy/test_support/remote_commands_state.h"
#include "components/policy/test_support/signature_provider.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::InvokeWithoutArgs;

namespace em = enterprise_management;

namespace enterprise_commands {

namespace {

constexpr char kTestUser[] = "test@example.com";
constexpr int kCommandId = 1;

struct FeaturesTestParam {
  std::vector<base::test::FeatureRef> enabled_features;
  std::vector<base::test::FeatureRef> disabled_features;
};

std::variant<std::unique_ptr<invalidation::InvalidationService>,
             std::unique_ptr<invalidation::InvalidationListener>>
CreateInvalidationServiceForProjectNumber(int64_t project_number,
                                          std::string /*log_prefix*/) {
  if (invalidation::IsInvalidationListenerSupported(project_number)) {
    return std::make_unique<invalidation::FakeInvalidationListener>(
        project_number);
  }

  return std::make_unique<invalidation::FakeInvalidationService>();
}

std::unique_ptr<KeyedService> BuildFakeProfileInvalidationProvider(
    content::BrowserContext* context) {
  Profile* profile = Profile::FromBrowserContext(context);
  return std::make_unique<invalidation::ProfileInvalidationProvider>(
      std::make_unique<invalidation::ProfileIdentityProvider>(
          IdentityManagerFactory::GetForProfile(profile)),
      base::BindRepeating(&CreateInvalidationServiceForProjectNumber));
}

}  // namespace

class UserRemoteCommandsServiceTest
    : public PlatformBrowserTest,
      public testing::WithParamInterface<FeaturesTestParam> {
 public:
  UserRemoteCommandsServiceTest() {
    scoped_feature_list_.InitWithFeatures(GetParam().enabled_features,
                                          GetParam().disabled_features);
  }
  ~UserRemoteCommandsServiceTest() override = default;

  void SetUpInProcessBrowserTestFixture() override {
    PlatformBrowserTest::SetUpOnMainThread();

    test_server_ = std::make_unique<policy::EmbeddedPolicyTestServer>();
    ASSERT_TRUE(test_server_->Start());

    test_server_->policy_storage()->add_managed_user("*");
    test_server_->policy_storage()->set_policy_user(kTestUser);
    test_server_->policy_storage()
        ->signature_provider()
        ->SetUniversalSigningKeys();

    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    command_line->AppendSwitchASCII(policy::switches::kDeviceManagementUrl,
                                    test_server_->GetServiceURL().spec());
    policy::ChromeBrowserPolicyConnector::EnableCommandLineSupportForTesting();
  }

  void CreatedBrowserMainParts(
      content::BrowserMainParts* browser_main_parts) override {
    PlatformBrowserTest::CreatedBrowserMainParts(browser_main_parts);
    invalidation::ProfileInvalidationProviderFactory::GetInstance()
        ->RegisterTestingFactory(
            base::BindRepeating(&BuildFakeProfileInvalidationProvider));
  }

  // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
  // the username to the UserCloudPolicyValidator.
  void CreateIdentityTestEnv() {
    identity_test_env_ = std::make_unique<signin::IdentityTestEnvironment>();
    identity_test_env_->MakePrimaryAccountAvailable(
        kTestUser, signin::ConsentLevel::kSync);
  }

  policy::UserCloudPolicyManager* InitCloudPolicyManager() {
    profile_ = chrome_test_utils::GetProfile(this);
    policy::UserCloudPolicyManager* policy_manager =
        profile()->GetUserCloudPolicyManager();
    policy_manager->Connect(
        g_browser_process->local_state(),
        std::make_unique<policy::CloudPolicyClient>(
            g_browser_process->browser_policy_connector()
                ->device_management_service(),
            g_browser_process->shared_url_loader_factory()));

    return policy_manager;
  }

  // Register the user with fake DM Server.
  void RegisterUser(policy::CloudPolicyClient* client) {
    base::test::TestFuture<void> registered_signal;
    policy::MockCloudPolicyClientObserver observer;
    EXPECT_CALL(observer, OnRegistrationStateChanged(_))
        .WillOnce(InvokeWithoutArgs(
            [&registered_signal]() { registered_signal.SetValue(); }));
    client->AddObserver(&observer);

    ASSERT_FALSE(client->is_registered());
    policy::CloudPolicyClient::RegistrationParameters parameters(
        em::DeviceRegisterRequest::BROWSER,
        em::DeviceRegisterRequest::FLAVOR_USER_REGISTRATION);
    client->Register(parameters, std::string(), "oauth_token_unused");
    EXPECT_TRUE(registered_signal.Wait());

    ::testing::Mock::VerifyAndClearExpectations(&observer);

    client->RemoveObserver(&observer);
    EXPECT_TRUE(client->is_registered());
  }

  // Remote command needs to verify the command with signing key and client id
  // that is received with policy fetch. Here as we skipped the policy fetch
  // in `SetUpOnMainThread`, those information are set directly.
  void SetUpFakePolicyData(policy::UserCloudPolicyManager* policy_manager) {
    auto* store = policy_manager->core()->store();
    auto fake_policy_data = std::make_unique<em::PolicyData>();
    fake_policy_data->set_device_id(
        policy_manager->core()->client()->client_id());
    fake_policy_data->set_cec_enabled(true);
    fake_policy_data->set_command_invalidation_topic("fake-topic");
    store->set_policy_data_for_testing(std::move(fake_policy_data));
    store->set_policy_signature_public_key_for_testing(
        test_server_->policy_storage()
            ->signature_provider()
            ->GetCurrentKey()
            ->public_key());
  }

  void SetUpOnMainThread() override {
    policy::BrowserPolicyConnector* connector =
        g_browser_process->browser_policy_connector();
    connector->ScheduleServiceInitialization(0);

    CreateIdentityTestEnv();

    policy::UserCloudPolicyManager* policy_manager = InitCloudPolicyManager();

    // Prevent auto policy fetch after register as we don't need to test that.
    policy_manager->core()->client()->RemoveObserver(
        policy_manager->core()->refresh_scheduler());

    RegisterUser(policy_manager->core()->client());
    SetUpFakePolicyData(policy_manager);
  }

  void TearDownOnMainThread() override {
    identity_test_env_.reset();
    profile_ = nullptr;
  }

  invalidation::FakeInvalidationService* GetInvalidationServiceForProjectNumber(
      int64_t project_number) {
    auto* profile_invalidation_provider_factory =
        static_cast<invalidation::ProfileInvalidationProvider*>(
            invalidation::ProfileInvalidationProviderFactory::GetInstance()
                ->GetForProfile(profile()));
    auto invalidation_service_or_listener =
        profile_invalidation_provider_factory->GetInvalidationServiceOrListener(
            project_number);
    CHECK(std::holds_alternative<invalidation::InvalidationService*>(
        invalidation_service_or_listener));
    return static_cast<invalidation::FakeInvalidationService*>(
        std::get<invalidation::InvalidationService*>(
            invalidation_service_or_listener));
  }

  void AddPendingRemoteCommand(const em::RemoteCommand& command) {
    test_server_->remote_commands_state()->AddPendingRemoteCommand(command);
  }

  em::RemoteCommandResult WaitForResult(int command_id) {
    return policy::RemoteCommandsResultWaiter(
               test_server_->remote_commands_state(), command_id)
        .WaitAndGetResult();
  }

  Profile* profile() {
    return profile_;
  }

 private:
  raw_ptr<Profile> profile_;

  std::unique_ptr<policy::EmbeddedPolicyTestServer> test_server_;
  std::unique_ptr<signin::IdentityTestEnvironment> identity_test_env_;

  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_P(UserRemoteCommandsServiceTest, Success) {
  em::RemoteCommand command;
  command.set_type(em::RemoteCommand_Type_BROWSER_CLEAR_BROWSING_DATA);
  command.set_command_id(kCommandId);
  command.set_payload("{}");
  AddPendingRemoteCommand(command);

  // Initial the `RemoteCommandService`. In real life, this part is handled
  // by UserPolicySigninService which triggered by a real signin process.
  // The initialization will automatically pull pending commands in the end.
  auto* remote_command_service =
      enterprise_commands::UserRemoteCommandsServiceFactory::GetForProfile(
          profile());

  if (!base::FeatureList::IsEnabled(kUserRemoteCommands)) {
    ASSERT_FALSE(remote_command_service);
    return;
  }

  ASSERT_TRUE(remote_command_service);
  remote_command_service->Init();

  em::RemoteCommandResult result = WaitForResult(kCommandId);

  EXPECT_EQ(em::RemoteCommandResult_ResultType_RESULT_SUCCESS, result.result());
}

INSTANTIATE_TEST_SUITE_P(
    /* no prefix */,
    UserRemoteCommandsServiceTest,
    testing::Values(
        FeaturesTestParam{},
        FeaturesTestParam{
            .enabled_features = {
                policy::
                    kUserRemoteCommandsInvalidationWithDirectMessagesEnabled,
                kUserRemoteCommands}}));

}  // namespace enterprise_commands