summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/api/identity/experimental_identity_api.cc
blob: 5839991f2d1da8b50b4ad0c92e30de944d135f80 (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/identity/experimental_identity_api.h"

#include <set>
#include <string>
#include <vector>

#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/app_mode/app_mode_utils.h"
#include "chrome/browser/extensions/api/identity/identity_api.h"
#include "chrome/browser/extensions/extension_install_prompt.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/api/experimental_identity.h"
#include "chrome/common/extensions/api/identity.h"
#include "chrome/common/extensions/api/identity/oauth2_manifest_handler.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/manifest_handler.h"
#include "chrome/common/url_constants.h"
#include "content/public/common/page_transition_types.h"
#include "google_apis/gaia/gaia_constants.h"
#include "ui/base/window_open_disposition.h"
#include "url/gurl.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#endif

namespace extensions {

namespace {

static const char kChromiumDomainRedirectUrlPattern[] =
    "https://%s.chromiumapp.org/";

}  // namespace

namespace identity_exp = api::experimental_identity;

ExperimentalIdentityGetAuthTokenFunction::
    ExperimentalIdentityGetAuthTokenFunction()
    : should_prompt_for_scopes_(false), should_prompt_for_signin_(false) {}

ExperimentalIdentityGetAuthTokenFunction::
    ~ExperimentalIdentityGetAuthTokenFunction() {}

bool ExperimentalIdentityGetAuthTokenFunction::RunImpl() {
  if (profile()->IsOffTheRecord()) {
    error_ = identity_constants::kOffTheRecord;
    return false;
  }

  scoped_ptr<identity_exp::GetAuthToken::Params> params(
      identity_exp::GetAuthToken::Params::Create(*args_));
  EXTENSION_FUNCTION_VALIDATE(params.get());
  bool interactive = params->details.get() &&
      params->details->interactive.get() &&
      *params->details->interactive;

  should_prompt_for_scopes_ = interactive;
  should_prompt_for_signin_ = interactive;

  const OAuth2Info& oauth2_info = OAuth2Info::GetOAuth2Info(GetExtension());

  // Check that the necessary information is present in the manifest.
  if (oauth2_info.client_id.empty()) {
    error_ = identity_constants::kInvalidClientId;
    return false;
  }

  if (oauth2_info.scopes.size() == 0) {
    error_ = identity_constants::kInvalidScopes;
    return false;
  }

  // Balanced in CompleteFunctionWithResult|CompleteFunctionWithError
  AddRef();

  if (!HasLoginToken()) {
    if (!should_prompt_for_signin_) {
      error_ = identity_constants::kUserNotSignedIn;
      Release();
      return false;
    }
    // Display a login prompt.
    StartSigninFlow();
  } else {
    StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE);
  }

  return true;
}

void ExperimentalIdentityGetAuthTokenFunction::CompleteFunctionWithResult(
    const std::string& access_token) {
  SetResult(new base::StringValue(access_token));
  SendResponse(true);
  Release();  // Balanced in RunImpl.
}

void ExperimentalIdentityGetAuthTokenFunction::CompleteFunctionWithError(
    const std::string& error) {
  error_ = error;
  SendResponse(false);
  Release();  // Balanced in RunImpl.
}

void ExperimentalIdentityGetAuthTokenFunction::StartSigninFlow() {
  // Display a login prompt. If the subsequent mint fails, don't display the
  // login prompt again.
  should_prompt_for_signin_ = false;
  ShowLoginPopup();
}

void ExperimentalIdentityGetAuthTokenFunction::StartMintTokenFlow(
    IdentityMintRequestQueue::MintType type) {
  if (!should_prompt_for_scopes_) {
    // Caller requested no interaction.

    if (type == IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE) {
      // GAIA told us to do a consent UI.
      CompleteFunctionWithError(identity_constants::kNoGrant);
      return;
    }
  }

  if (type == IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE) {
    gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_NO_FORCE;
    StartLoginAccessTokenRequest();
  } else {
    DCHECK(type == IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE);

    // GetAssociatedWebContents() could be NULL and this would trigger a CHECK
    // in the ExtensionInstallPrompt UI. Passing a valid Profile so that the
    // icon is loaded and avoid the CHECK failure.
    install_ui_.reset(
        GetAssociatedWebContents()
            ? new ExtensionInstallPrompt(GetAssociatedWebContents())
            : new ExtensionInstallPrompt(profile(), NULL, NULL));
    ShowOAuthApprovalDialog(issue_advice_);
  }
}

void ExperimentalIdentityGetAuthTokenFunction::OnMintTokenSuccess(
    const std::string& access_token, int time_to_live) {
  CompleteFunctionWithResult(access_token);
}

void ExperimentalIdentityGetAuthTokenFunction::OnMintTokenFailure(
    const GoogleServiceAuthError& error) {
  switch (error.state()) {
    case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS:
    case GoogleServiceAuthError::ACCOUNT_DELETED:
    case GoogleServiceAuthError::ACCOUNT_DISABLED:
      extensions::IdentityAPI::GetFactoryInstance()->GetForProfile(
          profile())->ReportAuthError(error);
      if (should_prompt_for_signin_) {
        // Display a login prompt and try again (once).
        StartSigninFlow();
        return;
      }
      break;
    default:
      // Return error to caller.
      break;
  }

  CompleteFunctionWithError(
      std::string(identity_constants::kAuthFailure) + error.ToString());
}

void ExperimentalIdentityGetAuthTokenFunction::OnIssueAdviceSuccess(
    const IssueAdviceInfo& issue_advice) {
  should_prompt_for_signin_ = false;
  // Existing grant was revoked and we used NO_FORCE, so we got info back
  // instead. Start a consent UI if we can.
  issue_advice_ = issue_advice;
  StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE);
}

