summaryrefslogtreecommitdiff
path: root/chromium/components/signin/core/browser/about_signin_internals.cc
blob: 20dcc821e7048ea39128f288896fee851e6d8c53 (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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
// 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 "components/signin/core/browser/about_signin_internals.h"

#include <stddef.h>

#include <algorithm>
#include <tuple>

#include "base/command_line.h"
#include "base/hash/hash.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/time/time_to_iso8601.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/signin_client.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h"
#include "components/signin/public/identity_manager/diagnostics_provider.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/load_credentials_state.h"
#include "net/base/backoff_entry.h"

namespace {

// The maximum number of the refresh token events. Only the last
// |kMaxRefreshTokenListSize| events are kept in memory.
const size_t kMaxRefreshTokenListSize = 50;

enum class GaiaCookiesState {
  kAllowed,
  kClearOnExit,
  kBlocked,
};

GaiaCookiesState GetGaiaCookiesState(SigninClient* signin_client) {
  bool signin_cookies_allowed = signin_client->AreSigninCookiesAllowed();
  if (!signin_cookies_allowed)
    return GaiaCookiesState::kBlocked;

  bool clear_cookies_on_exit = signin_client->AreSigninCookiesDeletedOnExit();
  if (clear_cookies_on_exit)
    return GaiaCookiesState::kClearOnExit;

  return GaiaCookiesState::kAllowed;
}

std::string GetGaiaCookiesStateAsString(const GaiaCookiesState state) {
  switch (state) {
    case GaiaCookiesState::kBlocked:
      return "Not allowed";
    case GaiaCookiesState::kClearOnExit:
      return "Cleared on exit";
    case GaiaCookiesState::kAllowed:
      return "Allowed";
  }
}

base::ListValue* AddSection(base::ListValue* parent_list,
                            const std::string& title) {
  auto section = std::make_unique<base::DictionaryValue>();

  section->SetString("title", title);
  base::ListValue* section_contents =
      section->SetList("data", std::make_unique<base::ListValue>());
  parent_list->Append(std::move(section));
  return section_contents;
}

void AddSectionEntry(base::ListValue* section_list,
                     const std::string& field_name,
                     const std::string& field_status,
                     const std::string& field_time = "") {
  std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
  entry->SetString("label", field_name);
  entry->SetString("status", field_status);
  entry->SetString("time", field_time);
  section_list->Append(std::move(entry));
}

void AddCookieEntry(base::ListValue* accounts_list,
                     const std::string& field_email,
                     const std::string& field_gaia_id,
                     const std::string& field_valid) {
  std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
  entry->SetString("email", field_email);
  entry->SetString("gaia_id", field_gaia_id);
  entry->SetString("valid", field_valid);
  accounts_list->Append(std::move(entry));
}

std::string SigninStatusFieldToLabel(
    signin_internals_util::UntimedSigninStatusField field) {
  switch (field) {
    case signin_internals_util::ACCOUNT_ID:
      return "Account Id";
    case signin_internals_util::GAIA_ID:
      return "Gaia Id";
    case signin_internals_util::USERNAME:
      return "Username";
    case signin_internals_util::UNTIMED_FIELDS_END:
      NOTREACHED();
      return std::string();
  }
  NOTREACHED();
  return std::string();
}

std::string TokenServiceLoadCredentialsStateToLabel(
    signin::LoadCredentialsState state) {
  switch (state) {
    case signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED:
      return "Load credentials not started";
    case signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS:
      return "Load credentials in progress";
    case signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS:
      return "Load credentials finished with success";
    case signin::LoadCredentialsState::
        LOAD_CREDENTIALS_FINISHED_WITH_DB_CANNOT_BE_OPENED:
      return "Load credentials failed with datase cannot be opened error";
    case signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS:
      return "Load credentials failed with database errors";
    case signin::LoadCredentialsState::
        LOAD_CREDENTIALS_FINISHED_WITH_DECRYPT_ERRORS:
      return "Load credentials failed with decrypt errors";
    case signin::LoadCredentialsState::
        LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT:
      return "Load credentials failed with no refresh token for signed in "
             "account";
    case signin::LoadCredentialsState::
        LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS:
      return "Load credentials failed with unknown errors";
  }
  NOTREACHED();
  return std::string();
}

#if !defined (OS_CHROMEOS)
std::string SigninStatusFieldToLabel(
    signin_internals_util::TimedSigninStatusField field) {
  switch (field) {
    case signin_internals_util::AUTHENTICATION_RESULT_RECEIVED:
      return "Gaia Authentication Result";
    case signin_internals_util::REFRESH_TOKEN_RECEIVED:
      return "RefreshToken Received";
    case signin_internals_util::TIMED_FIELDS_END:
      NOTREACHED();
      return "Error";
  }
  NOTREACHED();
  return "Error";
}
#endif  // !defined (OS_CHROMEOS)

// It's quite unfortunate that |time| is saved in prefs as a string instead of
// base::Time because any change of the format would create inconsistency.
void SetPref(PrefService* prefs,
             signin_internals_util::TimedSigninStatusField field,
             const std::string& value,
             const std::string& time) {
  std::string value_pref = SigninStatusFieldToString(field) + ".value";
  std::string time_pref = SigninStatusFieldToString(field) + ".time";
  prefs->SetString(value_pref, value);
  prefs->SetString(time_pref, time);
}

void GetPref(PrefService* prefs,
             signin_internals_util::TimedSigninStatusField field,
             std::string* value,
             std::string* time) {
  std::string value_pref = SigninStatusFieldToString(field) + ".value";
  std::string time_pref = SigninStatusFieldToString(field) + ".time";
  *value = prefs->GetString(value_pref);
  *time = prefs->GetString(time_pref);
}

void ClearPref(PrefService* prefs,
               signin_internals_util::TimedSigninStatusField field) {
  std::string value_pref = SigninStatusFieldToString(field) + ".value";
  std::string time_pref = SigninStatusFieldToString(field) + ".time";
  prefs->ClearPref(value_pref);
  prefs->ClearPref(time_pref);
}

std::string GetAccountConsistencyDescription(
    signin::AccountConsistencyMethod method) {
  switch (method) {
    case signin::AccountConsistencyMethod::kDisabled:
      return "None";
    case signin::AccountConsistencyMethod::kMirror:
      return "Mirror";
    case signin::AccountConsistencyMethod::kDiceMigration:
      return "DICE migration";
    case signin::AccountConsistencyMethod::kDice:
      return "DICE";
  }
  NOTREACHED();
  return "";
}

}  // anonymous namespace

AboutSigninInternals::AboutSigninInternals(
    signin::IdentityManager* identity_manager,
    SigninErrorController* signin_error_controller,
    signin::AccountConsistencyMethod account_consistency)
    : identity_manager_(identity_manager),
      client_(nullptr),
      signin_error_controller_(signin_error_controller),
      account_consistency_(account_consistency) {}

AboutSigninInternals::~AboutSigninInternals() {}

signin_internals_util::UntimedSigninStatusField& operator++(
    signin_internals_util::UntimedSigninStatusField& field) {
  field =
      static_cast<signin_internals_util::UntimedSigninStatusField>(field + 1);
  return field;
}

signin_internals_util::TimedSigninStatusField& operator++(
    signin_internals_util::TimedSigninStatusField& field) {
  field = static_cast<signin_internals_util::TimedSigninStatusField>(field + 1);
  return field;
}

// static
void AboutSigninInternals::RegisterPrefs(PrefRegistrySimple* user_prefs) {
  // TODO(rogerta): leaving untimed fields here for now because legacy
  // profiles still have these prefs.  In three or four version from M43
  // we can probably remove them.
  for (signin_internals_util::UntimedSigninStatusField i =
           signin_internals_util::UNTIMED_FIELDS_BEGIN;
       i < signin_internals_util::UNTIMED_FIELDS_END; ++i) {
    const std::string pref_path = SigninStatusFieldToString(i);
    user_prefs->RegisterStringPref(pref_path, std::string());
  }

  for (signin_internals_util::TimedSigninStatusField i =
           signin_internals_util::TIMED_FIELDS_BEGIN;
       i < signin_internals_util::TIMED_FIELDS_END; ++i) {
    const std::string value = SigninStatusFieldToString(i) + ".value";
    const std::string time = SigninStatusFieldToString(i) + ".time";
    user_prefs->RegisterStringPref(value, std::string());
    user_prefs->RegisterStringPref(time, std::string());
  }
}

void AboutSigninInternals::AddSigninObserver(
    AboutSigninInternals::Observer* observer) {
  signin_observers_.AddObserver(observer);
}

void AboutSigninInternals::RemoveSigninObserver(
    AboutSigninInternals::Observer* observer) {
  signin_observers_.RemoveObserver(observer);
}

void AboutSigninInternals::NotifyTimedSigninFieldValueChanged(
    const signin_internals_util::TimedSigninStatusField& field,
    const std::string& value) {
  unsigned int field_index = field - signin_internals_util::TIMED_FIELDS_BEGIN;
  DCHECK(field_index >= 0 &&
         field_index < signin_status_.timed_signin_fields.size());

  base::Time now = base::Time::NowFromSystemTime();
  std::string time_as_str = base::TimeToISO8601(now);
  TimedSigninStatusValue timed_value(value, time_as_str);

  signin_status_.timed_signin_fields[field_index] = timed_value;

  // Also persist these values in the prefs.
  SetPref(client_->GetPrefs(), field, value, time_as_str);

  // If the user is restarting a sign in process, clear the fields that are
  // to come.
  if (field == signin_internals_util::AUTHENTICATION_RESULT_RECEIVED) {
    ClearPref(client_->GetPrefs(),
              signin_internals_util::REFRESH_TOKEN_RECEIVED);
  }

  NotifyObservers();
}

void AboutSigninInternals::RefreshSigninPrefs() {
  // Return if no client exists. Can occur in unit tests.
  if (!client_)
    return;

  PrefService* pref_service = client_->GetPrefs();
  for (signin_internals_util::TimedSigninStatusField i =
           signin_internals_util::TIMED_FIELDS_BEGIN;
       i < signin_internals_util::TIMED_FIELDS_END; ++i) {
    std::string time_str;
    std::string value_str;
    GetPref(pref_service, i, &value_str, &time_str);
    TimedSigninStatusValue value(value_str, time_str);
    signin_status_
        .timed_signin_fields[i - signin_internals_util::TIMED_FIELDS_BEGIN] =
        value;
  }

  // TODO(rogerta): Get status and timestamps for oauth2 tokens.

  NotifyObservers();
}

void AboutSigninInternals::Initialize(SigninClient* client) {
  DCHECK(!client_);
  client_ = client;

  RefreshSigninPrefs();

  client_->AddContentSettingsObserver(this);
  signin_error_controller_->AddObserver(this);
  identity_manager_->AddObserver(this);
  identity_manager_->AddDiagnosticsObserver(this);
}

void AboutSigninInternals::Shutdown() {
  client_->RemoveContentSettingsObserver(this);
  signin_error_controller_->RemoveObserver(this);
  identity_manager_->RemoveObserver(this);
  identity_manager_->RemoveDiagnosticsObserver(this);
}

void AboutSigninInternals::OnContentSettingChanged(
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern,
    ContentSettingsType content_type,
    const std::string& resource_identifier) {
  // If this is not a change to cookie settings, just ignore.
  if (content_type != CONTENT_SETTINGS_TYPE_COOKIES)
    return;

  NotifyObservers();
}

void AboutSigninInternals::NotifyObservers() {
  if (!signin_observers_.might_have_observers())
    return;

  std::unique_ptr<base::DictionaryValue> signin_status_value =
      signin_status_.ToValue(identity_manager_, signin_error_controller_,
                             client_, account_consistency_);

  for (auto& observer : signin_observers_)
    observer.OnSigninStateChanged(signin_status_value.get());
}

std::unique_ptr<base::DictionaryValue> AboutSigninInternals::GetSigninStatus() {
  return signin_status_.ToValue(identity_manager_, signin_error_controller_,
                                client_, account_consistency_);
}

void AboutSigninInternals::OnAccessTokenRequested(
    const CoreAccountId& account_id,
    const std::string& consumer_id,
    const identity::ScopeSet& scopes) {
  TokenInfo* token = signin_status_.FindToken(account_id, consumer_id, scopes);
  if (token) {
    *token = TokenInfo(consumer_id, scopes);
  } else {
    signin_status_.token_info_map[account_id].push_back(
        std::make_unique<TokenInfo>(consumer_id, scopes));
  }

  NotifyObservers();
}

void AboutSigninInternals::OnAccessTokenRequestCompleted(
    const CoreAccountId& account_id,
    const std::string& consumer_id,
    const identity::ScopeSet& scopes,
    GoogleServiceAuthError error,
    base::Time expiration_time) {
  TokenInfo* token = signin_status_.FindToken(account_id, consumer_id, scopes);
  if (!token) {
    DVLOG(1) << "Can't find token: " << account_id << ", " << consumer_id;
    return;
  }

  token->receive_time = base::Time::Now();
  token->error = error;
  token->expiration_time = expiration_time;

  NotifyObservers();
}

void AboutSigninInternals::OnRefreshTokenUpdatedForAccountFromSource(
    const CoreAccountId& account_id,
    bool is_refresh_token_valid,
    const std::string& source) {
  RefreshTokenEvent event;
  event.account_id = account_id;
  event.type =
      is_refresh_token_valid
          ? AboutSigninInternals::RefreshTokenEventType::kUpdateToRegular
          : AboutSigninInternals::RefreshTokenEventType::kUpdateToInvalid;
  event.source = source;
  signin_status_.AddRefreshTokenEvent(event);
}

void AboutSigninInternals::OnRefreshTokenRemovedForAccountFromSource(
    const CoreAccountId& account_id,
    const std::string& source) {
  RefreshTokenEvent event;
  event.account_id = account_id;
  event.type = AboutSigninInternals::RefreshTokenEventType::kRevokeRegular;
  event.source = source;
  signin_status_.AddRefreshTokenEvent(event);
}

void AboutSigninInternals::OnRefreshTokensLoaded() {
  RefreshTokenEvent event;
  // This event concerns all accounts, so it does not have any account id.
  event.type = AboutSigninInternals::RefreshTokenEventType::kAllTokensLoaded;
  signin_status_.AddRefreshTokenEvent(event);
  NotifyObservers();
}

void AboutSigninInternals::OnEndBatchOfRefreshTokenStateChanges() {
  NotifyObservers();
}

void AboutSigninInternals::OnAccessTokenRemovedFromCache(
    const CoreAccountId& account_id,
    const identity::ScopeSet& scopes) {
  for (const std::unique_ptr<TokenInfo>& token :
       signin_status_.token_info_map[account_id]) {
    if (token->scopes == scopes)
      token->Invalidate();
  }
  NotifyObservers();
}

void AboutSigninInternals::OnRefreshTokenReceived(const std::string& status) {
  NotifyTimedSigninFieldValueChanged(
      signin_internals_util::REFRESH_TOKEN_RECEIVED, status);
}

void AboutSigninInternals::OnAuthenticationResultReceived(
    const std::string& status) {
  NotifyTimedSigninFieldValueChanged(
      signin_internals_util::AUTHENTICATION_RESULT_RECEIVED, status);
}

void AboutSigninInternals::OnErrorChanged() {
  NotifyObservers();
}

void AboutSigninInternals::OnPrimaryAccountSet(
    const CoreAccountInfo& primary_account_info) {
  NotifyObservers();
}

void AboutSigninInternals::OnPrimaryAccountCleared(
    const CoreAccountInfo& primary_account_info) {
  NotifyObservers();
}

void AboutSigninInternals::OnAccountsInCookieUpdated(
    const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
    const GoogleServiceAuthError& error) {
  if (error.state() != GoogleServiceAuthError::NONE)
    return;

  auto cookie_info = std::make_unique<base::ListValue>();

  for (const auto& signed_in_account :
       accounts_in_cookie_jar_info.signed_in_accounts) {
    AddCookieEntry(cookie_info.get(), signed_in_account.raw_email,
                   signed_in_account.gaia_id,
                   signed_in_account.valid ? "Valid" : "Invalid");
  }

  if (accounts_in_cookie_jar_info.signed_in_accounts.size() == 0) {
    AddCookieEntry(cookie_info.get(), "No Accounts Present.", std::string(),
                   std::string());
  }

  base::DictionaryValue cookie_status;
  cookie_status.Set("cookie_info", std::move(cookie_info));
  // Update the observers that the cookie's accounts are updated.
  for (auto& observer : signin_observers_)
    observer.OnCookieAccountsFetched(&cookie_status);
}

AboutSigninInternals::TokenInfo::TokenInfo(const std::string& consumer_id,
                                           const identity::ScopeSet& scopes)
    : consumer_id(consumer_id),
      scopes(scopes),
      request_time(base::Time::Now()),
      error(GoogleServiceAuthError::AuthErrorNone()),
      removed_(false) {}

AboutSigninInternals::TokenInfo::~TokenInfo() {}

bool AboutSigninInternals::TokenInfo::LessThan(
    const std::unique_ptr<TokenInfo>& a,
    const std::unique_ptr<TokenInfo>& b) {
  return std::tie(a->request_time, a->consumer_id, a->scopes) <
         std::tie(b->request_time, b->consumer_id, b->scopes);
}

void AboutSigninInternals::TokenInfo::Invalidate() { removed_ = true; }

std::unique_ptr<base::DictionaryValue>
AboutSigninInternals::TokenInfo::ToValue() const {
  std::unique_ptr<base::DictionaryValue> token_info(
      new base::DictionaryValue());
  token_info->SetString("service", consumer_id);

  std::string scopes_str;
  for (auto it = scopes.begin(); it != scopes.end(); ++it) {
    scopes_str += *it + "<br/>";
  }
  token_info->SetString("scopes", scopes_str);
  token_info->SetString("request_time", base::TimeToISO8601(request_time));

  if (removed_) {
    token_info->SetString("status", "Token was revoked.");
  } else if (!receive_time.is_null()) {
    if (error == GoogleServiceAuthError::AuthErrorNone()) {
      bool token_expired = expiration_time < base::Time::Now();
      std::string expiration_time_string = base::TimeToISO8601(expiration_time);
      if (expiration_time.is_null()) {
        token_expired = false;
        expiration_time_string = "Expiration time not available";
      }
      std::string status_str;
      if (token_expired)
        status_str = "<p style=\"color: #ffffff; background-color: #ff0000\">";
      base::StringAppendF(&status_str, "Received token at %s. Expire at %s",
                          base::TimeToISO8601(receive_time).c_str(),
                          expiration_time_string.c_str());
      if (token_expired)
        base::StringAppendF(&status_str, "</p>");
      token_info->SetString("status", status_str);
    } else {
      token_info->SetString(
          "status",
          base::StringPrintf("Failure: %s", error.ToString().c_str()));
    }
  } else {
    token_info->SetString("status", "Waiting for response");
  }

  return token_info;
}

AboutSigninInternals::RefreshTokenEvent::RefreshTokenEvent()
    : timestamp(base::Time::Now()) {}

std::string AboutSigninInternals::RefreshTokenEvent::GetTypeAsString() const {
  switch (type) {
    case AboutSigninInternals::RefreshTokenEventType::kUpdateToRegular:
      return "Updated";
    case AboutSigninInternals::RefreshTokenEventType::kUpdateToInvalid:
      return "Invalidated";
    case AboutSigninInternals::RefreshTokenEventType::kRevokeRegular:
      return "Revoked";
    case AboutSigninInternals::RefreshTokenEventType::kAllTokensLoaded:
      return "Loaded";
  }
}

AboutSigninInternals::SigninStatus::SigninStatus()
    : timed_signin_fields(signin_internals_util::TIMED_FIELDS_COUNT) {}

AboutSigninInternals::SigninStatus::~SigninStatus() {}

AboutSigninInternals::TokenInfo* AboutSigninInternals::SigninStatus::FindToken(
    const CoreAccountId& account_id,
    const std::string& consumer_id,
    const identity::ScopeSet& scopes) {
  for (const std::unique_ptr<TokenInfo>& token : token_info_map[account_id]) {
    if (token->consumer_id == consumer_id && token->scopes == scopes)
      return token.get();
  }
  return nullptr;
}

void AboutSigninInternals::SigninStatus::AddRefreshTokenEvent(
    const AboutSigninInternals::RefreshTokenEvent& event) {
  if (refresh_token_events.size() > kMaxRefreshTokenListSize)
    refresh_token_events.pop_front();

  refresh_token_events.push_back(event);
}

std::unique_ptr<base::DictionaryValue>
AboutSigninInternals::SigninStatus::ToValue(
    signin::IdentityManager* identity_manager,
    SigninErrorController* signin_error_controller,
    SigninClient* signin_client,
    signin::AccountConsistencyMethod account_consistency) {
  auto signin_status = std::make_unique<base::DictionaryValue>();
  auto signin_info = std::make_unique<base::ListValue>();

  // A summary of signin related info first.
  base::ListValue* basic_info =
      AddSection(signin_info.get(), "Basic Information");
  AddSectionEntry(basic_info, "Account Consistency",
                  GetAccountConsistencyDescription(account_consistency));
  AddSectionEntry(
      basic_info, "Signin Status",
      identity_manager->HasPrimaryAccount() ? "Signed In" : "Not Signed In");
  signin::LoadCredentialsState load_tokens_state =
      identity_manager->GetDiagnosticsProvider()
          ->GetDetailedStateOfLoadingOfRefreshTokens();
  AddSectionEntry(basic_info, "TokenService Load Status",
                  TokenServiceLoadCredentialsStateToLabel(load_tokens_state));
  AddSectionEntry(
      basic_info, "Gaia cookies state",
      GetGaiaCookiesStateAsString(GetGaiaCookiesState(signin_client)));

  if (identity_manager->HasPrimaryAccount()) {
    CoreAccountInfo account_info = identity_manager->GetPrimaryAccountInfo();
    AddSectionEntry(basic_info,
                    SigninStatusFieldToLabel(signin_internals_util::ACCOUNT_ID),
                    account_info.account_id.id);
    AddSectionEntry(basic_info,
                    SigninStatusFieldToLabel(signin_internals_util::GAIA_ID),
                    account_info.gaia);
    AddSectionEntry(basic_info,
                    SigninStatusFieldToLabel(signin_internals_util::USERNAME),
                    account_info.email);
    if (signin_error_controller->HasError()) {
      const CoreAccountId error_account_id =
          signin_error_controller->error_account_id();
      const base::Optional<AccountInfo> error_account_info =
          identity_manager
              ->FindExtendedAccountInfoForAccountWithRefreshTokenByAccountId(
                  error_account_id);
      AddSectionEntry(basic_info, "Auth Error",
          signin_error_controller->auth_error().ToString());
      AddSectionEntry(basic_info, "Auth Error Account Id", error_account_id.id);

      // The error_account_info optional should never be unset when we reach
      // this line (as we should have a refresh token, even if in an error
      // state). However, since this is a debug page, make the code resilient
      // to avoid rendering the page unavailable to debug if a regression is
      // introduced (and thus making debugging the regression harder).
      AddSectionEntry(basic_info, "Auth Error Username",
                      error_account_info ? error_account_info->email : "");
    } else {
      AddSectionEntry(basic_info, "Auth Error", "None");
    }
  }

#if !defined(OS_CHROMEOS)
  // Time and status information of the possible sign in types.
  base::ListValue* detailed_info =
      AddSection(signin_info.get(), "Last Signin Details");
  signin_status->Set("signin_info", std::move(signin_info));
  for (signin_internals_util::TimedSigninStatusField i =
           signin_internals_util::TIMED_FIELDS_BEGIN;
       i < signin_internals_util::TIMED_FIELDS_END; ++i) {
    const std::string status_field_label = SigninStatusFieldToLabel(i);

    AddSectionEntry(
        detailed_info, status_field_label,
        timed_signin_fields[i - signin_internals_util::TIMED_FIELDS_BEGIN]
            .first,
        timed_signin_fields[i - signin_internals_util::TIMED_FIELDS_BEGIN]
            .second);
  }

  base::TimeDelta cookie_requests_delay =
      identity_manager->GetDiagnosticsProvider()
          ->GetDelayBeforeMakingCookieRequests();

  if (cookie_requests_delay > base::TimeDelta()) {
    base::Time next_retry_time =
        base::Time::NowFromSystemTime() + cookie_requests_delay;
    AddSectionEntry(detailed_info, "Cookie Manager Next Retry",
                    base::TimeToISO8601(next_retry_time), "");
  }

  base::TimeDelta token_requests_delay =
      identity_manager->GetDiagnosticsProvider()
          ->GetDelayBeforeMakingAccessTokenRequests();

  if (token_requests_delay > base::TimeDelta()) {
    base::Time next_retry_time =
        base::Time::NowFromSystemTime() + token_requests_delay;
    AddSectionEntry(detailed_info, "Token Service Next Retry",
                    base::TimeToISO8601(next_retry_time), "");
  }

#endif  // !defined(OS_CHROMEOS)

  // Token information for all services.
  auto token_info = std::make_unique<base::ListValue>();
  for (auto it = token_info_map.begin(); it != token_info_map.end(); ++it) {
    base::ListValue* token_details = AddSection(token_info.get(), it->first.id);
    std::sort(it->second.begin(), it->second.end(), TokenInfo::LessThan);
    for (const std::unique_ptr<TokenInfo>& token : it->second)
      token_details->Append(token->ToValue());
  }
  signin_status->Set("token_info", std::move(token_info));

  // Account info section
  auto account_info_section = std::make_unique<base::ListValue>();
  const std::vector<CoreAccountInfo>& accounts_with_refresh_tokens =
      identity_manager->GetAccountsWithRefreshTokens();
  if (accounts_with_refresh_tokens.size() == 0) {
    auto no_token_entry = std::make_unique<base::DictionaryValue>();
    no_token_entry->SetString("accountId", "No token in Token Service.");
    account_info_section->Append(std::move(no_token_entry));
  } else {
    for (const CoreAccountInfo& account_info : accounts_with_refresh_tokens) {
      auto entry = std::make_unique<base::DictionaryValue>();
      entry->SetString("accountId", account_info.account_id.id);
      // TODO(https://crbug.com/919793): Remove this field once the token
      // service is internally consistent on all platforms.
      entry->SetBoolean("hasRefreshToken",
                        identity_manager->HasAccountWithRefreshToken(
                            account_info.account_id));
      entry->SetBoolean(
          "hasAuthError",
          identity_manager->HasAccountWithRefreshTokenInPersistentErrorState(
              account_info.account_id));
      account_info_section->Append(std::move(entry));
    }
  }
  signin_status->Set("accountInfo", std::move(account_info_section));

  // Refresh token events section
  auto refresh_token_events_value = std::make_unique<base::ListValue>();
  for (const auto& event : refresh_token_events) {
    auto entry = std::make_unique<base::DictionaryValue>();
    entry->SetString("accountId", event.account_id.id);
    entry->SetString("timestamp", base::TimeToISO8601(event.timestamp));
    entry->SetString("type", event.GetTypeAsString());
    entry->SetString("source", event.source);
    refresh_token_events_value->Append(std::move(entry));
  }
  signin_status->Set("refreshTokenEvents",
                     std::move(refresh_token_events_value));

  return signin_status;
}