File: install_app_from_verified_manifest_command.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 (293 lines) | stat: -rw-r--r-- 11,956 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
// Copyright 2024 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/web_applications/commands/install_app_from_verified_manifest_command.h"

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

#include "base/check_is_test.h"
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_set.h"
#include "base/containers/flat_tree.h"
#include "base/functional/bind.h"
#include "base/strings/to_string.h"
#include "chrome/browser/web_applications/commands/command_metrics.h"
#include "chrome/browser/web_applications/locks/shared_web_contents_lock.h"
#include "chrome/browser/web_applications/locks/shared_web_contents_with_app_lock.h"
#include "chrome/browser/web_applications/locks/web_app_lock_manager.h"
#include "chrome/browser/web_applications/mojom/user_display_mode.mojom.h"
#include "chrome/browser/web_applications/web_app_command_manager.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/browser/web_applications/web_app_icon_operations.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/browser/web_applications/web_app_install_params.h"
#include "chrome/browser/web_applications/web_app_install_utils.h"
#include "chrome/browser/web_applications/web_contents/web_contents_manager.h"
#include "components/webapps/browser/install_result_code.h"
#include "components/webapps/browser/installable/installable_metrics.h"
#include "components/webapps/browser/web_contents/web_app_url_loader.h"
#include "components/webapps/common/web_app_id.h"
#include "content/public/browser/web_contents.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/url_util.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/common/manifest/manifest_util.h"
#include "third_party/blink/public/mojom/manifest/manifest.mojom.h"
#include "third_party/blink/public/mojom/manifest/manifest_manager.mojom.h"
#include "url/url_constants.h"