void ExperimentalIdentityGetAuthTokenFunction::SigninSuccess() {
  StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE);
}

void ExperimentalIdentityGetAuthTokenFunction::SigninFailed() {
  CompleteFunctionWithError(identity_constants::kUserNotSignedIn);
}

void ExperimentalIdentityGetAuthTokenFunction::InstallUIProceed() {
  // The user has accepted the scopes, so we may now force (recording a grant
  // and receiving a token).
  gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_FORCE;
  StartLoginAccessTokenRequest();
}

void ExperimentalIdentityGetAuthTokenFunction::InstallUIAbort(
    bool user_initiated) {
  CompleteFunctionWithError(identity_constants::kUserRejected);
}

void ExperimentalIdentityGetAuthTokenFunction::OnGetTokenSuccess(
      const OAuth2TokenService::Request* request,
      const std::string& access_token,
      const base::Time& expiration_time) {
  DCHECK_EQ(login_token_request_.get(), request);
  login_token_request_.reset();
  StartGaiaRequest(access_token);
}

void ExperimentalIdentityGetAuthTokenFunction::OnGetTokenFailure(
      const OAuth2TokenService::Request* request,
      const GoogleServiceAuthError& error) {
  DCHECK_EQ(login_token_request_.get(), request);
  login_token_request_.reset();

  CompleteFunctionWithError(
      std::string(identity_constants::kAuthFailure) + error.ToString());
}

void ExperimentalIdentityGetAuthTokenFunction::StartLoginAccessTokenRequest() {
  ProfileOAuth2TokenService* service =
      ProfileOAuth2TokenServiceFactory::GetForProfile(profile());
#if defined(OS_CHROMEOS)
  if (chrome::IsRunningInForcedAppMode()) {
    std::string app_client_id;
    std::string app_client_secret;
    if (chromeos::UserManager::Get()->GetAppModeChromeClientOAuthInfo(
           &app_client_id, &app_client_secret)) {
      login_token_request_ =
          service->StartRequestForClient(service->GetPrimaryAccountId(),
                                         app_client_id,
                                         app_client_secret,
                                         OAuth2TokenService::ScopeSet(),
                                         this);
      return;
    }
  }
#endif
  login_token_request_ = service->StartRequest(
      service->GetPrimaryAccountId(), OAuth2TokenService::ScopeSet(), this);
}

void ExperimentalIdentityGetAuthTokenFunction::StartGaiaRequest(
    const std::string& login_access_token) {
  DCHECK(!login_access_token.empty());
  mint_token_flow_.reset(CreateMintTokenFlow(login_access_token));
  mint_token_flow_->Start();
}

void ExperimentalIdentityGetAuthTokenFunction::ShowLoginPopup() {
  signin_flow_.reset(new IdentitySigninFlow(this, profile()));
  signin_flow_->Start();
}

void ExperimentalIdentityGetAuthTokenFunction::ShowOAuthApprovalDialog(
    const IssueAdviceInfo& issue_advice) {
  install_ui_->ConfirmIssueAdvice(this, GetExtension(), issue_advice);
}

OAuth2MintTokenFlow*
ExperimentalIdentityGetAuthTokenFunction::CreateMintTokenFlow(
    const std::string& login_access_token) {
#if defined(OS_CHROMEOS)
  // Always force minting token for ChromeOS kiosk app.
  if (chrome::IsRunningInForcedAppMode())
    gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_FORCE;
#endif

  const OAuth2Info& oauth2_info = OAuth2Info::GetOAuth2Info(GetExtension());
  OAuth2MintTokenFlow* mint_token_flow =
      new OAuth2MintTokenFlow(
          profile()->GetRequestContext(),
          this,
          OAuth2MintTokenFlow::Parameters(
              login_access_token,
              GetExtension()->id(),
              oauth2_info.client_id,
              oauth2_info.scopes,
              gaia_mint_token_mode_));
  return mint_token_flow;
}

