File: auth_session_request_browsertest.mm

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 (437 lines) | stat: -rw-r--r-- 16,190 bytes parent folder | download | duplicates (6)
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/app_controller_mac.h"

#include "base/apple/foundation_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_test_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/profiles/profile_picker.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/prefs/pref_service.h"
#include "content/public/test/browser_test.h"
#include "net/base/apple/url_conversions.h"
#include "net/http/http_status_code.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_response.h"
#include "testing/gtest_mac.h"
#include "ui/base/page_transition_types.h"

namespace {

Profile& CreateAndWaitForProfile(const base::FilePath& profile_dir) {
  Profile& profile = profiles::testing::CreateProfileSync(
      g_browser_process->profile_manager(), profile_dir);
  return profile;
}

Profile& CreateAndWaitForGuestProfile() {
  return CreateAndWaitForProfile(ProfileManager::GetGuestProfilePath());
}

void SetGuestProfileAsLastProfile() {
  AppController* app_controller = AppController.sharedController;
  // Create the guest profile, and set it as the last used profile.
  Profile& guest_profile = CreateAndWaitForGuestProfile();
  [app_controller setLastProfile:&guest_profile];
  Profile* profile = [app_controller lastProfileIfLoaded];
  ASSERT_TRUE(profile);
  EXPECT_EQ(guest_profile.GetPath(), profile->GetPath());
  EXPECT_TRUE(profile->IsGuestSession());
  // Also set the last used profile path preference. If the profile does need to
  // be read from disk for some reason this acts as a backstop.
  g_browser_process->local_state()->SetString(
      prefs::kProfileLastUsed, guest_profile.GetPath().BaseName().value());
}

}  // namespace

using AuthSessionBrowserTest = InProcessBrowserTest;

@interface MockASWebAuthenticationSessionRequest : NSObject {
  NSUUID* __strong _uuid;
  NSURL* __strong _initialURL;

  NSURL* __strong _callbackURL;
  NSError* __strong _cancellationError;
}

// ASWebAuthenticationSessionRequest:

@property(readonly, nonatomic) NSURL* URL;
@property(readonly, nonatomic) BOOL shouldUseEphemeralSession;
@property(nullable, readonly, nonatomic, copy) NSString* callbackURLScheme;
@property(readonly, nonatomic) NSUUID* UUID;

- (void)completeWithCallbackURL:(NSURL*)url;
- (void)cancelWithError:(NSError*)error;

// Utilities:

@property(readonly, nonatomic) NSURL* callbackURL;
@property(readonly, nonatomic) NSError* cancellationError;

@end

@implementation MockASWebAuthenticationSessionRequest

- (instancetype)initWithInitialURL:(NSURL*)initialURL {
  if (self = [super init]) {
    _uuid = [[NSUUID alloc] init];
    _initialURL = initialURL;
  }
  return self;
}

- (NSURL*)URL {
  return _initialURL;
}

- (BOOL)shouldUseEphemeralSession {
  return false;
}

- (NSString*)callbackURLScheme {
  // Use occasional capital letters to test the canonicalization of schemes.
  return @"mAkEiTsO";
}

- (NSUUID*)UUID {
  return _uuid;
}

- (void)completeWithCallbackURL:(NSURL*)url {
  _callbackURL = url;
}

- (void)cancelWithError:(NSError*)error {
  _cancellationError = error;
}

- (NSURL*)callbackURL {
  return _callbackURL;
}

- (NSError*)cancellationError {
  return _cancellationError;
}

@end

