File: load_profile.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 (439 lines) | stat: -rw-r--r-- 16,527 bytes parent folder | download | duplicates (3)
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
// 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/load_profile.h"

#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <variant>

#include "base/check_deref.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/notimplemented.h"
#include "base/notreached.h"
#include "base/sequence_checker.h"
#include "base/syslog_logging.h"
#include "base/system/sys_info.h"
#include "base/thread_annotations.h"
#include "base/types/expected.h"
#include "chrome/browser/ash/app_mode/cancellable_job.h"
#include "chrome/browser/ash/app_mode/kiosk_app_launch_error.h"
#include "chrome/browser/ash/app_mode/kiosk_app_types.h"
#include "chrome/browser/ash/app_mode/retry_runner.h"
#include "chrome/browser/ash/login/auth/chrome_login_performer.h"
#include "chrome/browser/ash/login/session/user_session_manager.h"
#include "chrome/browser/ui/ash/login/login_display_host.h"
#include "chromeos/ash/components/dbus/cryptohome/UserDataAuth.pb.h"
#include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h"
#include "chromeos/ash/components/login/auth/auth_events_recorder.h"
#include "chromeos/ash/components/login/auth/login_performer.h"
#include "chromeos/ash/components/login/auth/public/auth_failure.h"
#include "chromeos/ash/components/login/auth/public/user_context.h"
#include "components/account_id/account_id.h"
#include "components/user_manager/user_names.h"

namespace ash::kiosk {

namespace {

bool IsTestOrLinuxChromeOS() {
  // This code should only run in Chrome OS, so not `IsRunningOnChromeOS()`
  // means it's either a test or linux-chromeos.
  return !base::SysInfo::IsRunningOnChromeOS();
}

KioskAppLaunchError::Error LoginFailureToKioskLaunchError(
    const AuthFailure& error) {
  switch (error.reason()) {
    case AuthFailure::COULD_NOT_MOUNT_TMPFS:
    case AuthFailure::COULD_NOT_MOUNT_CRYPTOHOME:
      return KioskAppLaunchError::Error::kUnableToMount;
    case AuthFailure::DATA_REMOVAL_FAILED:
      return KioskAppLaunchError::Error::kUnableToRemove;
    case AuthFailure::USERNAME_HASH_FAILED:
      return KioskAppLaunchError::Error::kUnableToRetrieveHash;
    default:
      LOG(ERROR) << "KIOSK launch error because of AuthFailure::FailureReason: "
                 << error.reason();
      return KioskAppLaunchError::Error::kUnableToMount;
  }
}

CryptohomeMountState ToResult(
    std::optional<user_data_auth::IsMountedReply> reply) {
  if (!reply.has_value()) {
    return CryptohomeMountState::kServiceUnavailable;
  }
  if (IsTestOrLinuxChromeOS()) {
    // In tests and in linux-chromeos there is no real cryptohome, and the fake
    // one always replies with `is_mounted()` true. We override the reply so
    // Kiosk login can proceed.
    return CryptohomeMountState::kNotMounted;
  }
  return reply->is_mounted() ? CryptohomeMountState::kMounted
                             : CryptohomeMountState::kNotMounted;
}

void CheckCryptohomeMountState(CryptohomeMountStateCallback on_done) {
  UserDataAuthClient::Get()->WaitForServiceToBeAvailable(base::BindOnce(
      [](CryptohomeMountStateCallback on_done, bool service_is_ready) {
        if (!service_is_ready || !UserDataAuthClient::Get()) {
          return std::move(on_done).Run(
              CryptohomeMountState::kServiceUnavailable);
        }

        UserDataAuthClient::Get()->IsMounted(
            user_data_auth::IsMountedRequest(),
            base::BindOnce(&ToResult).Then(std::move(on_done)));
      },
      std::move(on_done)));
}

// Checks the mount state of cryptohome and retries if the cryptohome service is
// not yet available.
std::unique_ptr<CancellableJob> CheckCryptohome(
    CryptohomeMountStateCallback on_done) {
  return RunUpToNTimes<CryptohomeMountState>(
      /*n=*/5,
      /*job=*/base::BindRepeating(&CheckCryptohomeMountState),
      /*should_retry=*/
      base::BindRepeating([](const CryptohomeMountState& result) {
        return result == CryptohomeMountState::kServiceUnavailable;
      }),
      std::move(on_done));
}

class SigninPerformer : public LoginPerformer::Delegate, public CancellableJob {
 public:
  static std::unique_ptr<CancellableJob> Run(
      KioskAppType app_type,
      AccountId account_id,
      PerformSigninResultCallback on_done) {
    auto handle = base::WrapUnique(new SigninPerformer(std::move(on_done)));

    switch (app_type) {
      case KioskAppType::kChromeApp:
        handle->login_performer_->LoginAsKioskAccount(account_id);
        break;
      case KioskAppType::kWebApp:
        handle->login_performer_->LoginAsWebKioskAccount(account_id);
        break;
      case KioskAppType::kIsolatedWebApp:
        handle->login_performer_->LoginAsIwaKioskAccount(account_id);
        break;
      case KioskAppType::kArcvmApp:
        // TODO(crbug.com/388602323): Add profile load and login.
        NOTIMPLEMENTED();
        break;
    }

    return handle;
  }