bool ExperimentalIdentityGetAuthTokenFunction::HasLoginToken() const {
  ProfileOAuth2TokenService* token_service =
      ProfileOAuth2TokenServiceFactory::GetForProfile(profile());
  return token_service->RefreshTokenIsAvailable(
      token_service->GetPrimaryAccountId());
}

ExperimentalIdentityLaunchWebAuthFlowFunction::
    ExperimentalIdentityLaunchWebAuthFlowFunction() {}

ExperimentalIdentityLaunchWebAuthFlowFunction::
    ~ExperimentalIdentityLaunchWebAuthFlowFunction() {
  if (auth_flow_)
    auth_flow_.release()->DetachDelegateAndDelete();
}

bool ExperimentalIdentityLaunchWebAuthFlowFunction::RunImpl() {
  if (profile()->IsOffTheRecord()) {
    error_ = identity_constants::kOffTheRecord;
    return false;
  }

  scoped_ptr<identity_exp::LaunchWebAuthFlow::Params> params(
      identity_exp::LaunchWebAuthFlow::Params::Create(*args_));
  EXTENSION_FUNCTION_VALIDATE(params.get());
  const identity_exp::ExperimentalWebAuthFlowDetails& details = params->details;

  GURL auth_url(params->details.url);
  ExperimentalWebAuthFlow::Mode mode =
      params->details.interactive && *params->details.interactive ?
      ExperimentalWebAuthFlow::INTERACTIVE : ExperimentalWebAuthFlow::SILENT;

  // Set up acceptable target URLs. (Includes chrome-extension scheme
  // for this version of the API.)
  InitFinalRedirectURLPrefixes(GetExtension()->id());

  // The bounds attributes are optional, but using 0 when they're not available
  // does the right thing.
  gfx::Rect initial_bounds;
  if (details.width)
    initial_bounds.set_width(*details.width);
  if (details.height)
    initial_bounds.set_height(*details.height);
  if (details.left)
    initial_bounds.set_x(*details.left);
  if (details.top)
    initial_bounds.set_y(*details.top);

  AddRef();  // Balanced in OnAuthFlowSuccess/Failure.

  Browser* current_browser = this->GetCurrentBrowser();
  chrome::HostDesktopType host_desktop_type = current_browser ?
      current_browser->host_desktop_type() : chrome::GetActiveDesktop();
  auth_flow_.reset(new ExperimentalWebAuthFlow(
      this, profile(), auth_url, mode, initial_bounds,
      host_desktop_type));
  auth_flow_->Start();
  return true;
}

bool ExperimentalIdentityLaunchWebAuthFlowFunction::IsFinalRedirectURL(
    const GURL& url) const {
  std::vector<GURL>::const_iterator iter;
  for (iter = final_prefixes_.begin(); iter != final_prefixes_.end(); ++iter) {
    if (url.GetWithEmptyPath() == *iter) {
      return true;
    }
  }
  return false;
}

void ExperimentalIdentityLaunchWebAuthFlowFunction::
    InitFinalRedirectURLPrefixes(const std::string& extension_id) {
  final_prefixes_.push_back(Extension::GetBaseURLFromExtensionId(extension_id));
  final_prefixes_.push_back(GURL(base::StringPrintf(
      kChromiumDomainRedirectUrlPattern, extension_id.c_str())));
}

void ExperimentalIdentityLaunchWebAuthFlowFunction::OnAuthFlowFailure(
    ExperimentalWebAuthFlow::Failure failure) {
  switch (failure) {
    case ExperimentalWebAuthFlow::WINDOW_CLOSED:
      error_ = identity_constants::kUserRejected;
      break;
    case ExperimentalWebAuthFlow::INTERACTION_REQUIRED:
      error_ = identity_constants::kInteractionRequired;
      break;
    default:
      NOTREACHED() << "Unexpected error from web auth flow: " << failure;
      error_ = identity_constants::kInvalidRedirect;
      break;
  }
  SendResponse(false);
  Release();  // Balanced in RunImpl.
}

void ExperimentalIdentityLaunchWebAuthFlowFunction::OnAuthFlowURLChange(
    const GURL& redirect_url) {
  if (IsFinalRedirectURL(redirect_url)) {
    SetResult(new base::StringValue(redirect_url.spec()));
    SendResponse(true);
    Release();  // Balanced in RunImpl.
  }
}

void ExperimentalIdentityLaunchWebAuthFlowFunction::
    InitFinalRedirectURLPrefixesForTest(const std::string& extension_id) {
  final_prefixes_.clear();
  InitFinalRedirectURLPrefixes(extension_id);
}

}  // namespace extensions