// Tests that an OS request to cancel an auth session works.
IN_PROC_BROWSER_TEST_F(AuthSessionBrowserTest, OSCancellation) {
  auto* browser_list = BrowserList::GetInstance();
  size_t start_browser_count = browser_list->size();

  MockASWebAuthenticationSessionRequest* session_request =
      [[MockASWebAuthenticationSessionRequest alloc]
          initWithInitialURL:[NSURL URLWithString:@"about:blank"]];
  id<ASWebAuthenticationSessionWebBrowserSessionHandling> session_handler =
      ASWebAuthenticationSessionWebBrowserSessionManager.sharedManager
          .sessionHandler;
  ASSERT_NE(nil, session_handler);

  // Ask the app controller to start handling our session request.

  id request = session_request;
  [session_handler beginHandlingWebAuthenticationSessionRequest:request];

  // Expect a browser window to be opened.

  Browser* browser = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_EQ(start_browser_count + 1, browser_list->size());

  // Ask the app controller to stop handling our session request.

  [session_handler cancelWebAuthenticationSessionRequest:request];

  // Expect the browser window to close.

  ui_test_utils::WaitForBrowserToClose(browser);
  EXPECT_EQ(start_browser_count, browser_list->size());

  // Expect there to have been the user cancellation callback.

  EXPECT_EQ(nil, session_request.callbackURL);
  ASSERT_NE(nil, session_request.cancellationError);
  EXPECT_EQ(ASWebAuthenticationSessionErrorDomain,
            session_request.cancellationError.domain);
  EXPECT_EQ(ASWebAuthenticationSessionErrorCodeCanceledLogin,
            session_request.cancellationError.code);
}

// Tests that a user request to cancel an auth session works.
IN_PROC_BROWSER_TEST_F(AuthSessionBrowserTest, UserCancellation) {
  auto* browser_list = BrowserList::GetInstance();
  size_t start_browser_count = browser_list->size();

  MockASWebAuthenticationSessionRequest* session_request =
      [[MockASWebAuthenticationSessionRequest alloc]
          initWithInitialURL:[NSURL URLWithString:@"about:blank"]];
  id<ASWebAuthenticationSessionWebBrowserSessionHandling> session_handler =
      ASWebAuthenticationSessionWebBrowserSessionManager.sharedManager
          .sessionHandler;
  ASSERT_NE(nil, session_handler);

  // Ask the app controller to start handling our session request.

  id request = session_request;
  [session_handler beginHandlingWebAuthenticationSessionRequest:request];

  // Expect a browser window to be opened.

  Browser* browser = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_EQ(start_browser_count + 1, browser_list->size());

  // Simulate the user closing the window.

  browser->window()->Close();

  // Expect the browser window to close.

  ui_test_utils::WaitForBrowserToClose(browser);
  EXPECT_EQ(start_browser_count, browser_list->size());

  // Expect there to have been the user cancellation callback.

  EXPECT_EQ(nil, session_request.callbackURL);
  ASSERT_NE(nil, session_request.cancellationError);
  EXPECT_EQ(ASWebAuthenticationSessionErrorDomain,
            session_request.cancellationError.domain);
  EXPECT_EQ(ASWebAuthenticationSessionErrorCodeCanceledLogin,
            session_request.cancellationError.code);
}

// Tests that the session works even if the profile is not already loaded.
IN_PROC_BROWSER_TEST_F(AuthSessionBrowserTest, ProfileNotLoaded) {
  auto* browser_list = BrowserList::GetInstance();
  size_t start_browser_count = browser_list->size();

  // Clear the last profile. It will be set by default since NSApp in browser
  // tests can activate.
  AppController* app_controller = AppController.sharedController;
  [app_controller setLastProfile:nullptr];

  // Use a profile that is not loaded yet.
  const std::string kProfileName = "Profile 2";
  g_browser_process->local_state()->SetString(prefs::kProfileLastUsed,
                                              kProfileName);
  const base::FilePath kProfilePath =
      browser()->profile()->GetPath().DirName().Append(kProfileName);
  ASSERT_FALSE(
      g_browser_process->profile_manager()->GetProfileByPath(kProfilePath));

  // Ask the app controller to start handling our session request.
  MockASWebAuthenticationSessionRequest* session_request =
      [[MockASWebAuthenticationSessionRequest alloc]
          initWithInitialURL:[NSURL URLWithString:@"about:blank"]];
  id<ASWebAuthenticationSessionWebBrowserSessionHandling> session_handler =
      ASWebAuthenticationSessionWebBrowserSessionManager.sharedManager
          .sessionHandler;
  ASSERT_NE(nil, session_handler);
  id request = session_request;
  [session_handler beginHandlingWebAuthenticationSessionRequest:request];

  // Expect the profile to be loaded and browser window to be opened.
  Browser* browser = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_TRUE(
      g_browser_process->profile_manager()->GetProfileByPath(kProfilePath));
  EXPECT_EQ(start_browser_count + 1, browser_list->size());
  EXPECT_EQ(browser->profile()->GetPath(), kProfilePath);
}

