File: oauth_token_getter_impl.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 (312 lines) | stat: -rw-r--r-- 11,012 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
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/base/oauth_token_getter_impl.h"

#include <memory>
#include <utility>

#include "base/containers/queue.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/strings/string_util.h"
#include "google_apis/google_api_keys.h"
#include "remoting/base/logging.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"

namespace remoting {

namespace {

// Maximum number of retries on network/500 errors.
const int kMaxRetries = 3;

// Time when we we try to update OAuth token before its expiration.
const int kTokenUpdateTimeBeforeExpirySeconds = 120;

// Max time we wait for the response before giving up.
constexpr base::TimeDelta kResponseTimeoutDuration = base::Seconds(30);

}  // namespace

OAuthTokenGetterImpl::OAuthTokenGetterImpl(
    std::unique_ptr<OAuthIntermediateCredentials> intermediate_credentials,
    const OAuthTokenGetter::CredentialsUpdatedCallback& on_credentials_update,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    bool auto_refresh)
    : url_loader_factory_(url_loader_factory),
      intermediate_credentials_(std::move(intermediate_credentials)),
      gaia_oauth_client_(new gaia::GaiaOAuthClient(url_loader_factory)),
      credentials_updated_callback_(on_credentials_update) {
  if (auto_refresh) {
    refresh_timer_ = std::make_unique<base::OneShotTimer>();
  }
}

OAuthTokenGetterImpl::OAuthTokenGetterImpl(
    std::unique_ptr<OAuthAuthorizationCredentials> authorization_credentials,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    bool auto_refresh)
    : url_loader_factory_(url_loader_factory),
      authorization_credentials_(std::move(authorization_credentials)),
      gaia_oauth_client_(new gaia::GaiaOAuthClient(url_loader_factory)) {
  if (auto_refresh) {
    refresh_timer_ = std::make_unique<base::OneShotTimer>();
  }
}

OAuthTokenGetterImpl::~OAuthTokenGetterImpl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void OAuthTokenGetterImpl::OnGetTokensResponse(const std::string& refresh_token,
                                               const std::string& access_token,
                                               int expires_seconds) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(intermediate_credentials_);
  VLOG(1) << "Received OAuth tokens.";

  // Update the access token and any other auto-update timers.
  UpdateAccessToken(access_token, expires_seconds);

  // Keep the refresh token in the authorization_credentials.
  authorization_credentials_ =
      std::make_unique<OAuthTokenGetter::OAuthAuthorizationCredentials>(

          std::string(), refresh_token,
          intermediate_credentials_->is_service_account);

  // Clear out the one time use token.
  intermediate_credentials_.reset();

  // At this point we don't know the email address so we need to fetch it.
  email_discovery_ = true;
  gaia_oauth_client_->GetUserEmail(access_token, kMaxRetries, this);
}

void OAuthTokenGetterImpl::OnRefreshTokenResponse(
    const std::string& access_token,
    int expires_seconds) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(authorization_credentials_);
  VLOG(1) << "Received OAuth token.";

  // Update the access token and any other auto-update timers.
  UpdateAccessToken(access_token, expires_seconds);

  if (!authorization_credentials_->is_service_account && !email_verified_) {
    gaia_oauth_client_->GetUserEmail(access_token, kMaxRetries, this);
  } else {
    NotifyTokenCallbacks(OAuthTokenGetterImpl::SUCCESS,
                         authorization_credentials_->login,
                         oauth_access_token_);
  }
}

void OAuthTokenGetterImpl::OnGetUserEmailResponse(
    const std::string& user_email) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(authorization_credentials_);
  VLOG(1) << "Received user info.";

  if (email_discovery_) {
    authorization_credentials_->login = user_email;
    email_discovery_ = false;
    NotifyUpdatedCallbacks(authorization_credentials_->login,
                           authorization_credentials_->refresh_token);
  } else if (user_email != authorization_credentials_->login) {
    LOG(ERROR) << "OAuth token and email address do not refer to "
                  "the same account.";
    OnOAuthError();
    return;
  }

  email_verified_ = true;

  NotifyTokenCallbacks(OAuthTokenGetterImpl::SUCCESS,
                       authorization_credentials_->login, oauth_access_token_);
}

void OAuthTokenGetterImpl::UpdateAccessToken(const std::string& access_token,
                                             int expires_seconds) {
  oauth_access_token_ = access_token;
  base::TimeDelta token_expiration =
      base::Seconds(expires_seconds) -
      base::Seconds(kTokenUpdateTimeBeforeExpirySeconds);
  access_token_expiry_time_ = base::Time::Now() + token_expiration;

  if (refresh_timer_) {
    refresh_timer_->Stop();
    refresh_timer_->Start(FROM_HERE, token_expiration, this,
                          &OAuthTokenGetterImpl::RefreshAccessToken);
  }
}

void OAuthTokenGetterImpl::NotifyTokenCallbacks(
    Status status,
    const std::string& user_email,
    const std::string& access_token) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  SetResponsePending(false);

  base::queue<TokenCallback> callbacks;
  callbacks.swap(pending_callbacks_);

  while (!callbacks.empty()) {
    std::move(callbacks.front()).Run(status, user_email, access_token);
    callbacks.pop();
  }
}