  SigninPerformer(const SigninPerformer&) = delete;
  SigninPerformer& operator=(const SigninPerformer&) = delete;
  ~SigninPerformer() override = default;

 private:
  explicit SigninPerformer(PerformSigninResultCallback on_done)
      : on_done_(std::move(on_done)),
        login_performer_(std::make_unique<ChromeLoginPerformer>(
            this,
            AuthEventsRecorder::Get())) {}

  // LoginPerformer::Delegate overrides:
  void OnAuthSuccess(const UserContext& user_context) override {
    // `LoginPerformer` manages its own lifecycle on success, release ownership.
    login_performer_->set_delegate(nullptr);
    std::ignore = login_performer_.release();

    std::move(on_done_).Run(user_context);
  }
  void OnAuthFailure(const AuthFailure& auth_error) override {
    KioskAppLaunchError::SaveCryptohomeFailure(auth_error);
    std::move(on_done_).Run(base::unexpected(auth_error));
  }
  void PolicyLoadFailed() override {
    std::move(on_done_).Run(
        base::unexpected(PerformSigninError::kPolicyLoadFailed));
  }
  void AllowlistCheckFailed(const std::string& email) override {
    std::move(on_done_).Run(
        base::unexpected(PerformSigninError::kAllowlistCheckFailed));
  }
  void OnOldEncryptionDetected(std::unique_ptr<UserContext> user_context,
                               bool has_incomplete_migration) override {
    NOTREACHED();
  }

