File: webapk_install_task.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 (522 lines) | stat: -rw-r--r-- 19,963 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
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
// 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/apps/app_service/webapk/webapk_install_task.h"

#include <algorithm>
#include <utility>

#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/apps/app_service/webapk/webapk_prefs.h"
#include "chrome/browser/apps/app_service/webapk/webapk_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/web_applications/web_app_icon_manager.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_utils.h"
#include "chrome/common/chrome_switches.h"
#include "chromeos/ash/experiences/arc/mojom/webapk.mojom.h"
#include "chromeos/ash/experiences/arc/session/arc_bridge_service.h"
#include "chromeos/ash/experiences/arc/session/arc_service_manager.h"
#include "components/services/app_service/public/cpp/share_target.h"
#include "components/version_info/version_info.h"
#include "components/webapk/webapk.pb.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/storage_partition.h"
#include "google_apis/google_api_keys.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "third_party/smhasher/src/src/MurmurHash2.h"
#include "url/gurl.h"

namespace {

// The MIME type of the POST data sent to the server.
constexpr char kProtoMimeType[] = "application/x-protobuf";

constexpr char kRequesterPackageName[] = "org.chromium.arc.webapk";

const char kMinimumIconSize = 64;

// The seed to use when taking the murmur2 hash of the icon.
const uint64_t kMurmur2HashSeed = 0;

// Time to wait for a response from the Web APK minter.
constexpr base::TimeDelta kMinterResponseTimeout = base::Seconds(60);

constexpr char kWebApkServerUrl[] =
    "https://webapk.googleapis.com/v1/webApks?key=";

constexpr net::NetworkTrafficAnnotationTag kWebApksTrafficAnnotation =
    net::DefineNetworkTrafficAnnotation("webapk_minter_install_request",
                                        R"(
        semantics {
          sender: "WebAPKs"
          description:
            "Chrome OS generates small Android apps called 'WebAPKs' which "
            "represent the Progressive Web Apps installed in Chrome OS. These "
            "apps are installed in the ARC Android environment and used to "
            "improve integration between ARC and Chrome OS. This network "
            "request sends the details for a single web app to the WebAPK "
            "service, which returns details about the WebAPK to install."
          trigger: "Installing or updating a progressive web app."
          data:
            "The contents of the web app manifest for the web app, plus system "
            "information needed to generate the app."
          destination: GOOGLE_OWNED_SERVICE
          internal {
            contacts {
              email: "cros-web-apps-team@google.com"
            }
          }
          user_data {
            type: NONE
          }
          last_reviewed: "2023-01-12"
        }
        policy {
          cookies_allowed: NO
          setting: "No setting apart from disabling ARC"
          chrome_policy: {
            ArcAppToWebAppSharingEnabled: {
              ArcAppToWebAppSharingEnabled: true
            }
          }
        }
      )");

GURL GetServerUrl() {
  std::string server_url =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kWebApkServerUrl);

  if (server_url.empty()) {
    server_url = base::StrCat({kWebApkServerUrl, google_apis::GetAPIKey()});
  }

  return GURL(server_url);
}

bool DoesShareTargetDiffer(webapk::WebAppManifest manifest,
                           arc::mojom::WebShareTargetInfoPtr share_info) {
  if (!share_info) {
    // There's no |share_info| in the current WebAPK, which means that a share
    // target was added.
    return true;
  }

  // There is only one share target added.
  auto share_target = manifest.share_targets(0);
  DCHECK_EQ(manifest.share_targets_size(), 1);

  if (share_target.action() != share_info->action.value_or("") ||
      share_target.method() != share_info->method.value_or("") ||
      share_target.enctype() != share_info->enctype.value_or("")) {
    return true;
  }

  auto share_param = share_target.params();
  if (share_param.title() != share_info->param_title.value_or("") ||
      share_param.text() != share_info->param_text.value_or("") ||
      share_param.url() != share_info->param_url.value_or("")) {
    return true;
  }

  // Compare share files.
  if (share_param.files_size() !=
      static_cast<int>(share_info->file_names.size())) {
    return true;
  }

  for (int i = 0; i < share_param.files_size(); i++) {
    if (share_param.files(i).name() != share_info->file_names[i]) {
      return true;
    }

    if (share_param.files(i).accept_size() !=
        static_cast<int>(share_info->file_accepts[i].size())) {
      return true;
    }

    for (int j = 0; j < share_param.files(i).accept_size(); j++) {
      if (share_param.files(i).accept(j) != share_info->file_accepts[i][j]) {
        return true;
      }
    }
  }
  return false;
}

