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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
|
// Copyright 2013 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/ash/app_mode/kiosk_app_data.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "base/check.h"
#include "base/check_op.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/values.h"
#include "chrome/browser/ash/app_mode/kiosk_app_data_delegate.h"
#include "chrome/browser/ash/app_mode/kiosk_chrome_app_manager.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/cws_item_service.pb.h"
#include "chrome/browser/extensions/webstore_data_fetcher.h"
#include "chrome/browser/extensions/webstore_install_helper.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/crx_file_info.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/image_loader.h"
#include "extensions/browser/install/crx_install_error.h"
#include "extensions/browser/sandboxed_unpacker.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_resource.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/icons/extension_icon_set.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/icons_handler.h"
#include "extensions/common/manifest_handlers/kiosk_mode_info.h"
#include "extensions/common/mojom/manifest.mojom-shared.h"
#include "extensions/common/verifier_formats.h"
#include "kiosk_app_data_base.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/image/image.h"
using content::BrowserThread;
namespace ash {
namespace {
// Keys for local state data. See sample layout in KioskChromeAppManager.
constexpr char kKeyRequiredPlatformVersion[] = "required_platform_version";
// Returns true for valid kiosk app manifest.
bool IsValidKioskAppManifest(const extensions::Manifest& manifest) {
return manifest.FindBoolPath(extensions::manifest_keys::kKioskEnabled)
.value_or(false);
}
std::string ValueToString(base::ValueView value) {
std::string json;
base::JSONWriter::Write(value, &json);
return json;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// KioskAppData::CrxLoader
// Loads meta data from crx file.
class KioskAppData::CrxLoader : public extensions::SandboxedUnpackerClient {
public:
CrxLoader(const base::WeakPtr<KioskAppData>& client,
const base::FilePath& crx_file)
: client_(client),
crx_file_(crx_file),
task_runner_(base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {}
CrxLoader(const CrxLoader&) = delete;
CrxLoader& operator=(const CrxLoader&) = delete;
void Start() {
task_runner_->PostTask(FROM_HERE,
base::BindOnce(&CrxLoader::StartInThreadPool, this));
}
bool success() const { return success_; }
const base::FilePath& crx_file() const { return crx_file_; }
const std::string& name() const { return name_; }
const SkBitmap& icon() const { return icon_; }
const std::string& required_platform_version() const {
return required_platform_version_;
}
private:
~CrxLoader() override = default;
// extensions::SandboxedUnpackerClient
void OnUnpackSuccess(const base::FilePath& temp_dir,
const base::FilePath& extension_root,
std::unique_ptr<base::Value::Dict> original_manifest,
const extensions::Extension* extension,
const SkBitmap& install_icon,
base::Value::Dict ruleset_install_prefs) override {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
const extensions::KioskModeInfo* info =
extensions::KioskModeInfo::Get(extension);
if (info == nullptr) {
LOG(ERROR) << extension->id() << " is not a valid kiosk app.";
success_ = false;
} else {
success_ = true;
name_ = extension->name();
icon_ = install_icon;
required_platform_version_ = info->required_platform_version;
}
NotifyFinishedInThreadPool();
}
void OnUnpackFailure(const extensions::CrxInstallError& error) override {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
success_ = false;
NotifyFinishedInThreadPool();
}
void StartInThreadPool() {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (!temp_dir_.CreateUniqueTempDir()) {
success_ = false;
NotifyFinishedInThreadPool();
return;
}
auto unpacker = base::MakeRefCounted<extensions::SandboxedUnpacker>(
extensions::mojom::ManifestLocation::kInternal,
extensions::Extension::NO_FLAGS, temp_dir_.GetPath(),
task_runner_.get(), this);
unpacker->StartWithCrx(extensions::CRXFileInfo(
crx_file_, extensions::GetPolicyVerifierFormat()));
}
void NotifyFinishedInThreadPool() {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (!temp_dir_.Delete()) {
LOG(WARNING) << "Can not delete temp directory at "
<< temp_dir_.GetPath().value();
}
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&CrxLoader::NotifyFinishedOnUIThread, this));
}
void NotifyFinishedOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (client_) {
client_->OnCrxLoadFinished(this);
}
}
base::WeakPtr<KioskAppData> client_;
base::FilePath crx_file_;
bool success_ = false;
const scoped_refptr<base::SequencedTaskRunner> task_runner_;
base::ScopedTempDir temp_dir_;
// Extracted meta data.
std::string name_;
SkBitmap icon_;
std::string required_platform_version_;
};
////////////////////////////////////////////////////////////////////////////////
// KioskAppData::WebstoreDataParser
// Use WebstoreInstallHelper to parse the manifest and decode the icon.
class KioskAppData::WebstoreDataParser
: public extensions::WebstoreInstallHelper::Delegate {
public:
explicit WebstoreDataParser(const base::WeakPtr<KioskAppData>& client)
: client_(client) {}
WebstoreDataParser(const WebstoreDataParser&) = delete;
WebstoreDataParser& operator=(const WebstoreDataParser&) = delete;
void Start(const std::string& app_id,
const std::string& manifest,
const GURL& icon_url,
network::mojom::URLLoaderFactory* loader_factory) {
scoped_refptr<extensions::WebstoreInstallHelper> webstore_helper =
new extensions::WebstoreInstallHelper(this, app_id, manifest, icon_url);
webstore_helper->Start(loader_factory);
}
private:
friend class base::RefCounted<WebstoreDataParser>;
~WebstoreDataParser() override = default;
void ReportFailure() {
if (client_) {
client_->OnWebstoreParseFailure();
}
delete this;
}
// WebstoreInstallHelper::Delegate overrides:
void OnWebstoreParseSuccess(const std::string& id,
const SkBitmap& icon,
base::Value::Dict parsed_manifest) override {
extensions::Manifest manifest(
extensions::mojom::ManifestLocation::kInvalidLocation,
std::move(parsed_manifest), id);
if (!IsValidKioskAppManifest(manifest)) {
ReportFailure();
return;
}
std::string required_platform_version;
if (const base::Value* temp = manifest.FindPath(
extensions::manifest_keys::kKioskRequiredPlatformVersion)) {
if (!temp->is_string() ||
!extensions::KioskModeInfo::IsValidPlatformVersion(
temp->GetString())) {
ReportFailure();
return;
}
required_platform_version = temp->GetString();
}
if (client_) {
client_->OnWebstoreParseSuccess(icon, required_platform_version);
}
delete this;
}
void OnWebstoreParseFailure(const std::string& id,
InstallHelperResultCode result_code,
const std::string& error_message) override {
ReportFailure();
}
base::WeakPtr<KioskAppData> client_;
};
////////////////////////////////////////////////////////////////////////////////
// KioskAppData
KioskAppData::KioskAppData(KioskAppDataDelegate& delegate,
const std::string& app_id,
const AccountId& account_id,
const GURL& update_url,
const base::FilePath& cached_crx)
: KioskAppDataBase(KioskChromeAppManager::kKioskDictionaryName,
app_id,
account_id),
delegate_(delegate),
status_(Status::kInit),
update_url_(update_url),
crx_file_(cached_crx) {}
KioskAppData::~KioskAppData() = default;
void KioskAppData::Load() {
SetStatus(Status::kLoading);
if (LoadFromCache()) {
return;
}
StartFetch();
}
void KioskAppData::LoadFromInstalledApp(Profile* profile,
const extensions::Extension* app) {
SetStatus(Status::kLoading);
if (!app) {
app = extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(
app_id());
}
DCHECK_EQ(app_id(), app->id());
name_ = app->name();
required_platform_version_ =
extensions::KioskModeInfo::Get(app)->required_platform_version;
const int kIconSize = extension_misc::EXTENSION_ICON_LARGE;
extensions::ExtensionResource image = extensions::IconsInfo::GetIconResource(
app, kIconSize, ExtensionIconSet::Match::kBigger);
extensions::ImageLoader::Get(profile)->LoadImageAsync(
app, image, gfx::Size(kIconSize, kIconSize),
base::BindOnce(&KioskAppData::OnExtensionIconLoaded,
weak_factory_.GetWeakPtr()));
}
void KioskAppData::SetCachedCrx(const base::FilePath& crx_file) {
if (crx_file_ == crx_file) {
return;
}
crx_file_ = crx_file;
LoadFromCrx();
}
bool KioskAppData::IsLoading() const {
return status_ == Status::kLoading;
}
bool KioskAppData::IsFromWebStore() const {
return update_url_.is_empty() ||
extension_urls::IsWebstoreUpdateUrl(update_url_);
}
void KioskAppData::SetStatusForTest(Status status) {
SetStatus(status);
}
// static
std::unique_ptr<KioskAppData> KioskAppData::CreateForTest(
KioskAppDataDelegate& delegate,
const std::string& app_id,
const AccountId& account_id,
const GURL& update_url,
const std::string& required_platform_version) {
std::unique_ptr<KioskAppData> data(new KioskAppData(
delegate, app_id, account_id, update_url, base::FilePath()));
data->status_ = Status::kLoaded;
data->required_platform_version_ = required_platform_version;
return data;
}
void KioskAppData::SetStatus(Status status) {
if (status_ == status) {
return;
}
status_ = status;
switch (status_) {
case Status::kInit:
case Status::kLoading:
case Status::kLoaded:
delegate_->OnKioskAppDataChanged(app_id());
break;
case Status::kError:
delegate_->OnKioskAppDataLoadFailure(app_id());
break;
}
}
network::mojom::URLLoaderFactory* KioskAppData::GetURLLoaderFactory() {
return g_browser_process->system_network_context_manager()
->GetURLLoaderFactory();
}
bool KioskAppData::LoadFromCache() {
PrefService* local_state = g_browser_process->local_state();
const base::Value::Dict& dict = local_state->GetDict(dictionary_name());
if (!LoadFromDictionary(dict)) {
return false;
}
DecodeIcon(base::BindOnce(&KioskAppData::OnIconLoadDone,
weak_factory_.GetWeakPtr()));
const std::string app_key = std::string(kKeyApps) + '.' + app_id();
const std::string required_platform_version_key =
app_key + '.' + kKeyRequiredPlatformVersion;
const std::string* maybe_required_platform_version =
dict.FindStringByDottedPath(required_platform_version_key);
if (!maybe_required_platform_version) {
return false;
}
required_platform_version_ = *maybe_required_platform_version;
return true;
}
void KioskAppData::SetCache(const std::string& name,
const SkBitmap& icon,
const std::string& required_platform_version) {
name_ = name;
required_platform_version_ = required_platform_version;
icon_ = gfx::ImageSkia::CreateFrom1xBitmap(icon);
icon_.MakeThreadSafe();
SaveIcon(icon, delegate_->GetKioskAppIconCacheDir());
PrefService* local_state = g_browser_process->local_state();
ScopedDictPrefUpdate dict_update(local_state, dictionary_name());
SaveToDictionary(dict_update);
const std::string app_key = std::string(kKeyApps) + '.' + app_id();
const std::string required_platform_version_key =
app_key + '.' + kKeyRequiredPlatformVersion;
dict_update->SetByDottedPath(required_platform_version_key,
required_platform_version);
}
void KioskAppData::OnExtensionIconLoaded(const gfx::Image& icon) {
if (icon.IsEmpty()) {
LOG(WARNING) << "Failed to load icon from installed app"
<< ", id=" << app_id();
SetCache(name_, *extensions::util::GetDefaultAppIcon().bitmap(),
required_platform_version_);
} else {
SetCache(name_, icon.AsBitmap(), required_platform_version_);
}
SetStatus(Status::kLoaded);
}
void KioskAppData::OnIconLoadDone(std::optional<gfx::ImageSkia> icon) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
kiosk_app_icon_loader_.reset();
if (!icon.has_value()) {
// Re-fetch data from web store when failed to load cached data.
StartFetch();
return;
}
icon_ = icon.value();
SetStatus(Status::kLoaded);
}
void KioskAppData::OnWebstoreParseSuccess(
const SkBitmap& icon,
const std::string& required_platform_version) {
SetCache(name_, icon, required_platform_version);
SetStatus(Status::kLoaded);
}
void KioskAppData::OnWebstoreParseFailure() {
LOG(WARNING) << "Webstore request parse failure for app_id=" << app_id();
SetStatus(Status::kError);
}
void KioskAppData::StartFetch() {
if (!IsFromWebStore()) {
LoadFromCrx();
return;
}
webstore_fetcher_ =
std::make_unique<extensions::WebstoreDataFetcher>(this, GURL(), app_id());
webstore_fetcher_->set_max_auto_retries(3);
webstore_fetcher_->Start(g_browser_process->system_network_context_manager()
->GetURLLoaderFactory());
}
void KioskAppData::OnWebstoreRequestFailure(const std::string& extension_id) {
LOG(WARNING) << "Webstore request failure for app_id=" << extension_id;
SetStatus(Status::kError);
}
void KioskAppData::OnFetchItemSnippetParseSuccess(
const std::string& extension_id,
extensions::FetchItemSnippetResponse item_snippet) {
if (extension_id != item_snippet.item_id()) {
LOG(ERROR) << "Webstore response error (itemId):"
<< " received extension id " << item_snippet.item_id()
<< " does not equal expected extension id " << extension_id;
OnWebstoreResponseParseFailure(extension_id, kInvalidWebstoreResponseError);
return;
}
webstore_fetcher_.reset();
GURL icon_url =
extension_urls::GetWebstoreLaunchURL().Resolve(item_snippet.logo_uri());
if (!icon_url.is_valid()) {
LOG(ERROR) << "Webstore response error (iconUri):"
<< " the provided icon url " << item_snippet.logo_uri()
<< " is not valid.";
OnWebstoreResponseParseFailure(extension_id, kInvalidWebstoreResponseError);
return;
}
name_ = item_snippet.title();
// WebstoreDataParser deletes itself when done.
(new WebstoreDataParser(weak_factory_.GetWeakPtr()))
->Start(app_id(), item_snippet.manifest(), icon_url,
GetURLLoaderFactory());
}
void KioskAppData::OnWebstoreResponseParseFailure(
const std::string& extension_id,
const std::string& error) {
LOG(ERROR) << "Webstore failed for kiosk app " << app_id() << ", " << error;
webstore_fetcher_.reset();
SetStatus(Status::kError);
}
bool KioskAppData::CheckResponseKeyValue(const std::string& extension_id,
const base::Value::Dict& response,
const char* key,
std::string* value) {
const std::string* value_ptr = response.FindString(key);
if (!value_ptr) {
LOG(ERROR) << "Webstore response error (" << key
<< "): " << ValueToString(response);
OnWebstoreResponseParseFailure(extension_id, kInvalidWebstoreResponseError);
return false;
}
*value = *value_ptr;
return true;
}
void KioskAppData::LoadFromCrx() {
if (crx_file_.empty()) {
return;
}
scoped_refptr<CrxLoader> crx_loader(
new CrxLoader(weak_factory_.GetWeakPtr(), crx_file_));
crx_loader->Start();
}
void KioskAppData::OnCrxLoadFinished(const CrxLoader* crx_loader) {
DCHECK(crx_loader);
if (crx_loader->crx_file() != crx_file_) {
return;
}
if (!crx_loader->success()) {
LOG(ERROR) << "Failed to load cached extension data for app_id="
<< app_id();
// If after unpacking the cached extension we received an error, schedule
// a redownload upon next session start(kiosk or login).
delegate_->OnExternalCacheDamaged(app_id());
SetStatus(Status::kInit);
return;
}
SkBitmap icon = crx_loader->icon();
if (icon.empty()) {
icon = *extensions::util::GetDefaultAppIcon().bitmap();
}
SetCache(crx_loader->name(), icon, crx_loader->required_platform_version());
SetStatus(Status::kLoaded);
}
} // namespace ash
|