File: supervised_user_navigation_observer_android_browsertest.cc

package info (click to toggle)
chromium 145.0.7632.159-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,976,224 kB
  • sloc: cpp: 36,198,469; ansic: 7,634,080; javascript: 3,564,060; python: 1,649,622; xml: 838,470; asm: 717,087; pascal: 185,708; sh: 88,786; perl: 88,718; objc: 79,984; sql: 59,811; cs: 42,452; fortran: 24,101; makefile: 21,144; tcl: 15,277; php: 14,022; yacc: 9,066; ruby: 7,553; awk: 3,720; lisp: 3,233; lex: 1,328; ada: 727; jsp: 228; sed: 36
file content (337 lines) | stat: -rw-r--r-- 15,055 bytes parent folder | download | duplicates (3)
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
// Copyright 2025 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/supervised_user/supervised_user_navigation_observer.h"

#include <memory>
#include <string_view>
#include <utility>

#include "base/check_deref.h"
#include "base/functional/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/global_features.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/supervised_user/supervised_user_browsertest_base.h"
#include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "components/google/core/common/google_switches.h"
#include "components/safe_search_api/url_checker_client.h"
#include "components/supervised_user/core/browser/android/android_parental_controls.h"
#include "components/supervised_user/core/browser/supervised_user_interstitial.h"
#include "components/supervised_user/core/browser/supervised_user_settings_service.h"
#include "components/supervised_user/core/common/features.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace supervised_user {
namespace {

using ::safe_search_api::ClientClassification;
using ::safe_search_api::URLCheckerClient;
using ::testing::_;

// Covers extra behaviors available only in Clank (Android). See supervised user
// navigation and throttle tests for general behavior.
class SupervisedUserNavigationObserverAndroidBrowserTest
    : public SupervisedUserBrowserTestBase {
 protected:
  content::WebContents* web_contents() {
    return chrome_test_utils::GetActiveWebContents(this);
  }

  base::HistogramTester& histogram_tester() { return histogram_tester_; }

 private:
  void SetUpOnMainThread() override {
    AndroidBrowserTest::SetUpOnMainThread();

    // Will resolve google.com to localhost, so the embedded test server can
    // serve a valid content for it.
    host_resolver()->AddRule("google.com", "127.0.0.1");
    embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
        [](const net::test_server::HttpRequest& request)
            -> std::unique_ptr<net::test_server::HttpResponse> {
          if (request.GetURL().GetPath() != "/search") {
            return nullptr;
          }
          // HTTP 200 OK with empty response body.
          return std::make_unique<net::test_server::BasicHttpResponse>();
        }));
    ASSERT_TRUE(embedded_test_server()->Start());
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    AndroidBrowserTest::SetUpCommandLine(command_line);
    // The production code only allows known ports (80 for http and 443 for
    // https), but the embedded test server runs on a random port and adds it to
    // the url spec.
    command_line->AppendSwitch(switches::kIgnoreGooglePortNumbers);
  }

  base::HistogramTester histogram_tester_;
  base::test::ScopedFeatureList scoped_feature_list_{
      kPropagateDeviceContentFiltersToSupervisedUser};
};

// With disabled search content filters, the navigation is unchanged and safe
// search query params are not appended.
IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationObserverAndroidBrowserTest,
                       DontPropagateSearchContentFilterSettingWhenDisabled) {
  ASSERT_FALSE(GetDeviceParentalControls().IsSearchContentFiltersEnabled());

  // The loaded URL is exactly as requested.
  EXPECT_TRUE(content::NavigateToURL(
      web_contents(),
      embedded_test_server()->GetURL("google.com", "/search?q=cat")));
}

// Verifies that the search content filter setting is propagated through the
// supervised user service to navigation throttles that alter the URL. This
// particular test doesn't require navigation observer, but is hosted here for
// feature consistency.
IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationObserverAndroidBrowserTest,
                       LoadSafeSearchResultsWithSearchContentFilterPreset) {
  GetDeviceParentalControls().SetSearchContentFiltersEnabledForTesting(true);
  GURL url = embedded_test_server()->GetURL("google.com", "/search?q=cat");

  // The final url will be different: with safe search query params.
  EXPECT_TRUE(content::NavigateToURL(
      web_contents(), url, GURL(url.spec() + "&safe=active&ssui=on")));
}