  PerformSigninResultCallback on_done_;
  std::unique_ptr<LoginPerformer> login_performer_;
};

bool IsRetriableError(const PerformSigninResult& result) {
  if (!result.has_value() &&
      std::holds_alternative<AuthFailure>(result.error())) {
    // Signal a retriable error if the cryptohome mount failed due to
    // corruption of the on-disk state. We always ask to "create" cryptohome
    // and the corrupted one was deleted under the hood.
    return std::get<AuthFailure>(result.error()).reason() ==
           AuthFailure::UNRECOVERABLE_CRYPTOHOME;
  }
  return false;
}

std::unique_ptr<CancellableJob> Signin(KioskAppType app_type,
                                       AccountId account_id,
                                       PerformSigninResultCallback on_done) {
  return RunUpToNTimes<PerformSigninResult>(
      /*n=*/3,
      /*job=*/
      base::BindRepeating(
          [](KioskAppType app_type, AccountId account_id,
             RetryResultCallback<PerformSigninResult> on_result) {
            return SigninPerformer::Run(app_type, account_id,
                                        std::move(on_result));
          },
          app_type, account_id),
      /*should_retry=*/base::BindRepeating(&IsRetriableError),
      /*on_done=*/
      std::move(on_done));
}

KioskAppLaunchError::Error SigninErrorToKioskLaunchError(
    PerformSigninError error) {
  switch (error) {
    case PerformSigninError::kPolicyLoadFailed:
      return KioskAppLaunchError::Error::kPolicyLoadFailed;
    case PerformSigninError::kAllowlistCheckFailed:
      return KioskAppLaunchError::Error::kUserNotAllowlisted;
  }
}

class SessionStarter : public CancellableJob,
                       public UserSessionManagerDelegate {
 public:
  static std::unique_ptr<CancellableJob> Run(
      const UserContext& user_context,
      StartSessionResultCallback on_done) {
    auto handle = base::WrapUnique(new SessionStarter(std::move(on_done)));
    UserSessionManager::GetInstance()->StartSession(
        user_context, UserSessionManager::StartSessionType::kPrimary,
        /*has_auth_cookies=*/false,
        /*has_active_session=*/false,
        /*delegate=*/handle->weak_ptr_factory_.GetWeakPtr());
    return handle;
  }

  SessionStarter(const SessionStarter&) = delete;
  SessionStarter& operator=(const SessionStarter&) = delete;
  ~SessionStarter() override = default;

 private:
  explicit SessionStarter(StartSessionResultCallback on_done)
      : on_done_(std::move(on_done)) {}

  // UserSessionManagerDelegate implementation:
  void OnProfilePrepared(Profile* profile, bool browser_launched) override {
    std::move(on_done_).Run(CHECK_DEREF(profile));
  }

  base::WeakPtr<UserSessionManagerDelegate> AsWeakPtr() override {
    return weak_ptr_factory_.GetWeakPtr();
  }

  StartSessionResultCallback on_done_;
  base::WeakPtrFactory<SessionStarter> weak_ptr_factory_{this};
};

void LogErrorToSyslog(KioskAppLaunchError::Error error) {
  switch (error) {
    case KioskAppLaunchError::Error::kCryptohomedNotRunning:
      SYSLOG(ERROR) << "Cryptohome not available when loading Kiosk profile.";
      break;
    case KioskAppLaunchError::Error::kAlreadyMounted:
      SYSLOG(ERROR) << "Cryptohome already mounted when loading Kiosk profile.";
      break;
    case KioskAppLaunchError::Error::kUserNotAllowlisted:
      SYSLOG(ERROR) << "LoginPerformer disallowed Kiosk user sign in.";
      break;
    default:
      SYSLOG(ERROR) << "Unexpected error " << (int)error;
  }
}

// Helper class that implements the functionality of `LoadProfile`.
// See docs on that function for more information.
class ProfileLoader : public CancellableJob {
 public:
  static std::unique_ptr<CancellableJob> Run(
      const AccountId& app_account_id,
      KioskAppType app_type,
      CheckCryptohomeCallback check_cryptohome,
      PerformSigninCallback perform_signin,
      StartSessionCallback start_session,
      LoadProfileResultCallback on_done);

  ProfileLoader(const ProfileLoader&) = delete;
  ProfileLoader& operator=(const ProfileLoader&) = delete;
  ~ProfileLoader() override;

 private:
  ProfileLoader(const AccountId& app_account_id,
                KioskAppType app_type,
                CheckCryptohomeCallback check_cryptohome,
                PerformSigninCallback perform_signin,
                StartSessionCallback start_session,
                LoadProfileResultCallback on_done);

  void CheckCryptohomeIsNotMounted();
  void DidCheckCryptohomeIsNotMounted(CryptohomeMountState result);
  void LoginAsKioskAccount();
  void DidLoginAsKioskAccount(PerformSigninResult result);
  void PrepareProfile(const UserContext& user_context);
  void ReturnSuccess(Profile& profile);
  void ReturnError(KioskAppLaunchError::Error result);

  const AccountId account_id_;
  const KioskAppType app_type_;

  // `current_step_` is a handle to the job currently being executed. The
  // possible steps are listed in the callbacks below.
  std::unique_ptr<CancellableJob> current_step_
      GUARDED_BY_CONTEXT(sequence_checker_);
  CheckCryptohomeCallback check_cryptohome_;
  PerformSigninCallback perform_signin_;
  StartSessionCallback start_session_;

  LoadProfileResultCallback on_done_ GUARDED_BY_CONTEXT(sequence_checker_);