void AddUpdateParams(webapk::WebApk* webapk,
                     arc::mojom::WebApkInfoPtr web_apk_info) {
  webapk->set_version(web_apk_info->apk_version);
  // The |manifest_url| is used as a key on Android, so the |manifest_url| sent
  // to the server to query a particular app should always be the same.
  webapk->set_manifest_url(web_apk_info->manifest_url);
  // Any changes to web app identity which make it through to App Service will
  // have gone through an update policy check, which makes it safe to update
  // the WebAPK too.
  webapk->set_app_identity_update_supported(true);

  auto manifest = webapk->manifest();
  if (manifest.short_name() != web_apk_info->name) {
    webapk->add_update_reasons(webapk::WebApk::SHORT_NAME_DIFFERS);
  }

  if (manifest.start_url() != web_apk_info->start_url) {
    webapk->add_update_reasons(webapk::WebApk::START_URL_DIFFERS);
  }

  // There is only one scope added to the scopes list.
  DCHECK_EQ(manifest.scopes_size(), 1);
  if (manifest.scopes(0) != web_apk_info->scope) {
    webapk->add_update_reasons(webapk::WebApk::SCOPE_DIFFERS);
  }

  // There is only one icon added to the icon list.
  DCHECK_EQ(manifest.icons_size(), 1);
  if (manifest.icons(0).hash() != web_apk_info->icon_hash) {
    webapk->add_update_reasons(webapk::WebApk::PRIMARY_ICON_HASH_DIFFERS);
  }

  // Check differences in share target
  if (DoesShareTargetDiffer(manifest, std::move(web_apk_info->share_info))) {
    webapk->add_update_reasons(webapk::WebApk::WEB_SHARE_TARGET_DIFFERS);
  }
}

// Attaches icon PNG data and hash to an existing icon entry, and then
// serializes and returns the entire proto. Should be called on a worker thread.
std::optional<std::string> AddIconDataAndSerializeProto(
    std::unique_ptr<webapk::WebApk> webapk,
    std::vector<uint8_t> icon_data,
    arc::mojom::WebApkInfoPtr web_apk_info) {
  base::AssertLongCPUWorkAllowed();
  DCHECK_EQ(webapk->manifest().icons_size(), 1);

  webapk::Image* icon = webapk->mutable_manifest()->mutable_icons(0);
  if (!icon->has_image_data()) {
    icon->set_image_data(icon_data.data(), icon_data.size());

    uint64_t icon_hash =
        MurmurHash64A(icon_data.data(), icon_data.size(), kMurmur2HashSeed);
    icon->set_hash(base::NumberToString(icon_hash));
  }

  if (web_apk_info) {
    AddUpdateParams(webapk.get(), std::move(web_apk_info));
    // If we don't have an update reason here, return before we query the server
    // as there is no reason to update.
    if (webapk->update_reasons_size() == 0) {
      return std::nullopt;
    }
  }

  std::string serialized_proto;
  webapk->SerializeToString(&serialized_proto);

  return serialized_proto;
}

std::string GetArcAbi(const arc::ArcFeatures& arc_features) {
  // The property value will be a comma separated list, e.g. "x86_64,x86". The
  // highest priority will be listed first.
  return base::SplitString(arc_features.build_props.abi_list, ",",
                           base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)[0];
}

}  // namespace