namespace web_app {

namespace {

// TODO(crbug.com/40273612): Figure out why tests fail when removing
// 127.0.0.1 even though that was added only for Lacros testing and hence
// shouldn't be needed anymore.
constexpr auto kHostAllowlist = base::MakeFixedFlatSet<std::string_view>(
    {"googleusercontent.com", "gstatic.com", "youtube.com",
     "127.0.0.1" /*FOR TESTING*/});

bool HasRequiredManifestFields(const blink::mojom::ManifestPtr& manifest) {
  if (!manifest->has_valid_specified_start_url) {
    return false;
  }

  if (!manifest->short_name.has_value() && !manifest->name.has_value()) {
    return false;
  }

  return true;
}

}  // namespace

InstallAppFromVerifiedManifestCommand::InstallAppFromVerifiedManifestCommand(
    webapps::WebappInstallSource install_source,
    GURL document_url,
    GURL verified_manifest_url,
    std::string verified_manifest_contents,
    webapps::AppId expected_id,
    bool is_diy_app,
    std::optional<WebAppInstallParams> install_params,
    OnceInstallCallback callback)
    : WebAppCommand<SharedWebContentsLock,
                    const webapps::AppId&,
                    webapps::InstallResultCode>(
          "InstallAppFromVerifiedManifestCommand",
          SharedWebContentsLockDescription(),
          std::move(callback),
          /*args_for_shutdown=*/
          std::make_tuple(webapps::AppId(),
                          webapps::InstallResultCode::
                              kCancelledOnWebAppProviderShuttingDown)),
      install_source_(install_source),
      document_url_(std::move(document_url)),
      verified_manifest_url_(std::move(verified_manifest_url)),
      verified_manifest_contents_(std::move(verified_manifest_contents)),
      expected_id_(std::move(expected_id)),
      is_diy_app_(is_diy_app),
      install_params_(std::move(install_params)) {
  if (install_params_) {
    // Not every `install_params` option has an effect, check that unused params
    // are not set.
    CHECK_EQ(install_params->install_state,
             proto::InstallState::INSTALLED_WITH_OS_INTEGRATION);
    CHECK(install_params->fallback_start_url.is_empty());
    CHECK(!install_params->fallback_app_name.has_value());
  }

  GetMutableDebugValue().Set("document_url", document_url_.spec());
  GetMutableDebugValue().Set("verified_manifest_url",
                             verified_manifest_url_.spec());
  GetMutableDebugValue().Set("expected_id", expected_id_);
  GetMutableDebugValue().Set("verified_manifest_contents",
                             verified_manifest_contents_);
  GetMutableDebugValue().Set("has_install_params", !!install_params_);
}

InstallAppFromVerifiedManifestCommand::
    ~InstallAppFromVerifiedManifestCommand() = default;

void InstallAppFromVerifiedManifestCommand::StartWithLock(
    std::unique_ptr<SharedWebContentsLock> lock) {
  web_contents_lock_ = std::move(lock);

  url_loader_ = web_contents_lock_->web_contents_manager().CreateUrlLoader();
  data_retriever_ =
      web_contents_lock_->web_contents_manager().CreateDataRetriever();
  url_loader_->LoadUrl(
      GURL(url::kAboutBlankURL), &web_contents_lock_->shared_web_contents(),
      webapps::WebAppUrlLoader::UrlComparison::kExact,
      base::BindOnce(&InstallAppFromVerifiedManifestCommand::OnAboutBlankLoaded,
                     weak_ptr_factory_.GetWeakPtr()));
}

void InstallAppFromVerifiedManifestCommand::OnAboutBlankLoaded(
    webapps::WebAppUrlLoaderResult result) {
  if (result != webapps::WebAppUrlLoaderResult::kUrlLoaded) {
    Abort(CommandResult::kFailure,
          webapps::InstallResultCode::kInstallURLLoadFailed);
    return;
  }

  // The shared web contents must have been reset to about:blank before command
  // execution.
  DCHECK_EQ(web_contents_lock_->shared_web_contents().GetURL(),
            GURL(url::kAboutBlankURL));

  web_contents_lock_->shared_web_contents()
      .GetPrimaryMainFrame()
      ->GetRemoteInterfaces()
      ->GetInterface(manifest_manager_.BindNewPipeAndPassReceiver());
  manifest_manager_.set_disconnect_handler(
      base::BindOnce(&InstallAppFromVerifiedManifestCommand::Abort,
                     weak_ptr_factory_.GetWeakPtr(), CommandResult::kFailure,
                     webapps::InstallResultCode::kWebContentsDestroyed));

  manifest_manager_->ParseManifestFromString(
      document_url_, verified_manifest_url_, verified_manifest_contents_,
      base::BindOnce(&InstallAppFromVerifiedManifestCommand::OnManifestParsed,
                     weak_ptr_factory_.GetWeakPtr()));
}

void InstallAppFromVerifiedManifestCommand::OnManifestParsed(
    blink::mojom::ManifestPtr manifest) {
  // Note that most errors during parsing (e.g. errors to do with parsing a
  // particular field) are silently ignored. As long as the manifest is valid
  // JSON and contains a valid start_url and name, installation will proceed.
  if (blink::IsEmptyManifest(manifest) ||
      !HasRequiredManifestFields(manifest)) {
    Abort(CommandResult::kFailure,
          webapps::InstallResultCode::kNotValidManifestForWebApp);
    return;
  }

  if (manifest->manifest_url != verified_manifest_url_) {
    mojo::ReportBadMessage("Returned manifest has incorrect manifest URL");
    Abort(CommandResult::kFailure,
          webapps::InstallResultCode::kNotValidManifestForWebApp);
    return;
  }

  GetMutableDebugValue().Set("manifest_parsed", true);
  web_app_info_ =
      std::make_unique<WebAppInstallInfo>(manifest->id, manifest->start_url);
  web_app_info_->user_display_mode = mojom::UserDisplayMode::kStandalone;
  web_app_info_->is_diy_app = is_diy_app_;

  UpdateWebAppInfoFromManifest(*manifest, web_app_info_.get());

  if (install_params_) {
    // TODO(crbug.com/354981650): Remove this call.
    ApplyParamsToWebAppInstallInfo(*install_params_, *web_app_info_);
  }

  IconUrlSizeSet icon_urls = GetValidIconUrlsToDownload(*web_app_info_);
  base::EraseIf(icon_urls, [](const IconUrlWithSize& url_with_size) {
    for (const auto& allowed_host : kHostAllowlist) {
      const GURL& icon_url = url_with_size.url;
      if (icon_url.DomainIs(allowed_host)) {
        // Found a match, don't erase this url!
        return false;
      }
    }
    // No matches, erase this url!
    return true;
  });

  if (icon_urls.empty()) {
    // Abort if there are no icons to download, so we can distinguish this case
    // from having icons but failing to download them.
    Abort(CommandResult::kFailure,
          webapps::InstallResultCode::kNoValidIconsInManifest);
    return;
  }

  data_retriever_->GetIcons(
      &web_contents_lock_->shared_web_contents(), std::move(icon_urls),
      /*skip_page_favicons=*/true,
      /*fail_all_if_any_fail=*/false,
      base::BindOnce(&InstallAppFromVerifiedManifestCommand::OnIconsRetrieved,
                     weak_ptr_factory_.GetWeakPtr()));
}

void InstallAppFromVerifiedManifestCommand::OnIconsRetrieved(
    IconsDownloadedResult result,
    IconsMap icons_map,
    DownloadedIconsHttpResults icons_http_results) {
  DCHECK(web_app_info_);

  PopulateProductIcons(web_app_info_.get(), &icons_map);
  if (web_app_info_->is_generated_icon) {
    // PopulateProductIcons sets is_generated_icon if it had to generate a
    // product icon due a lack of successfully downloaded product icons. In
    // this case, abort the installation and report the error.
    Abort(CommandResult::kFailure,
          webapps::InstallResultCode::kIconDownloadingFailed);
    return;
  }

  PopulateOtherIcons(web_app_info_.get(), icons_map);

  webapps::AppId app_id =
      GenerateAppIdFromManifestId(web_app_info_->manifest_id());

  if (app_id != expected_id_) {
    Abort(CommandResult::kFailure,
          webapps::InstallResultCode::kExpectedAppIdCheckFailed);
    return;
  }

  app_lock_ = std::make_unique<SharedWebContentsWithAppLock>();
  command_manager()->lock_manager().UpgradeAndAcquireLock(
      std::move(web_contents_lock_), *app_lock_, {app_id},
      base::BindOnce(&InstallAppFromVerifiedManifestCommand::OnAppLockAcquired,
                     weak_ptr_factory_.GetWeakPtr()));
}

void InstallAppFromVerifiedManifestCommand::OnAppLockAcquired() {
  CHECK(app_lock_);
  CHECK(app_lock_->IsGranted());
  WebAppInstallFinalizer::FinalizeOptions finalize_options(install_source_);
  finalize_options.add_to_quick_launch_bar = false;
  finalize_options.overwrite_existing_manifest_fields = false;

  if (install_params_) {
    ApplyParamsToFinalizeOptions(*install_params_, finalize_options);
  }

  // TODO(crbug.com/40197834): apply host_allowlist instead of disabling origin
  // association validate for all origins.
  finalize_options.skip_origin_association_validation = true;

  app_lock_->install_finalizer().FinalizeInstall(
      *web_app_info_, finalize_options,
      base::BindOnce(&InstallAppFromVerifiedManifestCommand::OnInstallFinalized,
                     weak_ptr_factory_.GetWeakPtr()));
}

void InstallAppFromVerifiedManifestCommand::OnInstallFinalized(
    const webapps::AppId& app_id,
    webapps::InstallResultCode code) {
  GetMutableDebugValue().Set("error_code", base::ToString(code));
  RecordInstallMetrics(InstallCommand::kInstallAppFromVerifiedManifest,
                       WebAppType::kCraftedApp, code, install_source_);
  CompleteAndSelfDestruct(webapps::IsSuccess(code) ? CommandResult::kSuccess
                                                   : CommandResult::kFailure,
                          app_id, code);
}

void InstallAppFromVerifiedManifestCommand::Abort(
    CommandResult result,
    webapps::InstallResultCode code) {
  GetMutableDebugValue().Set("error_code", base::ToString(code));
  RecordInstallMetrics(InstallCommand::kInstallAppFromVerifiedManifest,
                       WebAppType::kCraftedApp, code, install_source_);
  CompleteAndSelfDestruct(result, webapps::AppId(), code);
}

}  // namespace web_app