File: authentication_dialog_unittest.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (226 lines) | stat: -rw-r--r-- 8,248 bytes parent folder | download
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
// 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 "ash/in_session_auth/authentication_dialog.h"

#include "ash/public/cpp/in_session_auth_token_provider.h"
#include "ash/public/cpp/test/mock_in_session_auth_token_provider.h"
#include "ash/test/ash_test_base.h"
#include "base/logging.h"
#include "base/test/bind.h"
#include "base/unguessable_token.h"
#include "chromeos/ash/components/cryptohome/common_types.h"
#include "chromeos/ash/components/cryptohome/cryptohome_parameters.h"
#include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h"
#include "chromeos/ash/components/login/auth/auth_performer.h"
#include "chromeos/ash/components/login/auth/mock_auth_performer.h"
#include "chromeos/ash/components/login/auth/public/authentication_error.h"
#include "chromeos/ash/components/login/auth/public/cryptohome_key_constants.h"
#include "chromeos/ash/components/login/auth/public/session_auth_factors.h"
#include "chromeos/ash/components/osauth/public/common_types.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/strings/ascii.h"
#include "ui/events/keycodes/keyboard_codes_posix.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/textfield/textfield.h"

namespace ash {

namespace {

using ::cryptohome::KeyLabel;
using ::testing::_;

const char kTestAccount[] = "user@test.com";
const char kExpectedPassword[] = "qwerty";
AuthProofToken kToken = "auth-proof-token";

}  // namespace

class AuthenticationDialogTest : public AshTestBase {
 public:
  AuthenticationDialogTest() = default;

  void SetUp() override {
    AshTestBase::SetUp();
    UserDataAuthClient::InitializeFake();
    auth_token_provider_ = std::make_unique<MockInSessionAuthTokenProvider>();
  }

  void StartAuthSession(std::unique_ptr<UserContext> user_context,
                        bool /*ephemeral*/,
                        AuthSessionIntent /*intent*/,
                        AuthPerformer::StartSessionCallback callback) {
    cryptohome::AuthFactorRef ref{cryptohome::AuthFactorType::kPassword,
                                  KeyLabel(kCryptohomeGaiaKeyLabel)};
    cryptohome::AuthFactorCommonMetadata metadata{};
    cryptohome::AuthFactor factor{std::move(ref), std::move(metadata)};
    user_context->SetSessionAuthFactors(
        SessionAuthFactors{{std::move(factor)}});
    std::move(callback).Run(true, std::move(user_context), absl::nullopt);
  }

  void GetAuthToken(std::unique_ptr<UserContext> user_context,
                    InSessionAuthTokenProvider::OnAuthTokenGenerated callback) {
    std::move(callback).Run(kToken, base::Minutes(5));
  }

 protected:
  void CreateAndShowDialog() {
    auto auth_performer =
        std::make_unique<MockAuthPerformer>(UserDataAuthClient::Get());
    auth_performer_ = auth_performer.get();

    EXPECT_CALL(*auth_performer_, StartAuthSession)
        .WillRepeatedly(
            testing::Invoke(this, &AuthenticationDialogTest::StartAuthSession));

    // `dialog_` is a `DialogDelegateView` and will be owned by the
    // underlying widget.
    dialog_ = new AuthenticationDialog(
        base::BindLambdaForTesting([&](bool success,
                                       const AuthProofToken& token,
                                       base::TimeDelta timeout) {
          success_ = success;
          token_ = token;
        }),
        auth_token_provider_.get(), std::move(auth_performer),
        AccountId::FromUserEmail(kTestAccount));

    test_api_ = std::make_unique<AuthenticationDialog::TestApi>(dialog_);

    dialog_->Show();
  }

  void TypePassword(const std::string& password) {
    auto* generator = GetEventGenerator();
    generator->MoveMouseTo(
        test_api_->GetPasswordTextfield()->GetBoundsInScreen().CenterPoint());
    generator->ClickLeftButton();

    for (char c : password) {
      EXPECT_TRUE(absl::ascii_isalpha(static_cast<unsigned char>(c)));
      generator->PressAndReleaseKey(
          static_cast<ui::KeyboardCode>(ui::KeyboardCode::VKEY_A + (c - 'a')),
          ui::EF_NONE);
    }
  }

  void PressOkButton() {
    auto* generator = GetEventGenerator();
    generator->MoveMouseTo(
        dialog_->GetOkButton()->GetBoundsInScreen().CenterPoint());
    generator->ClickLeftButton();
  }