namespace apps {

// Installs or updates a WebAPK.
WebApkInstallTask::WebApkInstallTask(Profile* profile,
                                     const std::string& app_id)
    : profile_(profile),
      web_app_provider_(web_app::WebAppProvider::GetForWebApps(profile_)),
      app_id_(app_id),
      package_name_to_update_(
          webapk_prefs::GetWebApkPackageName(profile_, app_id_)),
      minter_timeout_(kMinterResponseTimeout) {
  DCHECK(web_app_provider_);
}

WebApkInstallTask::~WebApkInstallTask() = default;

void WebApkInstallTask::Start(ResultCallback callback) {
  VLOG(1) << "Generating WebAPK for app: " << app_id_;
  result_callback_ = std::move(callback);

  auto& registrar = web_app_provider_->registrar_unsafe();

  // Installation & share target are already checked in WebApkManager, check
  // again in case anything changed while the install request was queued.
  // Manifest URL is always set for apps installed or updated in recent
  // versions, but might be missing for older apps.
  if (!registrar.IsInstallState(
          app_id_,
          {web_app::proto::InstallState::SUGGESTED_FROM_ANOTHER_DEVICE,
           web_app::proto::InstallState::INSTALLED_WITHOUT_OS_INTEGRATION,
           web_app::proto::InstallState::INSTALLED_WITH_OS_INTEGRATION}) ||
      !registrar.GetAppShareTarget(app_id_) ||
      registrar.GetAppManifestUrl(app_id_).is_empty()) {
    DeliverResult(WebApkInstallStatus::kAppInvalid);
    return;
  }

  std::unique_ptr<webapk::WebApk> webapk = std::make_unique<webapk::WebApk>();
  webapk->set_manifest_url(registrar.GetAppManifestUrl(app_id_).spec());
  webapk->set_requester_application_package(kRequesterPackageName);
  webapk->set_requester_application_version(
      std::string(version_info::GetVersionNumber()));

  LoadWebApkInfo(std::move(webapk));
}

void WebApkInstallTask::LoadWebApkInfo(std::unique_ptr<webapk::WebApk> webapk) {
  if (!package_name_to_update_.has_value()) {
    // This is a new install, continue with the installation process.
    webapk->add_update_reasons(webapk::WebApk::NONE);
    arc::ArcFeaturesParser::GetArcFeatures(
        base::BindOnce(&WebApkInstallTask::OnArcFeaturesLoaded,
                       weak_ptr_factory_.GetWeakPtr(), std::move(webapk)));
    return;
  }

  // If a package_name exists in webapk_prefs, this WebAPK is already installed,
  // so we need to perform an update.
  webapk->set_package_name(package_name_to_update_.value());

  // Fetch details of the existing WebAPK from ARC++.
  auto* arc_service_manager = arc::ArcServiceManager::Get();
  DCHECK(arc_service_manager);
  auto* instance = ARC_GET_INSTANCE_FOR_METHOD(
      arc_service_manager->arc_bridge_service()->webapk(), GetWebApkInfo);

  if (!instance) {
    LOG(ERROR) << "WebApkInstance is not ready";
    DeliverResult(WebApkInstallStatus::kArcUnavailable);
    return;
  }

  instance->GetWebApkInfo(
      package_name_to_update_.value(),
      base::BindOnce(&WebApkInstallTask::OnWebApkInfoLoaded,
                     weak_ptr_factory_.GetWeakPtr(), std::move(webapk)));
}

void WebApkInstallTask::OnWebApkInfoLoaded(
    std::unique_ptr<webapk::WebApk> webapk,
    arc::mojom::WebApkInfoPtr result) {
  if (!result) {
    LOG(ERROR) << "Could not load WebApkInfo";
    DeliverResult(WebApkInstallStatus::kUpdateGetWebApkInfoError);
    return;
  }

  web_apk_info_ = std::move(result);

  arc::ArcFeaturesParser::GetArcFeatures(
      base::BindOnce(&WebApkInstallTask::OnArcFeaturesLoaded,
                     weak_ptr_factory_.GetWeakPtr(), std::move(webapk)));
}

void WebApkInstallTask::OnArcFeaturesLoaded(
    std::unique_ptr<webapk::WebApk> webapk,
    std::optional<arc::ArcFeatures> arc_features) {
  if (!arc_features) {
    LOG(ERROR) << "Could not load ArcFeatures";
    DeliverResult(WebApkInstallStatus::kArcUnavailable);
    return;
  }
  webapk->set_android_abi(GetArcAbi(arc_features.value()));

  auto& icon_manager = web_app_provider_->icon_manager();
  std::optional<web_app::WebAppIconManager::IconSizeAndPurpose>
      icon_size_and_purpose = icon_manager.FindIconMatchBigger(
          app_id_, {web_app::IconPurpose::MASKABLE, web_app::IconPurpose::ANY},
          kMinimumIconSize);

  if (!icon_size_and_purpose) {
    LOG(ERROR) << "Could not find suitable icon";
    DeliverResult(WebApkInstallStatus::kAppInvalid);
    return;
  }

  // We need to send a URL for the icon, but it's possible the local image we're
  // sending has been resized and so doesn't exactly match any of the images in
  // the manifest. Since we can't be perfect, it's okay to be roughly correct
  // and just send any URL of the correct purpose.
  auto& registrar = web_app_provider_->registrar_unsafe();
  const auto& manifest_icons = registrar.GetAppIconInfos(app_id_);
  auto it = std::ranges::find_if(
      manifest_icons, [&icon_size_and_purpose](const apps::IconInfo& info) {
        return info.purpose == web_app::ManifestPurposeToIconInfoPurpose(
                                   icon_size_and_purpose->purpose);
      });

  if (it == manifest_icons.end()) {
    LOG(ERROR) << "Could not find URL for icon";
    DeliverResult(WebApkInstallStatus::kAppInvalid);
    return;
  }
  std::string icon_url = it->url.spec();

  webapk::WebAppManifest* web_app_manifest = webapk->mutable_manifest();
  PopulateWebApkManifest(profile_, app_id_, web_app_manifest);

  webapk::Image* image = web_app_manifest->add_icons();
  image->set_src(std::move(icon_url));
  image->add_purposes(icon_size_and_purpose->purpose ==
                              web_app::IconPurpose::MASKABLE
                          ? webapk::Image::MASKABLE
                          : webapk::Image::ANY);
  image->add_usages(webapk::Image::PRIMARY_ICON);

  icon_manager.ReadSmallestCompressedIcon(
      app_id_, {icon_size_and_purpose->purpose}, icon_size_and_purpose->size_px,
      base::BindOnce(&WebApkInstallTask::OnLoadedIcon,
                     weak_ptr_factory_.GetWeakPtr(), std::move(webapk)));
}

void WebApkInstallTask::OnLoadedIcon(std::unique_ptr<webapk::WebApk> webapk,
                                     web_app::IconPurpose purpose,
                                     std::vector<uint8_t> data) {
  app_short_name_ = webapk->manifest().short_name();
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::TaskPriority::BEST_EFFORT},
      base::BindOnce(AddIconDataAndSerializeProto, std::move(webapk),
                     std::move(data), std::move(web_apk_info_)),
      base::BindOnce(&WebApkInstallTask::OnProtoSerialized,
                     weak_ptr_factory_.GetWeakPtr()));
}