// Tests that the profile picker is shown instead if the profile is unavailable.
IN_PROC_BROWSER_TEST_F(AuthSessionBrowserTest, ProfileNotAvailable) {
  auto* browser_list = BrowserList::GetInstance();
  size_t start_browser_count = browser_list->size();

  // Use the guest profile, but mark it as disallowed.
  SetGuestProfileAsLastProfile();
  PrefService* local_state = g_browser_process->local_state();
  local_state->SetBoolean(prefs::kBrowserGuestModeEnabled, false);

  // The profile picker is initially closed.
  base::RunLoop run_loop;
  ProfilePicker::AddOnProfilePickerOpenedCallbackForTesting(
      run_loop.QuitClosure());
  ASSERT_FALSE(ProfilePicker::IsOpen());

  // Ask the app controller to start handling our session request.
  MockASWebAuthenticationSessionRequest* session_request =
      [[MockASWebAuthenticationSessionRequest alloc]
          initWithInitialURL:[NSURL URLWithString:@"about:blank"]];
  id<ASWebAuthenticationSessionWebBrowserSessionHandling> session_handler =
      ASWebAuthenticationSessionWebBrowserSessionManager.sharedManager
          .sessionHandler;
  ASSERT_NE(nil, session_handler);
  id request = session_request;
  [session_handler beginHandlingWebAuthenticationSessionRequest:request];

  // Expect the profile picker to be opened, no browser was created, and the
  // session was cancelled.
  run_loop.Run();
  EXPECT_TRUE(ProfilePicker::IsOpen());
  EXPECT_EQ(start_browser_count, browser_list->size());
  EXPECT_EQ(nil, session_request.callbackURL);
  ASSERT_NE(nil, session_request.cancellationError);
  EXPECT_EQ(ASWebAuthenticationSessionErrorDomain,
            session_request.cancellationError.domain);
  EXPECT_EQ(ASWebAuthenticationSessionErrorCodePresentationContextInvalid,
            session_request.cancellationError.code);
}

// Tests that a successful auth session works via direct navigation.
IN_PROC_BROWSER_TEST_F(AuthSessionBrowserTest, UserSuccessDirect) {
  auto* browser_list = BrowserList::GetInstance();
  size_t start_browser_count = browser_list->size();

  MockASWebAuthenticationSessionRequest* session_request =
      [[MockASWebAuthenticationSessionRequest alloc]
          initWithInitialURL:[NSURL URLWithString:@"about:blank"]];
  id<ASWebAuthenticationSessionWebBrowserSessionHandling> session_handler =
      ASWebAuthenticationSessionWebBrowserSessionManager.sharedManager
          .sessionHandler;
  ASSERT_NE(nil, session_handler);

  // Ask the app controller to start handling our session request.

  id request = session_request;
  [session_handler beginHandlingWebAuthenticationSessionRequest:request];

  // Expect a browser window to be opened.

  Browser* browser = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_EQ(start_browser_count + 1, browser_list->size());

  // Simulate the user successfully logging in with a non-redirected load of
  // a URL with the expected scheme.

  GURL success_url("makeitso://enterprise");
  browser->tab_strip_model()->GetWebContentsAt(0)->GetController().LoadURL(
      success_url, content::Referrer(), ui::PAGE_TRANSITION_GENERATED,
      std::string());

  // Expect the browser window to close.

  ui_test_utils::WaitForBrowserToClose(browser);
  EXPECT_EQ(start_browser_count, browser_list->size());

  // Expect there to have been the success callback.

  ASSERT_NE(nil, session_request.callbackURL);
  EXPECT_EQ(nil, session_request.cancellationError);
  EXPECT_NSEQ(net::NSURLWithGURL(success_url), session_request.callbackURL);
}

