File: chrome_kiosk_app_installer.cc

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 (393 lines) | stat: -rw-r--r-- 13,934 bytes parent folder | download | duplicates (5)
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
// 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.

#include "chrome/browser/chromeos/app_mode/chrome_kiosk_app_installer.h"

#include <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/check.h"
#include "base/check_deref.h"
#include "base/check_op.h"
#include "base/containers/flat_set.h"
#include "base/functional/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_util.h"
#include "base/syslog_logging.h"
#include "chrome/browser/chromeos/app_mode/chrome_kiosk_external_loader_broker.h"
#include "chrome/browser/chromeos/app_mode/startup_app_launcher_update_checker.h"
#include "chrome/browser/extensions/forced_extensions/install_stage_tracker.h"
#include "chrome/browser/extensions/install_tracker_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/pending_extension_manager.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest_handlers/kiosk_mode_info.h"
#include "extensions/common/manifest_handlers/shared_module_info.h"

namespace chromeos {

namespace {

const std::string_view kChromeKioskExtensionUpdateErrorHistogram =
    "Kiosk.ChromeApp.ExtensionUpdateError";

const std::string_view kChromeKioskExtensionHasUpdateDurationHistogram =
    "Kiosk.ChromeApp.ExtensionUpdateDuration.HasUpdate";

const std::string_view kChromeKioskExtensionNoUpdateDurationHistogram =
    "Kiosk.ChromeApp.ExtensionUpdateDuration.NoUpdate";

// Returns true if the app with `id` is pending an install or update.
bool IsExtensionInstallPending(content::BrowserContext& browser_context,
                               const std::string& id) {
  return extensions::PendingExtensionManager::Get(&browser_context)
      ->IsIdPending(id);
}

// Returns the `Extension` corresponding to `id` installed in `browser_context`,
// or null if the extension is not installed.
const extensions::Extension* FindInstalledExtension(
    content::BrowserContext& browser_context,
    const extensions::ExtensionId& id) {
  return extensions::ExtensionRegistry::Get(&browser_context)
      ->GetInstalledExtension(id);
}

// Returns true if the extension with `id` is installed in `browser_context`.
bool IsExtensionInstalled(content::BrowserContext& browser_context,
                          const extensions::ExtensionId& id) {
  return FindInstalledExtension(browser_context, id) != nullptr;
}

// Returns true if all extensions in `ids` are installed in `browser_context`.
bool AreExtensionsInstalled(content::BrowserContext& browser_context,
                            const std::vector<extensions::ExtensionId>& ids) {
  return std::ranges::all_of(ids.begin(), ids.end(),
                             [&browser_context](const auto& id) {
                               return IsExtensionInstalled(browser_context, id);
                             });
}

// Returns true if the secondary apps of `app` contain the given `id`.
bool SecondaryAppsContain(const extensions::Extension& app,
                          const extensions::ExtensionId& id) {
  if (auto* info = extensions::KioskModeInfo::Get(&app); info != nullptr) {
    auto it = std::ranges::find(info->secondary_apps, id,
                                [](const auto& app) { return app.id; });
    return it != info->secondary_apps.end();
  }

  return false;
}

// Returns the IDs of the secondary apps of `app`.
std::vector<extensions::ExtensionId> SecondaryAppIdsOf(
    const extensions::Extension& app) {
  std::vector<extensions::ExtensionId> result;
  if (auto* info = extensions::KioskModeInfo::Get(&app); info != nullptr) {
    std::ranges::transform(info->secondary_apps, std::back_inserter(result),
                           [](const auto& app) { return app.id; });
  }
  return result;
}

// Returns the subset of `app_ids` that is pending install or update.
std::vector<extensions::ExtensionId> CopyIdsPendingInstall(
    content::BrowserContext& browser_context,
    const std::vector<extensions::ExtensionId>& app_ids) {
  std::vector<extensions::ExtensionId> result;
  std::ranges::copy_if(app_ids, std::back_inserter(result),
                       [&browser_context](const auto& id) {
                         return IsExtensionInstallPending(browser_context, id);
                       });
  return result;
}

// Inserts the shared modules `extension` imports into the set of `ids` that are
// pending install.
void InsertPendingSharedModules(content::BrowserContext& browser_context,
                                base::flat_set<extensions::ExtensionId>& ids,
                                const extensions::Extension& extension) {
  const auto& imports = extensions::SharedModuleInfo::GetImports(&extension);
  for (const auto& import_info : imports) {
    if (IsExtensionInstallPending(browser_context, import_info.extension_id)) {
      ids.insert(import_info.extension_id);
    }
  }
}

}  // namespace

ChromeKioskAppInstaller::ChromeKioskAppInstaller(
    Profile* profile,
    const AppInstallParams& install_data)
    : profile_(CHECK_DEREF(profile)), primary_app_install_data_(install_data) {}

ChromeKioskAppInstaller::~ChromeKioskAppInstaller() = default;

void ChromeKioskAppInstaller::BeginInstall(InstallCallback callback) {
  DCHECK(!install_complete_);

  SYSLOG(INFO) << "BeginInstall primary app id: " << primary_app_id();

  on_ready_callback_ = std::move(callback);

  extensions::file_util::SetUseSafeInstallation(true);

  const auto* primary_app =
      FindInstalledExtension(profile_.get(), primary_app_id());

  if (primary_app_install_data_.crx_file_location.empty() &&
      primary_app == nullptr) {
    ReportInstallFailure(InstallResult::kPrimaryAppNotCached);
    return;
  }

  ChromeKioskExternalLoaderBroker::Get()->TriggerPrimaryAppInstall(
      primary_app_install_data_);
  if (IsExtensionInstallPending(profile_.get(), primary_app_id())) {
    ObserveInstallations({primary_app_id()});
    return;
  }

  if (primary_app == nullptr) {
    // The extension is skipped for installation due to some error.
    ReportInstallFailure(InstallResult::kPrimaryAppInstallFailed);
    return;
  }

  if (!extensions::KioskModeInfo::IsKioskEnabled(primary_app)) {
    // The installed primary app is not kiosk enabled.
    ReportInstallFailure(InstallResult::kPrimaryAppNotKioskEnabled);
    return;
  }

  // Install secondary apps.
  MaybeInstallSecondaryApps(*primary_app);
}

void ChromeKioskAppInstaller::MaybeInstallSecondaryApps(
    const extensions::Extension& primary_app) {
  if (install_complete_) {
    return;
  }

  secondary_apps_installing_ = true;

  auto secondary_app_ids = SecondaryAppIdsOf(primary_app);

  ChromeKioskExternalLoaderBroker::Get()->UpdateSecondaryAppList(
      secondary_app_ids);

  if (!secondary_app_ids.empty()) {
    auto pending_ids = CopyIdsPendingInstall(profile_.get(), secondary_app_ids);
    if (!pending_ids.empty()) {
      ObserveInstallations(pending_ids);
      return;
    }
  }

  if (!AreExtensionsInstalled(profile_.get(), secondary_app_ids)) {
    ReportInstallFailure(InstallResult::kSecondaryAppInstallFailed);
    return;
  }

  // Check extension update before launching the primary kiosk app.
  MaybeCheckExtensionUpdate();
}

void ChromeKioskAppInstaller::MaybeCheckExtensionUpdate() {
  DCHECK(!install_complete_);

  SYSLOG(INFO) << "MaybeCheckExtensionUpdate";

  // Record update start time to calculate time consumed by update check. When
  // `OnExtensionUpdateCheckFinished` is called the update is already finished
  // because `extensions::ExtensionUpdater::CheckParams::install_immediately` is
  // set to true.
  extension_update_start_time_ = base::Time::Now();

  // Observe installation failures.
  install_stage_observation_.Observe(
      extensions::InstallStageTracker::Get(&profile_.get()));

  // Enforce an immediate version update check for all extensions before
  // launching the primary app. After the chromeos is updated, the shared
  // module (e.g. ARC runtime) may need to be updated to a newer version
  // compatible with the new chromeos. See crbug.com/555083.
  update_checker_ =
      std::make_unique<StartupAppLauncherUpdateChecker>(&profile_.get());
  if (!update_checker_->Run(base::BindOnce(
          &ChromeKioskAppInstaller::OnExtensionUpdateCheckFinished,
          weak_ptr_factory_.GetWeakPtr()))) {
    update_checker_.reset();
    install_stage_observation_.Reset();
    SYSLOG(WARNING) << "Could not check extension updates";
    FinalizeAppInstall();
    return;
  }

  SYSLOG(INFO) << "Checking extension updates";
}

void ChromeKioskAppInstaller::OnExtensionUpdateCheckFinished(
    bool update_found) {
  DCHECK(!install_complete_);

  SYSLOG(INFO) << "OnExtensionUpdateCheckFinished";
  update_checker_.reset();
  install_stage_observation_.Reset();
  if (update_found) {
    SYSLOG(INFO) << "Reloading extension with id " << primary_app_id();

    // Reload the primary app to make sure any reference to the previous version
    // of the shared module, extension, etc will be cleaned up and the new
    // version will be loaded.
    extensions::ExtensionRegistrar::Get(&profile_.get())
        ->ReloadExtension(primary_app_id());

    SYSLOG(INFO) << "Reloaded extension with id " << primary_app_id();
  }

  base::UmaHistogramMediumTimes(
      update_found ? kChromeKioskExtensionHasUpdateDurationHistogram
                   : kChromeKioskExtensionNoUpdateDurationHistogram,
      base::Time::Now() - extension_update_start_time_);

  FinalizeAppInstall();
}

void ChromeKioskAppInstaller::FinalizeAppInstall() {
  DCHECK(!install_complete_);

  install_complete_ = true;

  if (primary_app_update_failed_) {
    ReportInstallFailure(
        ChromeKioskAppInstaller::InstallResult::kPrimaryAppUpdateFailed);
  } else if (secondary_app_update_failed_) {
    ReportInstallFailure(
        ChromeKioskAppInstaller::InstallResult::kSecondaryAppUpdateFailed);
  } else {
    ReportInstallSuccess();
  }
}

void ChromeKioskAppInstaller::OnFinishCrxInstall(
    content::BrowserContext* context,
    const base::FilePath& source_file,
    const std::string& extension_id,
    const extensions::Extension* extension,
    bool success) {
  DCHECK(!install_complete_);

  SYSLOG(INFO) << (success ? "OnFinishCrxInstall succeeded for id: "
                           : "OnFinishCrxInstall failed for id: ")
               << extension_id;

  // Exit early if this is not one of the IDs we care about.
  if (!waiting_ids_.contains(extension_id)) {
    return;
  }
  waiting_ids_.erase(extension_id);

  // Also wait for updates on any shared modules the extension imports.
  if (extension != nullptr) {
    InsertPendingSharedModules(profile_.get(), waiting_ids_, *extension);
  }

  const auto* primary_app =
      FindInstalledExtension(profile_.get(), primary_app_id());

  if (!success) {
    // Primary or secondary app install failed. Abort and report the failure.
    if (primary_app == nullptr && extension_id == primary_app_id()) {
      install_observation_.Reset();
      ReportInstallFailure(InstallResult::kPrimaryAppInstallFailed);
      return;
    }
    if (primary_app != nullptr &&
        SecondaryAppsContain(*primary_app, extension_id) &&
        !IsExtensionInstalled(profile_.get(), extension_id)) {
      install_observation_.Reset();
      ReportInstallFailure(InstallResult::kSecondaryAppInstallFailed);
      return;
    }
    // Primary or secondary app update failed, but there is an installed version
    // in the `profile_`. Proceed for now and report the update failure later.
    if (primary_app != nullptr && extension_id == primary_app_id()) {
      primary_app_update_failed_ = true;
    }
    if (primary_app != nullptr &&
        SecondaryAppsContain(*primary_app, extension_id) &&
        IsExtensionInstalled(profile_.get(), extension_id)) {
      secondary_app_update_failed_ = true;
    }
  }

  // Wait for `OnFinishCrxInstall` to be called for remaining `waiting_ids_`.
  if (!waiting_ids_.empty()) {
    return;
  }

  install_observation_.Reset();

  if (primary_app == nullptr) {
    ReportInstallFailure(InstallResult::kPrimaryAppInstallFailed);
    return;
  }

  if (!extensions::KioskModeInfo::IsKioskEnabled(primary_app)) {
    ReportInstallFailure(InstallResult::kPrimaryAppNotKioskEnabled);
    return;
  }

  if (!secondary_apps_installing_) {
    MaybeInstallSecondaryApps(*primary_app);
  } else {
    MaybeCheckExtensionUpdate();
  }
}

void ChromeKioskAppInstaller::OnExtensionInstallationFailed(
    const extensions::ExtensionId& id,
    extensions::InstallStageTracker::FailureReason reason) {
  base::UmaHistogramEnumeration(kChromeKioskExtensionUpdateErrorHistogram,
                                reason);
}

void ChromeKioskAppInstaller::ReportInstallSuccess() {
  DCHECK(install_complete_);
  SYSLOG(INFO) << "Kiosk app install succeeded";

  std::move(on_ready_callback_)
      .Run(ChromeKioskAppInstaller::InstallResult::kSuccess);
}

void ChromeKioskAppInstaller::ReportInstallFailure(
    ChromeKioskAppInstaller::InstallResult error) {
  SYSLOG(ERROR) << "App install failed, error: " << static_cast<int>(error);
  DCHECK_NE(ChromeKioskAppInstaller::InstallResult::kSuccess, error);

  std::move(on_ready_callback_).Run(error);
}

void ChromeKioskAppInstaller::ObserveInstallations(
    const std::vector<extensions::ExtensionId>& ids) {
  waiting_ids_.insert(ids.begin(), ids.end());
  install_observation_.Observe(
      extensions::InstallTrackerFactory::GetForBrowserContext(&profile_.get()));
}

}  // namespace chromeos