void WebApkInstallTask::OnProtoSerialized(
    std::optional<std::string> serialized_proto) {
  if (!serialized_proto && !serialized_proto.has_value()) {
    // We don't need to continue the update, because the existing WebAPK is up
    // to date.
    webapk_prefs::SetUpdateNeededForApp(profile_, app_id_,
                                        /* update_needed= */ false);
    DeliverResult(WebApkInstallStatus::kUpdateCancelledWebApkUpToDate);
    return;
  }
  GURL server_url = GetServerUrl();

  timer_.Start(FROM_HERE, minter_timeout_,
               base::BindOnce(&WebApkInstallTask::DeliverResult,
                              weak_ptr_factory_.GetWeakPtr(),
                              WebApkInstallStatus::kNetworkTimeout));

  auto request = std::make_unique<network::ResourceRequest>();
  request->url = server_url;
  request->method = "POST";
  request->load_flags = net::LOAD_DISABLE_CACHE;
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  auto* url_loader_factory = profile_->GetDefaultStoragePartition()
                                 ->GetURLLoaderFactoryForBrowserProcess()
                                 .get();

  url_loader_ = network::SimpleURLLoader::Create(std::move(request),
                                                 kWebApksTrafficAnnotation);
  url_loader_->AttachStringForUpload(std::move(serialized_proto.value()),
                                     kProtoMimeType);
  url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      url_loader_factory,
      base::BindOnce(&WebApkInstallTask::OnUrlLoaderComplete,
                     weak_ptr_factory_.GetWeakPtr()));
}