namespace {

std::unique_ptr<net::test_server::HttpResponse> RedirectionRequestHandler(
    const GURL& redirection_url,
    const net::test_server::HttpRequest& request) {
  auto http_response = std::make_unique<net::test_server::BasicHttpResponse>();
  http_response->set_code(net::HTTP_FOUND);
  http_response->AddCustomHeader("Location", redirection_url.spec());
  return http_response;
}

}  // namespace

// Tests that a successful auth session works via a redirect.
IN_PROC_BROWSER_TEST_F(AuthSessionBrowserTest, UserSuccessEventualRedirect) {
  GURL success_url("makeitso://cerritos");

  net::EmbeddedTestServer embedded_test_server;
  embedded_test_server.RegisterRequestHandler(
      base::BindRepeating(RedirectionRequestHandler, success_url));
  ASSERT_TRUE(embedded_test_server.Start());

  auto* browser_list = BrowserList::GetInstance();
  size_t start_browser_count = browser_list->size();

  MockASWebAuthenticationSessionRequest* session_request =
      [[MockASWebAuthenticationSessionRequest alloc]
          initWithInitialURL:[NSURL URLWithString:@"about:blank"]];
  id<ASWebAuthenticationSessionWebBrowserSessionHandling> session_handler =
      ASWebAuthenticationSessionWebBrowserSessionManager.sharedManager
          .sessionHandler;
  ASSERT_NE(nil, session_handler);

  // Ask the app controller to start handling our session request.

  id request = session_request;
  [session_handler beginHandlingWebAuthenticationSessionRequest:request];

  // Expect a browser window to be opened.

  Browser* browser = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_EQ(start_browser_count + 1, browser_list->size());

  // Simulate the user successfully logging in with a redirected load of a URL
  // with the expected scheme.

  GURL url = embedded_test_server.GetURL("/something");
  browser->tab_strip_model()->GetWebContentsAt(0)->GetController().LoadURL(
      url, content::Referrer(), ui::PAGE_TRANSITION_GENERATED, std::string());

  // Expect the browser window to close.

  ui_test_utils::WaitForBrowserToClose(browser);
  EXPECT_EQ(start_browser_count, browser_list->size());

  // Expect there to have been the success callback.

  ASSERT_NE(nil, session_request.callbackURL);
  EXPECT_EQ(nil, session_request.cancellationError);
  EXPECT_NSEQ(net::NSURLWithGURL(success_url), session_request.callbackURL);
}

// Tests that a successful auth session works if the success scheme comes on a
// redirect from the initial navigation.
IN_PROC_BROWSER_TEST_F(AuthSessionBrowserTest, UserSuccessInitialRedirect) {
  GURL success_url("makeitso://titan");

  net::EmbeddedTestServer embedded_test_server;
  embedded_test_server.RegisterRequestHandler(
      base::BindRepeating(RedirectionRequestHandler, success_url));
  ASSERT_TRUE(embedded_test_server.Start());

  auto* browser_list = BrowserList::GetInstance();
  size_t start_browser_count = browser_list->size();

  GURL url = embedded_test_server.GetURL("/something");
  MockASWebAuthenticationSessionRequest* session_request =
      [[MockASWebAuthenticationSessionRequest alloc]
          initWithInitialURL:net::NSURLWithGURL(url)];
  id<ASWebAuthenticationSessionWebBrowserSessionHandling> session_handler =
      ASWebAuthenticationSessionWebBrowserSessionManager.sharedManager
          .sessionHandler;
  ASSERT_NE(nil, session_handler);

  // Ask the app controller to start handling our session request.

  id request = session_request;
  [session_handler beginHandlingWebAuthenticationSessionRequest:request];

  // Expect a browser window to be opened.

  Browser* browser = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_EQ(start_browser_count + 1, browser_list->size());

  // Expect the browser window to close.

  ui_test_utils::WaitForBrowserToClose(browser);
  EXPECT_EQ(start_browser_count, browser_list->size());

  // Expect there to have been the success callback.

  ASSERT_NE(nil, session_request.callbackURL);
  EXPECT_EQ(nil, session_request.cancellationError);
  EXPECT_NSEQ(net::NSURLWithGURL(success_url), session_request.callbackURL);
}