void OAuthTokenGetterImpl::NotifyUpdatedCallbacks(
    const std::string& user_email,
    const std::string& refresh_token) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (credentials_updated_callback_) {
    credentials_updated_callback_.Run(user_email, refresh_token);
  }
}

void OAuthTokenGetterImpl::OnOAuthError() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  LOG(ERROR) << "OAuth: invalid credentials.";

  // Throw away invalid credentials and force a refresh.
  oauth_access_token_.clear();
  access_token_expiry_time_ = base::Time();
  email_verified_ = false;

  NotifyTokenCallbacks(OAuthTokenGetterImpl::AUTH_ERROR, std::string(),
                       std::string());
}

void OAuthTokenGetterImpl::OnNetworkError(int response_code) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  LOG(ERROR) << "Network error when trying to update OAuth token: "
             << response_code;
  NotifyTokenCallbacks(OAuthTokenGetterImpl::NETWORK_ERROR, std::string(),
                       std::string());
}

void OAuthTokenGetterImpl::CallWithToken(TokenCallback on_access_token) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  pending_callbacks_.push(std::move(on_access_token));

  if (intermediate_credentials_) {
    if (!IsResponsePending()) {
      GetOauthTokensFromAuthCode();
    }
  } else {
    bool need_new_auth_token =
        access_token_expiry_time_.is_null() ||
        base::Time::Now() >= access_token_expiry_time_ ||
        (!authorization_credentials_->is_service_account && !email_verified_);

    if (need_new_auth_token) {
      if (!IsResponsePending()) {
        RefreshAccessToken();
      }
    } else {
      // If IsResponsePending() is true here, |on_access_token| will be called
      // when the response is received.
      if (!IsResponsePending()) {
        NotifyTokenCallbacks(OAuthTokenGetterImpl::SUCCESS,
                             authorization_credentials_->login,
                             oauth_access_token_);
      }
    }
  }
}

void OAuthTokenGetterImpl::InvalidateCache() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  access_token_expiry_time_ = base::Time();
}

base::WeakPtr<OAuthTokenGetterImpl> OAuthTokenGetterImpl::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

void OAuthTokenGetterImpl::GetOauthTokensFromAuthCode() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  VLOG(1) << "Fetching OAuth token from Auth Code.";
  DCHECK(!IsResponsePending());

  // Service accounts use different API keys, as they use the client app flow.
  google_apis::OAuth2Client oauth2_client =
      intermediate_credentials_->is_service_account
          ? google_apis::CLIENT_REMOTING_HOST
          : google_apis::CLIENT_REMOTING;

  // For the case of fetching an OAuth token from a one-time-use code, the
  // caller should provide a redirect URI.
  std::string redirect_uri = intermediate_credentials_->oauth_redirect_uri;
  DCHECK(!redirect_uri.empty());

  gaia::OAuthClientInfo client_info = {
      google_apis::GetOAuth2ClientID(oauth2_client),
      google_apis::GetOAuth2ClientSecret(oauth2_client), redirect_uri};

  SetResponsePending(true);

  gaia_oauth_client_->GetTokensFromAuthCode(
      client_info, intermediate_credentials_->authorization_code, kMaxRetries,
      this);
}

void OAuthTokenGetterImpl::RefreshAccessToken() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  VLOG(1) << "Refreshing OAuth Access token.";
  DCHECK(!IsResponsePending());

  // Service accounts use different API keys, as they use the client app flow.
  google_apis::OAuth2Client oauth2_client =
      authorization_credentials_->is_service_account
          ? google_apis::CLIENT_REMOTING_HOST
          : google_apis::CLIENT_REMOTING;

  gaia::OAuthClientInfo client_info = {
      google_apis::GetOAuth2ClientID(oauth2_client),
      google_apis::GetOAuth2ClientSecret(oauth2_client),
      // Redirect URL is only used when getting tokens from auth code. It
      // is not required when getting access tokens from refresh tokens.
      ""};

  SetResponsePending(true);
  std::vector<std::string> empty_scope_list;  // Use scope from refresh token.
  gaia_oauth_client_->RefreshToken(client_info,
                                   authorization_credentials_->refresh_token,
                                   empty_scope_list, kMaxRetries, this);
}

bool OAuthTokenGetterImpl::IsResponsePending() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return response_timeout_timer_.IsRunning();
}

void OAuthTokenGetterImpl::SetResponsePending(bool is_pending) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (is_pending) {
    if (IsResponsePending()) {
      LOG(DFATAL) << "The response is already pending.";
      return;
    }
    response_timeout_timer_.Start(FROM_HERE, kResponseTimeoutDuration, this,
                                  &OAuthTokenGetterImpl::OnResponseTimeout);
  } else {
    response_timeout_timer_.Stop();
  }
}

void OAuthTokenGetterImpl::OnResponseTimeout() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  LOG(ERROR) << "GaiaOAuthClient response timeout";
  gaia_oauth_client_ =
      std::make_unique<gaia::GaiaOAuthClient>(url_loader_factory_);
  NotifyTokenCallbacks(OAuthTokenGetterImpl::NETWORK_ERROR, {}, {});
}

}  // namespace remoting