Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(629)

Side by Side Diff: chrome/browser/chromeos/arc/arc_auth_service_browsertest.cc

Issue 2507073002: Split ArcSessionManager from ArcAuthService. (Closed)
Patch Set: Fix rebase mistake Created 4 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <memory>
6 #include <string>
7
8 #include "base/command_line.h"
9 #include "base/files/file_path.h"
10 #include "base/files/scoped_temp_dir.h"
11 #include "base/macros.h"
12 #include "base/memory/ptr_util.h"
13 #include "base/run_loop.h"
14 #include "base/time/time.h"
15 #include "chrome/browser/browser_process.h"
16 #include "chrome/browser/chromeos/arc/arc_auth_service.h"
17 #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h"
18 #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
19 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
20 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
21 #include "chrome/browser/policy/profile_policy_connector.h"
22 #include "chrome/browser/policy/profile_policy_connector_factory.h"
23 #include "chrome/browser/policy/test/local_policy_test_server.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
26 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
27 #include "chrome/browser/ui/ash/multi_user/multi_user_util.h"
28 #include "chrome/common/pref_names.h"
29 #include "chrome/test/base/in_process_browser_test.h"
30 #include "chrome/test/base/testing_profile.h"
31 #include "chromeos/chromeos_switches.h"
32 #include "chromeos/dbus/dbus_thread_manager.h"
33 #include "chromeos/dbus/fake_session_manager_client.h"
34 #include "chromeos/dbus/session_manager_client.h"
35 #include "components/arc/arc_bridge_service_impl.h"
36 #include "components/arc/arc_service_manager.h"
37 #include "components/arc/test/fake_arc_session.h"
38 #include "components/policy/core/common/cloud/device_management_service.h"
39 #include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
40 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
41 #include "components/policy/core/common/policy_switches.h"
42 #include "components/prefs/pref_member.h"
43 #include "components/prefs/pref_service.h"
44 #include "components/signin/core/account_id/account_id.h"
45 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
46 #include "components/user_manager/user_manager.h"
47 #include "content/public/browser/browser_thread.h"
48 #include "net/base/upload_bytes_element_reader.h"
49 #include "net/base/upload_data_stream.h"
50 #include "net/url_request/url_request_test_job.h"
51 #include "testing/gtest/include/gtest/gtest.h"
52 #include "url/gurl.h"
53
54 namespace {
55
56 constexpr char kRefreshToken[] = "fake-refresh-token";
57 // Set managed auth token for Android managed accounts.
58 constexpr char kManagedAuthToken[] = "managed-auth-token";
59 // Set unmanaged auth token for other Android unmanaged accounts.
60 constexpr char kUnmanagedAuthToken[] = "unmanaged-auth-token";
61 constexpr char kWellKnownConsumerName[] = "test@gmail.com";
62 constexpr char kFakeUserName[] = "test@example.com";
63 constexpr char kFakeAuthCode[] = "fake-auth-code";
64
65 // JobCallback for the interceptor.
66 net::URLRequestJob* ResponseJob(net::URLRequest* request,
67 net::NetworkDelegate* network_delegate) {
68 const net::UploadDataStream* upload = request->get_upload();
69 if (!upload || !upload->GetElementReaders() ||
70 upload->GetElementReaders()->size() != 1 ||
71 !(*upload->GetElementReaders())[0]->AsBytesReader())
72 return nullptr;
73
74 const net::UploadBytesElementReader* bytes_reader =
75 (*upload->GetElementReaders())[0]->AsBytesReader();
76
77 enterprise_management::DeviceManagementRequest parsed_request;
78 EXPECT_TRUE(parsed_request.ParseFromArray(bytes_reader->bytes(),
79 bytes_reader->length()));
80 // Check if auth code is requested.
81 EXPECT_TRUE(parsed_request.has_service_api_access_request());
82
83 enterprise_management::DeviceManagementResponse response;
84 response.mutable_service_api_access_response()->set_auth_code(kFakeAuthCode);
85
86 std::string response_data;
87 EXPECT_TRUE(response.SerializeToString(&response_data));
88
89 return new net::URLRequestTestJob(request, network_delegate,
90 net::URLRequestTestJob::test_headers(),
91 response_data, true);
92 }
93
94 class FakeAuthInstance : public arc::mojom::AuthInstance {
95 public:
96 void Init(arc::mojom::AuthHostPtr host_ptr) override {}
97 void OnAccountInfoReady(arc::mojom::AccountInfoPtr account_info) override {
98 ASSERT_FALSE(callback.is_null());
99 callback.Run(account_info);
100 }
101 base::Callback<void(const arc::mojom::AccountInfoPtr&)> callback;
102 };
103
104 } // namespace
105
106 namespace arc {
107
108 // Observer of ARC bridge shutdown.
109 class ArcAuthServiceShutdownObserver : public ArcAuthService::Observer {
110 public:
111 ArcAuthServiceShutdownObserver() { ArcAuthService::Get()->AddObserver(this); }
112
113 ~ArcAuthServiceShutdownObserver() override {
114 ArcAuthService::Get()->RemoveObserver(this);
115 }
116
117 void Wait() {
118 run_loop_.reset(new base::RunLoop);
119 run_loop_->Run();
120 run_loop_.reset();
121 }
122
123 // ArcAuthService::Observer:
124 void OnShutdownBridge() override {
125 if (!run_loop_)
126 return;
127 run_loop_->Quit();
128 }
129
130 private:
131 std::unique_ptr<base::RunLoop> run_loop_;
132
133 DISALLOW_COPY_AND_ASSIGN(ArcAuthServiceShutdownObserver);
134 };
135
136 class ArcAuthServiceTest : public InProcessBrowserTest {
137 protected:
138 ArcAuthServiceTest() {}
139
140 // InProcessBrowserTest:
141 ~ArcAuthServiceTest() override {}
142
143 void SetUpInProcessBrowserTestFixture() override {
144 // Start test device management server.
145 test_server_.reset(new policy::LocalPolicyTestServer());
146 ASSERT_TRUE(test_server_->Start());
147
148 // Specify device management server URL.
149 std::string url = test_server_->GetServiceURL().spec();
150 base::CommandLine* const command_line =
151 base::CommandLine::ForCurrentProcess();
152 command_line->AppendSwitchASCII(policy::switches::kDeviceManagementUrl,
153 url);
154
155 // Enable ARC.
156 command_line->AppendSwitch(chromeos::switches::kEnableArc);
157 chromeos::FakeSessionManagerClient* const fake_session_manager_client =
158 new chromeos::FakeSessionManagerClient;
159 fake_session_manager_client->set_arc_available(true);
160 chromeos::DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient(
161 std::unique_ptr<chromeos::SessionManagerClient>(
162 fake_session_manager_client));
163
164 // Mock out ARC bridge.
165 // Here inject FakeArcSession so blocking task runner is not needed.
166 auto service = base::MakeUnique<ArcBridgeServiceImpl>(nullptr);
167 service->SetArcSessionFactoryForTesting(base::Bind(FakeArcSession::Create));
168 ArcServiceManager::SetArcBridgeServiceForTesting(std::move(service));
169 }
170
171 void SetUpOnMainThread() override {
172 user_manager_enabler_.reset(new chromeos::ScopedUserManagerEnabler(
173 new chromeos::FakeChromeUserManager));
174 // Init ArcAuthService for testing.
175 ArcAuthService::DisableUIForTesting();
176 ArcAuthService::EnableCheckAndroidManagementForTesting();
177
178 EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
179
180 // Create test profile.
181 TestingProfile::Builder profile_builder;
182 profile_builder.SetPath(temp_dir_.GetPath().AppendASCII("TestArcProfile"));
183 profile_builder.SetProfileName(kFakeUserName);
184 profile_builder.AddTestingFactory(
185 ProfileOAuth2TokenServiceFactory::GetInstance(),
186 BuildFakeProfileOAuth2TokenService);
187 profile_ = profile_builder.Build();
188 token_service_ = static_cast<FakeProfileOAuth2TokenService*>(
189 ProfileOAuth2TokenServiceFactory::GetForProfile(profile()));
190 token_service_->UpdateCredentials("", kRefreshToken);
191
192 profile()->GetPrefs()->SetBoolean(prefs::kArcSignedIn, true);
193
194 const AccountId account_id(
195 AccountId::FromUserEmailGaiaId(kFakeUserName, "1234567890"));
196 GetFakeUserManager()->AddUser(account_id);
197 GetFakeUserManager()->LoginUser(account_id);
198
199 // Set up ARC for test profile.
200 std::unique_ptr<BooleanPrefMember> arc_enabled_pref =
201 base::MakeUnique<BooleanPrefMember>();
202 arc_enabled_pref->Init(prefs::kArcEnabled, profile()->GetPrefs());
203 ArcServiceManager::Get()->OnPrimaryUserProfilePrepared(
204 multi_user_util::GetAccountIdFromProfile(profile()),
205 std::move(arc_enabled_pref));
206 ArcAuthService::Get()->OnPrimaryUserProfilePrepared(profile());
207 }
208
209 void TearDownOnMainThread() override {
210 ArcAuthService::Get()->Shutdown();
211 ArcServiceManager::Get()->Shutdown();
212 profile_.reset();
213 user_manager_enabler_.reset();
214 test_server_.reset();
215 }
216
217 chromeos::FakeChromeUserManager* GetFakeUserManager() const {
218 return static_cast<chromeos::FakeChromeUserManager*>(
219 user_manager::UserManager::Get());
220 }
221
222 void set_profile_name(const std::string& username) {
223 profile_->set_profile_name(username);
224 }
225
226 Profile* profile() { return profile_.get(); }
227
228 FakeProfileOAuth2TokenService* token_service() { return token_service_; }
229
230 private:
231 std::unique_ptr<policy::LocalPolicyTestServer> test_server_;
232 std::unique_ptr<chromeos::ScopedUserManagerEnabler> user_manager_enabler_;
233 base::ScopedTempDir temp_dir_;
234 std::unique_ptr<TestingProfile> profile_;
235 FakeProfileOAuth2TokenService* token_service_;
236
237 DISALLOW_COPY_AND_ASSIGN(ArcAuthServiceTest);
238 };
239
240 IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, ConsumerAccount) {
241 PrefService* const prefs = profile()->GetPrefs();
242 prefs->SetBoolean(prefs::kArcEnabled, true);
243 token_service()->IssueTokenForAllPendingRequests(kUnmanagedAuthToken,
244 base::Time::Max());
245 ASSERT_EQ(ArcAuthService::State::ACTIVE, ArcAuthService::Get()->state());
246 }
247
248 IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, WellKnownConsumerAccount) {
249 set_profile_name(kWellKnownConsumerName);
250 PrefService* const prefs = profile()->GetPrefs();
251
252 prefs->SetBoolean(prefs::kArcEnabled, true);
253 ASSERT_EQ(ArcAuthService::State::ACTIVE, ArcAuthService::Get()->state());
254 }
255
256 IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, ManagedChromeAccount) {
257 policy::ProfilePolicyConnector* const connector =
258 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile());
259 connector->OverrideIsManagedForTesting(true);
260
261 PrefService* const pref = profile()->GetPrefs();
262
263 pref->SetBoolean(prefs::kArcEnabled, true);
264 ASSERT_EQ(ArcAuthService::State::ACTIVE, ArcAuthService::Get()->state());
265 }
266
267 IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, ManagedAndroidAccount) {
268 PrefService* const prefs = profile()->GetPrefs();
269
270 prefs->SetBoolean(prefs::kArcEnabled, true);
271 token_service()->IssueTokenForAllPendingRequests(kManagedAuthToken,
272 base::Time::Max());
273 ArcAuthServiceShutdownObserver observer;
274 observer.Wait();
275 ASSERT_EQ(ArcAuthService::State::STOPPED, ArcAuthService::Get()->state());
276 }
277
278 class KioskArcAuthServiceTest : public InProcessBrowserTest {
279 protected:
280 KioskArcAuthServiceTest() = default;
281
282 // InProcessBrowserTest:
283 ~KioskArcAuthServiceTest() override = default;
284
285 void SetUpCommandLine(base::CommandLine* command_line) override {
286 InProcessBrowserTest::SetUpCommandLine(command_line);
287 command_line->AppendSwitchASCII(policy::switches::kDeviceManagementUrl,
288 "http://localhost");
289 command_line->AppendSwitch(chromeos::switches::kEnableArc);
290 }
291
292 void SetUpOnMainThread() override {
293 interceptor_.reset(new policy::TestRequestInterceptor(
294 "localhost", content::BrowserThread::GetTaskRunnerForThread(
295 content::BrowserThread::IO)));
296
297 user_manager_enabler_.reset(new chromeos::ScopedUserManagerEnabler(
298 new chromeos::FakeChromeUserManager));
299
300 const AccountId account_id(AccountId::FromUserEmail(kFakeUserName));
301 GetFakeUserManager()->AddArcKioskAppUser(account_id);
302 GetFakeUserManager()->LoginUser(account_id);
303
304 policy::BrowserPolicyConnectorChromeOS* const connector =
305 g_browser_process->platform_part()->browser_policy_connector_chromeos();
306 policy::DeviceCloudPolicyManagerChromeOS* const cloud_policy_manager =
307 connector->GetDeviceCloudPolicyManager();
308
309 cloud_policy_manager->StartConnection(
310 base::MakeUnique<policy::MockCloudPolicyClient>(),
311 connector->GetInstallAttributes());
312
313 policy::MockCloudPolicyClient* const cloud_policy_client =
314 static_cast<policy::MockCloudPolicyClient*>(
315 cloud_policy_manager->core()->client());
316 cloud_policy_client->SetDMToken("fake-dm-token");
317 cloud_policy_client->client_id_ = "client-id";
318
319 ArcBridgeService::Get()->auth()->SetInstance(&auth_instance_);
320 }
321
322 void TearDownOnMainThread() override {
323 ArcBridgeService::Get()->auth()->SetInstance(nullptr);
324 ArcAuthService::Get()->Shutdown();
325 ArcServiceManager::Get()->Shutdown();
326 user_manager_enabler_.reset();
327
328 // Verify that all the expected requests were handled.
329 EXPECT_EQ(0u, interceptor_->GetPendingSize());
330 interceptor_.reset();
331 }
332
333 chromeos::FakeChromeUserManager* GetFakeUserManager() const {
334 return static_cast<chromeos::FakeChromeUserManager*>(
335 user_manager::UserManager::Get());
336 }
337
338 std::unique_ptr<policy::TestRequestInterceptor> interceptor_;
339 FakeAuthInstance auth_instance_;
340
341 private:
342 std::unique_ptr<chromeos::ScopedUserManagerEnabler> user_manager_enabler_;
343
344 DISALLOW_COPY_AND_ASSIGN(KioskArcAuthServiceTest);
345 };
346
347 IN_PROC_BROWSER_TEST_F(KioskArcAuthServiceTest, RequestAccountInfoSuccess) {
348 interceptor_->PushJobCallback(base::Bind(&ResponseJob));
349
350 auth_instance_.callback =
351 base::Bind([](const mojom::AccountInfoPtr& account_info) {
352 EXPECT_EQ(kFakeAuthCode, account_info->auth_code.value());
353 EXPECT_EQ(mojom::ChromeAccountType::ROBOT_ACCOUNT,
354 account_info->account_type);
355 EXPECT_FALSE(account_info->is_managed);
356 });
357
358 ArcAuthService::Get()->RequestAccountInfo();
359 base::RunLoop().RunUntilIdle();
360 }
361
362 IN_PROC_BROWSER_TEST_F(KioskArcAuthServiceTest, RequestAccountInfoError) {
363 interceptor_->PushJobCallback(
364 policy::TestRequestInterceptor::BadRequestJob());
365
366 auth_instance_.callback =
367 base::Bind([](const mojom::AccountInfoPtr&) { FAIL(); });
368
369 ArcAuthService::Get()->RequestAccountInfo();
370 // This MessageLoop will be stopped by AttemptUserExit(), that is called as
371 // a result of error of auth code fetching.
372 base::RunLoop().Run();
373 }
374
375 } // namespace arc
OLDNEW
« no previous file with comments | « chrome/browser/chromeos/arc/arc_auth_service.cc ('k') | chrome/browser/chromeos/arc/arc_auth_service_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698