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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/api/system_info/system_info_api.h"
#include <string>
#include "base/containers/flat_map.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "components/storage_monitor/storage_info.h"
#include "components/storage_monitor/storage_monitor.h"
#include "components/storage_monitor/test_storage_monitor.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
#include "extensions/browser/api/system_info/system_info_provider.h"
#include "extensions/browser/display_info_provider_base.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/mock_extension_system.h"
#include "extensions/browser/test_extensions_browser_client.h"
#include "extensions/common/api/system_display.h"
#include "extensions/common/api/system_storage.h"
#include "extensions/common/extension_id.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
namespace {
const char kFakeExtensionId[] = "extension_id";
const char kFakeExtensionId2[] = "extension_id_2";
// Extends TestExtensionsBrowserClient to support a secondary context, and also
// tracks events broadcast to renderers.
class FakeExtensionsBrowserClient : public TestExtensionsBrowserClient {
public:
struct Broadcast {
Broadcast(events::HistogramValue histogram_value,
base::Value::List args,
bool dispatch_to_off_the_record_profiles)
: histogram_value(histogram_value),
args(std::move(args)),
dispatch_to_off_the_record_profiles(
dispatch_to_off_the_record_profiles) {}
Broadcast(Broadcast&&) = default;
~Broadcast() = default;
events::HistogramValue histogram_value;
base::Value::List args;
bool dispatch_to_off_the_record_profiles;
};
// TestExtensionsBrowserClient:
bool IsValidContext(void* context) override {
return TestExtensionsBrowserClient::IsValidContext(context) ||
context == second_context_;
}
// TestExtensionsBrowserClient:
content::BrowserContext* GetOriginalContext(
content::BrowserContext* context) override {
if (context == second_context_)
return second_context_;
return TestExtensionsBrowserClient::GetOriginalContext(context);
}
// TestExtensionsBrowserClient:
void BroadcastEventToRenderers(
events::HistogramValue histogram_value,
const std::string& event_name,
base::Value::List args,
bool dispatch_to_off_the_record_profiles) override {
event_name_to_broadcasts_map_[event_name].emplace_back(
histogram_value, std::move(args), dispatch_to_off_the_record_profiles);
}
void SetSecondContext(content::BrowserContext* second_context) {
DCHECK(!second_context_);
DCHECK(second_context);
DCHECK(!second_context->IsOffTheRecord());
second_context_ = second_context;
}
const std::vector<Broadcast>& GetBroadcastsForEvent(
const std::string& event_name) {
return event_name_to_broadcasts_map_[event_name];
}
private:
raw_ptr<content::BrowserContext> second_context_ = nullptr;
base::flat_map<std::string, std::vector<Broadcast>>
event_name_to_broadcasts_map_;
};
class FakeDisplayInfoProvider : public DisplayInfoProviderBase {
public:
FakeDisplayInfoProvider() = default;
~FakeDisplayInfoProvider() override = default;
// DisplayInfoProvider:
void StartObserving() override { is_observing_ = true; }
void StopObserving() override { is_observing_ = false; }
bool is_observing() const { return is_observing_; }
private:
bool is_observing_ = false;
};
EventRouter* CreateAndUsePreflessEventRouter(content::BrowserContext* context) {
return static_cast<EventRouter*>(
EventRouterFactory::GetInstance()->SetTestingFactoryAndUse(
context, base::BindRepeating([](content::BrowserContext* context) {
return static_cast<std::unique_ptr<KeyedService>>(
std::make_unique<EventRouter>(context,
nullptr /* extensions_prefs */));
})));
}
const std::string& GetFakeStorageDeviceId() {
static const base::NoDestructor<std::string> id([] {
return storage_monitor::StorageInfo::MakeDeviceId(
storage_monitor::StorageInfo::Type::REMOVABLE_MASS_STORAGE_WITH_DCIM,
"storage_device_id");
}());
return *id;
}
const storage_monitor::StorageInfo& GetFakeStorageInfo() {
static const base::NoDestructor<storage_monitor::StorageInfo> info([] {
return storage_monitor::StorageInfo(
GetFakeStorageDeviceId(),
base::FilePath::StringType() /* device_location */,
std::u16string() /* label */, std::u16string() /* vendor */,
std::u16string() /* model */, 0 /* size_in_bytes */);
}());
return *info;
}
base::Value::List GetStorageAttachedArgs() {
// Because of the use of GetTransientIdForDeviceId() in
// BuildStorageUnitInfo(), we cannot use a static variable and cache the
// returned value.
api::system_storage::StorageUnitInfo unit;
systeminfo::BuildStorageUnitInfo(GetFakeStorageInfo(), &unit);
base::Value::List args;
args.Append(unit.ToValue());
return args;
}
base::Value::List GetStorageDetachedArgs() {
// Because of the use of GetTransientIdForDeviceId(), we cannot use a static
// variable and cache the returned value.
base::Value::List args;
args.Append(
storage_monitor::StorageMonitor::GetInstance()->GetTransientIdForDeviceId(
GetFakeStorageDeviceId()));
return args;
}
} // namespace
class SystemInfoAPITest : public testing::Test {
protected:
enum class EventType { kDisplay, kStorageAttached, kStorageDetached };
SystemInfoAPITest() = default;
~SystemInfoAPITest() override = default;
void SetUp() override {
client_.SetMainContext(&context1_);
client_.SetSecondContext(&context2_);
ExtensionsBrowserClient::Set(&client_);
client_.set_extension_system_factory(&factory_);
BrowserContextDependencyManager::GetInstance()
->CreateBrowserContextServicesForTest(&context1_);
BrowserContextDependencyManager::GetInstance()
->CreateBrowserContextServicesForTest(&context2_);
router1_ = CreateAndUsePreflessEventRouter(&context1_);
router2_ = CreateAndUsePreflessEventRouter(&context2_);
FakeDisplayInfoProvider::InitializeForTesting(&display_info_provider_);
storage_monitor_ = storage_monitor::TestStorageMonitor::CreateAndInstall();
render_process_host_ =
std::make_unique<content::MockRenderProcessHost>(&context1_);
}
void TearDown() override {
storage_monitor_ = nullptr;
storage_monitor::StorageMonitor::Destroy();
DisplayInfoProvider::ResetForTesting();
router2_ = nullptr;
router1_ = nullptr;
BrowserContextDependencyManager::GetInstance()
->DestroyBrowserContextServices(&context2_);
BrowserContextDependencyManager::GetInstance()
->DestroyBrowserContextServices(&context1_);
ExtensionsBrowserClient::Set(nullptr);
render_process_host_.reset();
}
content::RenderProcessHost* render_process_host() const {
return render_process_host_.get();
}
std::string EventTypeToName(EventType type) {
switch (type) {
case EventType::kDisplay:
return api::system_display::OnDisplayChanged::kEventName;
case EventType::kStorageAttached:
return api::system_storage::OnAttached::kEventName;
case EventType::kStorageDetached:
return api::system_storage::OnDetached::kEventName;
}
}
void AddEventListener(EventRouter* router,
EventType type,
const ExtensionId& extension_id = kFakeExtensionId) {
router->AddEventListener(EventTypeToName(type), render_process_host(),
extension_id);
}
void RemoveEventListener(EventRouter* router,
EventType type,
const ExtensionId& extension_id = kFakeExtensionId) {
router->RemoveEventListener(EventTypeToName(type), render_process_host(),
extension_id);
}
// Returns true if the DisplayInfoProvider is observing. When
// DisplayInfoProvider is observing, it is notified of display changes, and is
// responsible for dispatching events.
bool IsDispatchingDisplayEvents() {
return display_info_provider_.is_observing();
}
// Returns true if the extension is observing storage-attach changes from the
// StorageMonitor and subsequently dispatching the expected storage-attached
// events.
bool IsDispatchingStorageAttachedEvents() {
size_t num_events_before =
client_
.GetBroadcastsForEvent(api::system_storage::OnAttached::kEventName)
.size();
// Because the StorageMonitor uses thread-safe observers, we need the
// RunUntilIdle() statement.
storage_monitor_->receiver()->ProcessAttach(GetFakeStorageInfo());
base::RunLoop().RunUntilIdle();
const std::vector<FakeExtensionsBrowserClient::Broadcast>& broadcasts =
client_.GetBroadcastsForEvent(
api::system_storage::OnAttached::kEventName);
size_t num_events_after = broadcasts.size();
if (num_events_after != num_events_before + 1)
return false;
return broadcasts.back().histogram_value ==
events::SYSTEM_STORAGE_ON_ATTACHED &&
broadcasts.back().args == GetStorageAttachedArgs() &&
!broadcasts.back().dispatch_to_off_the_record_profiles;
}
// Returns true if the extension is observing storage-detach changes from the
// StorageMonitor and subsequently dispatching the expected storage-detached
// events.
bool IsDispatchingStorageDetachedEvents() {
size_t num_events_before =
client_
.GetBroadcastsForEvent(api::system_storage::OnDetached::kEventName)
.size();
// Because the StorageMonitor uses thread-safe observers, we need the
// RunUntilIdle() statement.
storage_monitor_->receiver()->ProcessDetach(GetFakeStorageDeviceId());
base::RunLoop().RunUntilIdle();
const std::vector<FakeExtensionsBrowserClient::Broadcast>& broadcasts =
client_.GetBroadcastsForEvent(
api::system_storage::OnDetached::kEventName);
size_t num_events_after = broadcasts.size();
if (num_events_after != num_events_before + 1)
return false;
return broadcasts.back().histogram_value ==
events::SYSTEM_STORAGE_ON_DETACHED &&
broadcasts.back().args == GetStorageDetachedArgs() &&
!broadcasts.back().dispatch_to_off_the_record_profiles;
}
content::BrowserTaskEnvironment task_environment_;
content::TestBrowserContext context1_;
content::TestBrowserContext context2_;
FakeExtensionsBrowserClient client_;
MockExtensionSystemFactory<MockExtensionSystem> factory_;
raw_ptr<EventRouter> router1_ = nullptr;
raw_ptr<EventRouter> router2_ = nullptr;
FakeDisplayInfoProvider display_info_provider_;
raw_ptr<storage_monitor::TestStorageMonitor> storage_monitor_;
std::unique_ptr<content::RenderProcessHost> render_process_host_;
};
/******************************************************************************/
// Display event tests
/******************************************************************************/
TEST_F(SystemInfoAPITest, DisplayListener_AddRemove) {
EXPECT_FALSE(IsDispatchingDisplayEvents());
// Say a display event listener exists before SystemInfoAPI is created.
AddEventListener(router1_, EventType::kDisplay);
SystemInfoAPI api1(&context1_);
EXPECT_TRUE(IsDispatchingDisplayEvents());
RemoveEventListener(router1_, EventType::kDisplay);
EXPECT_FALSE(IsDispatchingDisplayEvents());
AddEventListener(router1_, EventType::kDisplay);
EXPECT_TRUE(IsDispatchingDisplayEvents());
api1.Shutdown();
EXPECT_FALSE(IsDispatchingDisplayEvents());
}
TEST_F(SystemInfoAPITest, DisplayListener_MultipleContexts) {
SystemInfoAPI api1(&context1_);
SystemInfoAPI api2(&context2_);
EXPECT_FALSE(IsDispatchingDisplayEvents());
AddEventListener(router1_, EventType::kDisplay);
EXPECT_TRUE(IsDispatchingDisplayEvents());
AddEventListener(router2_, EventType::kDisplay);
EXPECT_TRUE(IsDispatchingDisplayEvents());
// DisplayInfoProvider should be observing (in other words, display events
// should be dispatched) if and only if at least one browser context has a
// display listener.
RemoveEventListener(router1_, EventType::kDisplay);
EXPECT_TRUE(IsDispatchingDisplayEvents());
RemoveEventListener(router2_, EventType::kDisplay);
EXPECT_FALSE(IsDispatchingDisplayEvents());
AddEventListener(router1_, EventType::kDisplay);
EXPECT_TRUE(IsDispatchingDisplayEvents());
api2.Shutdown();
EXPECT_TRUE(IsDispatchingDisplayEvents());
api1.Shutdown();
EXPECT_FALSE(IsDispatchingDisplayEvents());
}
TEST_F(SystemInfoAPITest, DisplayListener_MultipleListeners) {
SystemInfoAPI api1(&context1_);
EXPECT_FALSE(IsDispatchingDisplayEvents());
AddEventListener(router1_, EventType::kDisplay);
EXPECT_TRUE(IsDispatchingDisplayEvents());
// Add another listener for the same browser context and use a different
// extension ID so that it is distinct from the other listener.
AddEventListener(router1_, EventType::kDisplay, kFakeExtensionId2);
EXPECT_TRUE(IsDispatchingDisplayEvents());
// Dispatch events until all listeners are removed.
RemoveEventListener(router1_, EventType::kDisplay);
EXPECT_TRUE(IsDispatchingDisplayEvents());
RemoveEventListener(router1_, EventType::kDisplay, kFakeExtensionId2);
EXPECT_FALSE(IsDispatchingDisplayEvents());
api1.Shutdown();
}
/******************************************************************************/
// Storage event tests
/******************************************************************************/
TEST_F(SystemInfoAPITest, StorageListener_AddRemove) {
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
// Say a storage-attached listener exists before SystemInfoAPI is created.
AddEventListener(router1_, EventType::kStorageAttached);
SystemInfoAPI api1(&context1_);
// If a storage-attached *or* storage-detached listener exists, then both
// events are dispatched.
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
AddEventListener(router1_, EventType::kStorageDetached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
RemoveEventListener(router1_, EventType::kStorageDetached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
RemoveEventListener(router1_, EventType::kStorageAttached);
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
AddEventListener(router1_, EventType::kStorageAttached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
api1.Shutdown();
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
}
TEST_F(SystemInfoAPITest, StorageListener_MultipleContexts) {
SystemInfoAPI api1(&context1_);
SystemInfoAPI api2(&context2_);
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
AddEventListener(router1_, EventType::kStorageAttached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
AddEventListener(router2_, EventType::kStorageAttached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
// Storage events should be dispatched if and only if at least one browser
// context has a storage listener.
RemoveEventListener(router1_, EventType::kStorageAttached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
RemoveEventListener(router2_, EventType::kStorageAttached);
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
AddEventListener(router1_, EventType::kStorageAttached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
api2.Shutdown();
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
api1.Shutdown();
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
}
TEST_F(SystemInfoAPITest, StorageListener_MultipleListeners) {
SystemInfoAPI api1(&context1_);
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
AddEventListener(router1_, EventType::kStorageAttached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
// Add another listener for the same browser context and use a different
// extension ID so that it is distinct from the other listener.
AddEventListener(router1_, EventType::kStorageAttached, kFakeExtensionId2);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
// Dispatch events until all listeners are removed.
RemoveEventListener(router1_, EventType::kStorageAttached);
EXPECT_TRUE(IsDispatchingStorageAttachedEvents());
EXPECT_TRUE(IsDispatchingStorageDetachedEvents());
RemoveEventListener(router1_, EventType::kStorageAttached, kFakeExtensionId2);
EXPECT_FALSE(IsDispatchingStorageAttachedEvents());
EXPECT_FALSE(IsDispatchingStorageDetachedEvents());
api1.Shutdown();
}
} // namespace extensions
|