  SEQUENCE_CHECKER(sequence_checker_);
  base::WeakPtrFactory<ProfileLoader> weak_ptr_factory_{this};
};

std::unique_ptr<CancellableJob> ProfileLoader::Run(
    const AccountId& app_account_id,
    KioskAppType app_type,
    CheckCryptohomeCallback check_cryptohome,
    PerformSigninCallback perform_signin,
    StartSessionCallback start_session,
    LoadProfileResultCallback on_done) {
  auto loader = base::WrapUnique(new ProfileLoader(
      app_account_id, app_type, std::move(check_cryptohome),
      std::move(perform_signin), std::move(start_session), std::move(on_done)));
  loader->CheckCryptohomeIsNotMounted();
  return loader;
}

ProfileLoader::ProfileLoader(const AccountId& app_account_id,
                             KioskAppType app_type,
                             CheckCryptohomeCallback check_cryptohome,
                             PerformSigninCallback perform_signin,
                             StartSessionCallback start_session,
                             LoadProfileResultCallback on_done)
    : account_id_(app_account_id),
      app_type_(app_type),
      check_cryptohome_(std::move(check_cryptohome)),
      perform_signin_(std::move(perform_signin)),
      start_session_(std::move(start_session)),
      on_done_(std::move(on_done)) {}

ProfileLoader::~ProfileLoader() = default;

void ProfileLoader::CheckCryptohomeIsNotMounted() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  current_step_ =
      std::move(check_cryptohome_)
          .Run(base::BindOnce(&ProfileLoader::DidCheckCryptohomeIsNotMounted,
                              weak_ptr_factory_.GetWeakPtr()));
}

void ProfileLoader::DidCheckCryptohomeIsNotMounted(
    CryptohomeMountState result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  switch (result) {
    case CryptohomeMountState::kNotMounted:
      return LoginAsKioskAccount();
    case CryptohomeMountState::kMounted:
      return ReturnError(KioskAppLaunchError::Error::kAlreadyMounted);
    case CryptohomeMountState::kServiceUnavailable:
      return ReturnError(KioskAppLaunchError::Error::kCryptohomedNotRunning);
  }
}

void ProfileLoader::LoginAsKioskAccount() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  current_step_ =
      std::move(perform_signin_)
          .Run(app_type_, account_id_,
               /*on_done=*/
               base::BindOnce(&ProfileLoader::DidLoginAsKioskAccount,
                              weak_ptr_factory_.GetWeakPtr()));
}

void ProfileLoader::DidLoginAsKioskAccount(PerformSigninResult result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (result.has_value()) {
    return PrepareProfile(result.value());
  } else if (auto* error = std::get_if<PerformSigninError>(&result.error())) {
    return ReturnError(SigninErrorToKioskLaunchError(*error));
  } else if (auto* auth_failure = std::get_if<AuthFailure>(&result.error())) {
    return ReturnError(LoginFailureToKioskLaunchError(*auth_failure));
  }
  NOTREACHED();
}

void ProfileLoader::PrepareProfile(const UserContext& user_context) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  current_step_ = std::move(start_session_)
                      .Run(user_context,
                           /*on_done=*/
                           base::BindOnce(&ProfileLoader::ReturnSuccess,
                                          weak_ptr_factory_.GetWeakPtr()));
}

void ProfileLoader::ReturnSuccess(Profile& profile) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  current_step_.reset();
  std::move(on_done_).Run(&profile);
}

void ProfileLoader::ReturnError(KioskAppLaunchError::Error result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  current_step_.reset();
  LogErrorToSyslog(result);
  std::move(on_done_).Run(base::unexpected(std::move(result)));
}

}  // namespace

std::unique_ptr<CancellableJob> LoadProfile(const AccountId& app_account_id,
                                            KioskAppType app_type,
                                            LoadProfileResultCallback on_done) {
  return LoadProfileWithCallbacks(
      app_account_id, app_type, base::BindOnce(&CheckCryptohome),
      base::BindOnce(&Signin), base::BindOnce(&SessionStarter::Run),
      std::move(on_done));
}

std::unique_ptr<CancellableJob> LoadProfileWithCallbacks(
    const AccountId& app_account_id,
    KioskAppType app_type,
    CheckCryptohomeCallback check_cryptohome,
    PerformSigninCallback perform_signin,
    StartSessionCallback start_session,
    LoadProfileResultCallback on_done) {
  return ProfileLoader::Run(
      app_account_id, app_type, std::move(check_cryptohome),
      std::move(perform_signin), std::move(start_session), std::move(on_done));
}

}  // namespace ash::kiosk