void WebApkInstallTask::OnUrlLoaderComplete(
    std::unique_ptr<std::string> response_body) {
  timer_.Stop();

  int response_code = -1;
  if (url_loader_->ResponseInfo() && url_loader_->ResponseInfo()->headers) {
    response_code = url_loader_->ResponseInfo()->headers->response_code();
  }

  if (!response_body || response_code != net::HTTP_OK) {
    LOG(WARNING) << "WebAPK server returned response code " << response_code;
    DeliverResult(WebApkInstallStatus::kNetworkError);
    return;
  }

  auto response = std::make_unique<webapk::WebApkResponse>();
  if (!response->ParseFromString(*response_body)) {
    LOG(WARNING) << "Failed to parse WebApkResponse proto";
    DeliverResult(WebApkInstallStatus::kNetworkError);
    return;
  }

  VLOG(1) << "Installing WebAPK: " << response->package_name();

  auto* arc_service_manager = arc::ArcServiceManager::Get();
  DCHECK(arc_service_manager);
  auto* instance = ARC_GET_INSTANCE_FOR_METHOD(
      arc_service_manager->arc_bridge_service()->webapk(), InstallWebApk);

  if (!instance) {
    LOG(ERROR) << "WebApkInstance is not ready";
    DeliverResult(WebApkInstallStatus::kArcUnavailable);
    return;
  }

  int webapk_version;
  base::StringToInt(response->version(), &webapk_version);
  instance->InstallWebApk(
      response->package_name(), webapk_version, app_short_name_,
      response->token(),
      base::BindOnce(&WebApkInstallTask::OnInstallComplete,
                     weak_ptr_factory_.GetWeakPtr(), response->package_name()));
}

void WebApkInstallTask::OnInstallComplete(
    const std::string& package_name,
    arc::mojom::WebApkInstallResult result) {
  VLOG(1) << "WebAPK installation finished with result " << result;

  const bool success = result == arc::mojom::WebApkInstallResult::kSuccess;
  const bool is_update = package_name_to_update_.has_value();
  if (success) {
    if (is_update) {
      webapk_prefs::SetUpdateNeededForApp(profile_, app_id_,
                                          /* update_needed= */ false);
    } else {
      webapk_prefs::AddWebApk(profile_, app_id_, package_name);
    }
  }

  DeliverResult(success ? WebApkInstallStatus::kSuccess
                        : WebApkInstallStatus::kGooglePlayError);
}

void WebApkInstallTask::DeliverResult(WebApkInstallStatus result) {
  // Invalidate weak pointers so that in-flight tasks cannot attempt to deliver
  // a second result.
  weak_ptr_factory_.InvalidateWeakPtrs();

  RecordWebApkInstallResult(package_name_to_update_.has_value(), result);

  DCHECK(result_callback_);
  std::move(result_callback_).Run(result == WebApkInstallStatus::kSuccess);
}

}  // namespace apps