  absl::optional<bool> success_;
  AuthProofToken token_;
  raw_ptr<AuthenticationDialog, AcrossTasksDanglingUntriaged> dialog_;
  std::unique_ptr<MockInSessionAuthTokenProvider> auth_token_provider_;
  raw_ptr<MockAuthPerformer, AcrossTasksDanglingUntriaged> auth_performer_;
  std::unique_ptr<AuthenticationDialog::TestApi> test_api_;
};

TEST_F(AuthenticationDialogTest, CallbackCalledOnCancel) {
  CreateAndShowDialog();
  dialog_->Cancel();
  EXPECT_TRUE(success_.has_value());
  EXPECT_EQ(success_.value(), false);
}

TEST_F(AuthenticationDialogTest, CallbackCalledOnClose) {
  CreateAndShowDialog();
  dialog_->Close();
  EXPECT_TRUE(success_.has_value());
  EXPECT_EQ(success_.value(), false);
}

TEST_F(AuthenticationDialogTest, CorrectPasswordProvided) {
  CreateAndShowDialog();
  TypePassword(kExpectedPassword);

  EXPECT_CALL(*auth_performer_,
              AuthenticateWithPassword(kCryptohomeGaiaKeyLabel,
                                       kExpectedPassword, _, _))
      .WillOnce([](const std::string& key_label, const std::string& password,
                   std::unique_ptr<UserContext> user_context,
                   AuthOperationCallback callback) {
        std::move(callback).Run(std::move(user_context), absl::nullopt);
      });

  EXPECT_CALL(*auth_token_provider_, ExchangeForToken)
      .WillOnce(testing::Invoke(this, &AuthenticationDialogTest::GetAuthToken));

  PressOkButton();

  EXPECT_TRUE(success_.has_value());
  EXPECT_TRUE(success_.value());
  EXPECT_EQ(token_, kToken);
}

TEST_F(AuthenticationDialogTest, IncorrectPasswordProvidedThenCorrect) {
  CreateAndShowDialog();
  TypePassword("ytrewq");

  EXPECT_CALL(*auth_performer_,
              AuthenticateWithPassword(kCryptohomeGaiaKeyLabel, _, _, _))
      .WillRepeatedly([](const std::string& key_label,
                         const std::string& password,
                         std::unique_ptr<UserContext> user_context,
                         AuthOperationCallback callback) {
        std::move(callback).Run(
            std::move(user_context),
            password == kExpectedPassword
                ? absl::nullopt
                : absl::optional<AuthenticationError>{AuthenticationError{
                      user_data_auth::
                          CRYPTOHOME_ERROR_AUTHORIZATION_KEY_NOT_FOUND}});
      });

  PressOkButton();
  TypePassword(kExpectedPassword);

  EXPECT_CALL(*auth_token_provider_, ExchangeForToken)
      .WillOnce(testing::Invoke(this, &AuthenticationDialogTest::GetAuthToken));

  PressOkButton();

  EXPECT_TRUE(success_.has_value());
  EXPECT_TRUE(success_.value());
  EXPECT_EQ(token_, kToken);
}

TEST_F(AuthenticationDialogTest, AuthSessionRestartedWhenExpired) {
  CreateAndShowDialog();
  TypePassword(kExpectedPassword);

  int number_of_calls = 0;
  EXPECT_CALL(*auth_performer_,
              AuthenticateWithPassword(kCryptohomeGaiaKeyLabel,
                                       kExpectedPassword, _, _))
      .WillRepeatedly([&number_of_calls](
                          const std::string& key_label,
                          const std::string& password,
                          std::unique_ptr<UserContext> user_context,
                          AuthOperationCallback callback) {
        std::move(callback).Run(
            std::move(user_context),
            number_of_calls++
                ? absl::nullopt
                : absl::optional<AuthenticationError>{AuthenticationError{
                      user_data_auth::CRYPTOHOME_INVALID_AUTH_SESSION_TOKEN}});
      });

  EXPECT_CALL(*auth_token_provider_, ExchangeForToken)
      .WillOnce(testing::Invoke(this, &AuthenticationDialogTest::GetAuthToken));

  PressOkButton();

  EXPECT_TRUE(success_.has_value());
  EXPECT_TRUE(success_.value());
  EXPECT_EQ(token_, kToken);
}

}  // namespace ash