// Anti-regression test.
// Inactive supervised user settings must not affect the values set in the
// supervised user pref store by device parental controls.
IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationObserverAndroidBrowserTest,
                       InactiveSupervisedUserSettingsCantVetoSafeSearch) {
  GetDeviceParentalControls().SetSearchContentFiltersEnabledForTesting(true);

  Profile* profile =
      Profile::FromBrowserContext(web_contents()->GetBrowserContext());
  SupervisedUserSettingsService* settings_service =
      SupervisedUserSettingsServiceFactory::GetForKey(profile->GetProfileKey());

  // Settings service should be already inactive (because family link parental
  // controls were never activated).
  ASSERT_FALSE(IsSubjectToParentalControls(*profile->GetPrefs()));
  ASSERT_FALSE(settings_service->IsActive());
  // This means that this call should be a no-op if service was previously
  // inactive. If it was not a no-op, it would clear the supervised user prefs
  // store and consequently the safe search setting from device parental
  // controls.
  settings_service->SetActive(false);

  GURL url = embedded_test_server()->GetURL("google.com", "/search?q=cat");

  // Despite inactivating the settings service, the final url still contains
  // safe search extra query params - it's because the inactivation was a no-op.
  EXPECT_TRUE(content::NavigateToURL(
      web_contents(), url, GURL(url.spec() + "&safe=active&ssui=on")));
}

// Similar to the above test, but the URL already contains safe search query
// params (for example, from a previous navigation or added manually by user in
// the Omnibox). They are removed regardless of their value, and safe search
// params are appended.
IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationObserverAndroidBrowserTest,
                       PreexistingSafeSearchParamsAreRemovedBeforeAppending) {
  GetDeviceParentalControls().SetSearchContentFiltersEnabledForTesting(true);
  GURL url = embedded_test_server()->GetURL("google.com",
                                            "/search?safe=off&ssui=on&q=cat");

  // The final url will be different: with extra query params appended and
  // previous ones removed.
  GURL expected_url = embedded_test_server()->GetURL(
      "google.com", "/search?q=cat&safe=active&ssui=on");
  EXPECT_TRUE(content::NavigateToURL(web_contents(), url, expected_url));
}

// Verifies that the search content filter is propagated through the supervised
// user service to to the navigation observer, and that the navigation observer
// triggers the page reload.
IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationObserverAndroidBrowserTest,
                       ReloadSearchResultAfterSearchContentFilterIsEnabled) {
  // Verify that the observer is attached.
  ASSERT_NE(nullptr,
            SupervisedUserNavigationObserver::FromWebContents(web_contents()));

  GURL url = embedded_test_server()->GetURL("google.com", "/search?q=cat");
  EXPECT_TRUE(content::NavigateToURL(web_contents(), url));

  content::TestNavigationObserver navigation_observer(web_contents());
  GetDeviceParentalControls().SetSearchContentFiltersEnabledForTesting(true);
  navigation_observer.Wait();

  // Key part: the search results are reloaded with extra query params.
  EXPECT_EQ(url.spec() + "&safe=active&ssui=on",
            web_contents()->GetLastCommittedURL());
}

// Tests if no-approval interstitial is shown when the browser content filter
// is enabled.
class SupervisedUserNavigationObserverNoApprovalsInterstitialAndroidBrowserTest
    : public SupervisedUserNavigationObserverAndroidBrowserTest {
 protected:
  void EnableBrowserFilteringAndWaitForInterstitial() {
    content::TestNavigationObserver navigation_observer(web_contents());
    // Turn the filtering on. That will trigger a url check which is resolved to
    // restricted.
    GetDeviceParentalControls().SetBrowserContentFiltersEnabledForTesting(true);
    navigation_observer.Wait();
  }

  void ClickButtonById(std::string_view link_id) {
    content::TestNavigationObserver navigation_observer(web_contents());
    content::SimulateMouseClickOrTapElementWithId(web_contents(), link_id);
    navigation_observer.Wait();
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_{
      kSupervisedUserInterstitialWithoutApprovals};
};

// Shows the interstitial page when the search content filter is enabled.
IN_PROC_BROWSER_TEST_F(
    SupervisedUserNavigationObserverNoApprovalsInterstitialAndroidBrowserTest,
    ShowInterstitialPage) {
  // Verify that the observer is attached.
  ASSERT_NE(nullptr,
            SupervisedUserNavigationObserver::FromWebContents(web_contents()));
  GURL url = embedded_test_server()->GetURL("/supervised_user/simple.html");

  // In this test, all classifications are restricted after enabling the
  // browser content filter.
  EXPECT_CALL(GetMockUrlCheckerClient(), CheckURL(url, _))
      .WillOnce(
          [](const GURL& url, URLCheckerClient::ClientCheckCallback callback) {
            std::move(callback).Run(url, ClientClassification::kRestricted);
          });

  // Navigate to a simple page and verify the title. The page is not filtered.
  ASSERT_TRUE(content::NavigateToURL(web_contents(), url));
  ASSERT_EQ(u"Supervised User test: simple page", web_contents()->GetTitle());

  EnableBrowserFilteringAndWaitForInterstitial();

  EXPECT_EQ(u"Site blocked", web_contents()->GetTitle());
  // Learn more button is specific to this interstitial.
  EXPECT_TRUE(content::ExecJs(web_contents(),
                              "document.getElementById('learn-more-button');"));
}

// Clicks the learn more button on the interstitial page and verifies that the
// help center page about to be loaded.
IN_PROC_BROWSER_TEST_F(
    SupervisedUserNavigationObserverNoApprovalsInterstitialAndroidBrowserTest,
    GoToHelpCenterPage) {
  // Verify that the observer is attached.
  ASSERT_NE(nullptr,
            SupervisedUserNavigationObserver::FromWebContents(web_contents()));

  // In this test, all classifications are restricted after enabling the
  // browser content filter.
  ON_CALL(GetMockUrlCheckerClient(), CheckURL)
      .WillByDefault(
          [](const GURL& url, URLCheckerClient::ClientCheckCallback callback) {
            std::move(callback).Run(url, ClientClassification::kRestricted);
          });

  // Navigate to a simple page and verify the title. The page is not filtered.
  ASSERT_TRUE(content::NavigateToURL(
      web_contents(),
      embedded_test_server()->GetURL("/supervised_user/simple.html")));
  ASSERT_EQ(u"Supervised User test: simple page", web_contents()->GetTitle());

  // After filters are enabled, the interstitial page is shown.
  EnableBrowserFilteringAndWaitForInterstitial();
  EXPECT_EQ(u"Site blocked", web_contents()->GetTitle());

  // Navigation to google.com pages is expected to be always allowed.
  GURL help_center_url = GURL(kDeviceFiltersHelpCenterUrl);
  ASSERT_TRUE(GetSupervisedUserService()
                  ->GetURLFilter()
                  ->GetFilteringBehavior(help_center_url)
                  .IsAllowed());

  histogram_tester().ExpectTotalCount("ManagedMode.BlockingInterstitialCommand",
                                      0);
  ClickButtonById("learn-more-button");
  histogram_tester().ExpectBucketCount(
      "ManagedMode.BlockingInterstitialCommand",
      SupervisedUserInterstitial::Commands::LEARN_MORE, 1);

  // This expectation verifies that the help center page was attempted to be
  // loaded (test don't have internet)
  EXPECT_EQ(base::UTF8ToUTF16(help_center_url.GetHost()),
            web_contents()->GetTitle());
}

// Clicks the back button on the interstitial page and verifies that the
// previous page is shown again.
IN_PROC_BROWSER_TEST_F(
    SupervisedUserNavigationObserverNoApprovalsInterstitialAndroidBrowserTest,
    GoBack) {
  // Verify that the observer is attached.
  ASSERT_NE(SupervisedUserNavigationObserver::FromWebContents(web_contents()),
            nullptr);

  GURL allowed_url =
      embedded_test_server()->GetURL("/supervised_user/simple.html");
  GURL blocked_url =
      embedded_test_server()->GetURL("/supervised_user/explicit.html");

  // In this test to facilitate the back button click, one url is allowed but
  // others are not. All navigations are subject to classification in this test.
  GetDeviceParentalControls().SetBrowserContentFiltersEnabledForTesting(true);

  // Two classification calls are expected:
  // 1. when the page is first loaded
  // 2. when the explicit page is attempted to be loaded
  // Back button click is not triggering any classification requests.
  EXPECT_CALL(GetMockUrlCheckerClient(), CheckURL(allowed_url, _))
      .WillOnce(
          [](const GURL& url, URLCheckerClient::ClientCheckCallback callback) {
            std::move(callback).Run(url, ClientClassification::kAllowed);
          });
  EXPECT_CALL(GetMockUrlCheckerClient(), CheckURL(blocked_url, _))
      .WillOnce(
          [](const GURL& url, URLCheckerClient::ClientCheckCallback callback) {
            std::move(callback).Run(url, ClientClassification::kRestricted);
          });

  // Navigate to a simple page and verify the title. The page is not filtered.
  ASSERT_TRUE(content::NavigateToURL(web_contents(), allowed_url));
  ASSERT_EQ(u"Supervised User test: simple page", web_contents()->GetTitle());

  // Navigate to blocked url. The navigation is not successful even though the
  // url is committed, because the interstitial blocks it.
  EXPECT_FALSE(content::NavigateToURL(web_contents(), blocked_url));
  EXPECT_EQ(u"Site blocked", web_contents()->GetTitle());
  EXPECT_EQ(blocked_url, web_contents()->GetLastCommittedURL());

  // After clicking the back button, the previous page is available back again.
  histogram_tester().ExpectTotalCount("ManagedMode.BlockingInterstitialCommand",
                                      0);
  ClickButtonById("back-button");
  histogram_tester().ExpectBucketCount(
      "ManagedMode.BlockingInterstitialCommand",
      SupervisedUserInterstitial::Commands::BACK, 1);

  EXPECT_EQ(u"Supervised User test: simple page", web_contents()->GetTitle());
  EXPECT_EQ(allowed_url, web_contents()->GetLastCommittedURL());
}

}  // namespace
}  // namespace supervised_user