File: permission_uma_util.h

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 (991 lines) | stat: -rw-r--r-- 37,385 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
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
// 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.

#ifndef COMPONENTS_PERMISSIONS_PERMISSION_UMA_UTIL_H_
#define COMPONENTS_PERMISSIONS_PERMISSION_UMA_UTIL_H_

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

#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "base/version.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/permissions/permission_request_enums.h"
#include "components/permissions/prediction_service/prediction_service_messages.pb.h"
#include "components/permissions/request_type.h"
#include "content/public/browser/permission_result.h"
#include "url/gurl.h"

namespace blink {
enum class PermissionType;
}

namespace content {
class BrowserContext;
class RenderFrameHost;
class WebContents;
class RenderFrameHost;
}  // namespace content

namespace permissions {
enum class PermissionRequestGestureType;
enum class PermissionAction;
class PermissionRequest;

enum class ActivityIndicatorState {
  kInUse = 0,
  kBlockedOnSiteLevel = 1,
  kBlockedOnSystemLevel = 2,

  // Always keep at the end.
  kMaxValue = kBlockedOnSystemLevel,
};

// Used for UMA histograms to record model execution stats for the different
// models we use for a permission prediction.
// LINT.IfChange(PredictionModelType)
enum class PredictionModelType {
  kUnknown = 0,
  kServerSideCpssV3Model = 1,
  kOnDeviceCpssV1Model = 2,
  kOnDeviceAiV3Model = 3,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/permissions/histograms.xml:PredictionModels)

// Used for UMA to record the types of permission prompts shown.
// When updating, you also need to update:
//   1) The PermissionRequestType enum in
//      tools/metrics/histograms/metadata/permissions/enums.xml.
//   2) The PermissionRequestTypes suffix list in
//      tools/metrics/histograms/metadata/histogram_suffixes_list.xml.
//   3) GetPermissionRequestString function in
//      components/permissions/permission_uma_util.cc
//
// The usual rules of updating UMA values applies to this enum:
// - don't remove values
// - only ever add values at the end
enum class RequestTypeForUma {
  UNKNOWN = 0,
  MULTIPLE_AUDIO_AND_VIDEO_CAPTURE = 1,
  // UNUSED_PERMISSION = 2,
  QUOTA = 3,
  DOWNLOAD = 4,
  // MEDIA_STREAM = 5,
  REGISTER_PROTOCOL_HANDLER = 6,
  PERMISSION_GEOLOCATION = 7,
  PERMISSION_MIDI_SYSEX = 8,
  PERMISSION_NOTIFICATIONS = 9,
  PERMISSION_PROTECTED_MEDIA_IDENTIFIER = 10,
  // PERMISSION_PUSH_MESSAGING = 11,
  PERMISSION_FLASH = 12,
  PERMISSION_MEDIASTREAM_MIC = 13,
  PERMISSION_MEDIASTREAM_CAMERA = 14,
  // PERMISSION_ACCESSIBILITY_EVENTS = 15,  // Removed in M131.
  // PERMISSION_CLIPBOARD_READ = 16, // Replaced by
  // PERMISSION_CLIPBOARD_READ_WRITE in M81.
  // PERMISSION_SECURITY_KEY_ATTESTATION = 17,
  PERMISSION_PAYMENT_HANDLER = 18,
  PERMISSION_NFC = 19,
  PERMISSION_CLIPBOARD_READ_WRITE = 20,
  PERMISSION_VR = 21,
  PERMISSION_AR = 22,
  PERMISSION_STORAGE_ACCESS = 23,
  PERMISSION_CAMERA_PAN_TILT_ZOOM = 24,
  PERMISSION_WINDOW_MANAGEMENT = 25,
  PERMISSION_LOCAL_FONTS = 26,
  PERMISSION_IDLE_DETECTION = 27,
  PERMISSION_FILE_HANDLING = 28,
  // PERMISSION_U2F_API_REQUEST = 29,
  PERMISSION_TOP_LEVEL_STORAGE_ACCESS = 30,
  // PERMISSION_MIDI = 31,
  PERMISSION_FILE_SYSTEM_ACCESS = 32,
  CAPTURED_SURFACE_CONTROL = 33,
  PERMISSION_SMART_CARD = 34,
  PERMISSION_WEB_PRINTING = 35,
  PERMISSION_IDENTITY_PROVIDER = 36,
  PERMISSION_KEYBOARD_LOCK = 37,
  PERMISSION_POINTER_LOCK = 38,
  MULTIPLE_KEYBOARD_AND_POINTER_LOCK = 39,
  PERMISSION_HAND_TRACKING = 40,
  PERMISSION_WEB_APP_INSTALLATION = 41,
  PERMISSION_LOCAL_NETWORK_ACCESS = 42,
  // NUM must be the last value in the enum.
  NUM,
};

// Any new values should be inserted immediately prior to kMaxValue.
enum class PermissionSourceUI {
  // Permission prompt.
  PROMPT = 0,

  // Origin info bubble.
  // https://www.chromium.org/Home/chromium-security/enamel/goals-for-the-origin-info-bubble
  OIB = 1,

  // chrome://settings/content/siteDetails?site=[SITE]
  // chrome://settings/content/[PERMISSION TYPE]
  SITE_SETTINGS = 2,

  // Page action bubble.
  PAGE_ACTION = 3,

  // Permission settings from Android.
  // Currently this value is only used when revoking notification permission in
  // Android O+ system channel settings.
  ANDROID_SETTINGS = 4,

  // Permission settings as part of the event's UI.
  // Currently this value is only used when revoking notification permission
  // through the notification UI.
  INLINE_SETTINGS = 5,

  // Permission settings changes as part of the abusive origins revocation.
  AUTO_REVOCATION = 6,

  // Permission changes due to automatic revocations of permissions from unused
  // sites, as part of Safety Hub.
  SAFETY_HUB_AUTO_REVOCATION = 7,

  // The permission status changed, but we're unsure from what source.
  // This is likely ANDROID_SETTINGS above though.
  UNIDENTIFIED = 8,

  // Always keep this at the end.
  kMaxValue = UNIDENTIFIED,
};

// Any new values should be inserted immediately prior to NUM.
enum class PermissionEmbargoStatus {
  NOT_EMBARGOED = 0,
  // Removed: PERMISSIONS_BLACKLISTING = 1,
  REPEATED_DISMISSALS = 2,
  REPEATED_IGNORES = 3,
  RECENT_DISPLAY = 4,

  // Keep this at the end.
  NUM,
};

// Used for UMA to record the strict level of permission policy which is
// configured to allow sub-frame origin. Any new values should be inserted
// immediately prior to NUM. All values here should have corresponding entries
// PermissionsPolicyConfiguration area of enums.xml.
enum class PermissionHeaderPolicyForUMA {
  // No (or an invalid) Permissions-Policy header was present, results in an
  // empty features list. It indicates none security-awareness of permissions
  // policy configuration.
  HEADER_NOT_PRESENT_OR_INVALID = 0,

  // Permissions-Policy header was present, but it did not define an allowlist
  // for the feature. It indicates less security-awareness of permissions policy
  // configuration.
  FEATURE_NOT_PRESENT = 1,

  // The sub-frame origin is included in allow-list of permission
  // policy. This indicates a good policy configuration.
  FEATURE_ALLOWLIST_EXPLICITLY_MATCHES_ORIGIN = 2,

  // Granted by setting value of permission policy to '*'. This also
  // indicates a bad policy configuration.
  FEATURE_ALLOWLIST_IS_WILDCARD = 3,

  // The Permissions-Policy header was present and defined an empty
  // allowlist for the feature. The feature will be disabled everywhere.
  FEATURE_ALLOWLIST_IS_NONE = 4,

  // The sub-frame origin is not explicitly declared in allow-list of top level
  // permission policy. It generally indicates less security-awareness of
  // policy configuration.
  FEATURE_ALLOWLIST_DOES_NOT_MATCH_ORIGIN = 5,

  // Always keep this at the end.
  NUM,
};

// The kind of permission prompt UX used to surface a permission request.
// Enum used in UKMs and UMAs, do not re-order or change values. Deprecated
// items should only be commented out. New items should be added at the end,
// and the "PermissionPromptDisposition" histogram suffix needs to be updated to
// match (tools/metrics/histograms/metadata/histogram_suffixes_list.xml).
enum class PermissionPromptDisposition {
  // Not all permission actions will have an associated permission prompt (e.g.
  // changing permission via the settings page).
  NOT_APPLICABLE = 0,

  // Only used on desktop, a bubble under the site settings padlock.
  ANCHORED_BUBBLE = 1,

  // Only used on desktop, a static indicator on the right-hand side of the
  // location bar.
  LOCATION_BAR_RIGHT_STATIC_ICON = 2,

  // Only used on desktop, an animated indicator on the right-hand side of the
  // location bar.
  LOCATION_BAR_RIGHT_ANIMATED_ICON = 3,

  // Only used on Android, a modal dialog.
  MODAL_DIALOG = 4,

  // Only used on Android, an initially-collapsed infobar at the bottom of the
  // page.
  MINI_INFOBAR = 5,

  // Only used on desktop, a chip on the left-hand side of the location bar that
  // shows a bubble when clicked.
  LOCATION_BAR_LEFT_CHIP = 6,

  // There was no UI being shown. This is usually because the user closed an
  // inactive tab that had a pending permission request.
  NONE_VISIBLE = 7,

  // Other custom modal dialogs.
  CUSTOM_MODAL_DIALOG = 8,

  // Only used on desktop, a less prominent version of chip on the left-hand
  // side of the location bar that shows a bubble when clicked.
  LOCATION_BAR_LEFT_QUIET_CHIP = 9,

  // Only used on Android, a message bubble near top of the screen and below the
  // location bar. Message UI is an alternative UI to infobar UI.
  MESSAGE_UI = 10,

  // Only used on desktop, a chip on the left-hand side of the location bar that
  // automatically shows a bubble.
  LOCATION_BAR_LEFT_QUIET_ABUSIVE_CHIP = 11,

  // Only used on desktop, a chip on the left-hand side of the location bar that
  // automatically shows a bubble.
  LOCATION_BAR_LEFT_CHIP_AUTO_BUBBLE = 12,

  // A prompt shown as a result of the user clicking the permission element.
  ELEMENT_ANCHORED_BUBBLE = 13,

  // Only used on macOS, a native OS provided permission prompt.
  MAC_OS_PROMPT = 14,
};

// The reason why the permission prompt disposition was used. Enum used in UKMs,
// do not re-order or change values. Deprecated items should only be commented
// out.
enum class PermissionPromptDispositionReason {
  // Disposition was selected in prefs.
  USER_PREFERENCE_IN_SETTINGS = 0,

  // Disposition was chosen because Safe Browsing classifies the origin
  // as being spammy or abusive with permission requests.
  SAFE_BROWSING_VERDICT = 1,

  // Disposition was chosen based on grant likelihood predicted by the
  // Web Permission Prediction Service.
  PREDICTION_SERVICE = 2,

  // Disposition was used as a fallback, if no selector made a decision.
  DEFAULT_FALLBACK = 3,

  // Disposition was chosen based on grant likelihood predicted by the On-Device
  // Permission Prediction Model.
  ON_DEVICE_PREDICTION_MODEL = 4,
};

enum class AdaptiveTriggers {
  // None of the adaptive triggers were met. Currently this means two or less
  // consecutive denies in a row.
  NONE = 0,

  // User denied permission prompt 3 or more times.
  THREE_CONSECUTIVE_DENIES = 0x01,
};

// LINT.IfChange(DismissedReason)
enum class DismissedReason {
  // The prompt was dismissed through the [x] button.
  kDismissedXButton = 0,

  // The prompt was dismissed through the user clicking on the scrim (area
  // around the prompt).
  kDismissedScrim = 1,

  kMaxValue = kDismissedScrim,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/permissions/enums.xml:DismissedReason)

// LINT.IfChange(OsScreen)
enum class OsScreen {
  // Informs the user that Chrome needs permission from the OS level.
  kOsPrompt = 0,

  // Informs the user that they need to go to OS system settings.
  kOsSystemSettings = 1,

  kMaxValue = kOsSystemSettings,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/permissions/histograms.xml:OsScreen)

// LINT.IfChange(OsScreenAction)
enum class OsScreenAction {
  // User clicks on "Go to System settings"
  kSystemSettings = 0,

  // The prompt was dismissed through the [x] button.
  kDismissedXButton = 1,

  // The prompt was dismissed through the user clicking on the scrim (area
  // around the prompt).
  kDismissedScrim = 2,

  // Os prompt denied.
  kOsPromptDenied = 3,

  // Os prompt allowed.
  kOsPromptAllowed = 4,

  kMaxValue = kOsPromptAllowed,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/permissions/histograms.xml:OsScreenAction)

// These values are logged to UMA. Entries should not be renumbered and
// numeric values should never be reused. Please keep in sync with
// "OneTimePermissionEvent" in tools/metrics/histograms/enums.xml.
enum class OneTimePermissionEvent {
  // Recorded for each one time grant
  GRANTED_ONE_TIME = 0,

  // Recorded when the user manually revokes a one time grant
  REVOKED_MANUALLY = 1,

  // Recorded when a one time grant expires because all tabs are either closed
  // or discarded.
  ALL_TABS_CLOSED_OR_DISCARDED = 2,

  // Recorded when a one time grant expires because the permission was unused in
  // the background.
  EXPIRED_IN_BACKGROUND = 3,

  // Revoked because of the maximum one time permission lifetime
  // `kOneTimePermissionMaximumLifetime`
  EXPIRED_AFTER_MAXIMUM_LIFETIME = 4,

  // Recorded when a one time grant expires because the device was suspended.
  EXPIRED_ON_SUSPEND = 5,

  kMaxValue = EXPIRED_ON_SUSPEND,
};

// LINT.IfChange(ElementAnchoredBubbleVariant)
// Prompt views shown after the user clicks on the embedded permission prompt.
// The values represent the priority of each variant, higher number means
// higher priority.
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class ElementAnchoredBubbleVariant {
  // Default when conditions are not met to show any of the permission views.
  kUninitialized = 0,
  // Informs the user that the permission was allowed by their administrator.
  kAdministratorGranted = 1,
  // Permission prompt that informs the user they already granted permission.
  // Offers additional options to modify the permission decision.
  kPreviouslyGranted = 2,
  // Informs the user that they need to go to OS system settings to grant
  // access to Chrome.
  kOsSystemSettings = 3,
  // Informs the user that Chrome needs permission from the OS level, in order
  // for the site to be able to access a permission.
  kOsPrompt = 4,
  // Permission prompt that asks the user for site-level permission.
  kAsk = 5,
  // Permission prompt that additionally informs the user that they have
  // previously denied permission to the site. May offer different options
  // (buttons) to the site-level prompt |kAsk|.
  kPreviouslyDenied = 6,
  // Informs the user that the permission was denied by their administrator.
  kAdministratorDenied = 7,

  kMaxValue = kAdministratorDenied,
};
// LINT.ThenChange(//tools/metrics/histograms/enums.xml:ElementAnchoredBubbleVariant)

enum class PermissionAutoRevocationHistory {
  // Permission has not been automatically revoked.
  NONE = 0,

  // Permission has been automatically revoked.
  PREVIOUSLY_AUTO_REVOKED = 0x01,
};

// This enum backs up the `AutoDSEPermissionRevertTransition` histogram enum.
// Never reuse values and mirror any updates to it.
// Describes the transition that has occurred for the setting of a DSE origin
// when DSE autogrant becomes disabled.
enum class AutoDSEPermissionRevertTransition {
  // The user has not previously made any decision so it results in an `ASK` end
  // state.
  NO_DECISION_ASK = 0,
  // The user has decided to `ALLOW` the origin before it was the DSE origin and
  // has not reverted this decision.
  PRESERVE_ALLOW = 1,
  // The user has previously `BLOCKED` the origin but has allowed it after it
  // became the DSE origin. Resolve the conflict by setting it to `ASK` so the
  // user will make a decision again.
  CONFLICT_ASK = 2,
  // The user has blocked the DSE origin and has not made a previous decision
  // before the origin became the DSE origin.
  PRESERVE_BLOCK_ASK = 3,
  // The user has blocked the DSE origin and has `ALLOWED` it before it became
  // the DSE origin, preserve the latest decision.
  PRESERVE_BLOCK_ALLOW = 4,
  // The user has blocked the DSE origin and has `BLOCKED` it before it became
  // the DSE origin as well.
  PRESERVE_BLOCK_BLOCK = 5,
  // There has been an invalid transition.
  INVALID_END_STATE = 6,

  // Always keep at the end.
  kMaxValue = INVALID_END_STATE,
};

// LINT.IfChange(PermissionPredictionSource)

// This enum backs up the 'PermissionPredictionSource` histogram enum. It
// indicates whether the permission prediction was done by the local on device
// model or by the server side model (or both).
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class PermissionPredictionSource {
  ON_DEVICE_TFLITE = 0,
  SERVER_SIDE = 1,
  ONDEVICE_AI_AND_SERVER_SIDE = 2,

  // Always keep at the end.
  kMaxValue = ONDEVICE_AI_AND_SERVER_SIDE,
};

// LINT.ThenChange(//tools/metrics/histograms/metadata/permissions/enums.xml:PermissionPredictionSource)

// This enum backs up the 'PageInfoDialogAccessType' histogram enum.
// It is used for collecting page info access type metrics in the context of
// the confirmation chip.
enum class PageInfoDialogAccessType {
  // The user opened page info by clicking on the lock in a situation that is
  // considered independent of the display of a confirmation chip.
  LOCK_CLICK = 0,
  // The user opened page info by clicking on the lock while a confirmation chip
  // was being displayed.
  LOCK_CLICK_DURING_CONFIRMATION_CHIP = 1,
  // The user opened page info by clicking on the confirmation chip while it was
  // being displayed.
  CONFIRMATION_CHIP_CLICK = 2,

  // The user opened page info by clicking on the lock within
  // 'kConfirmationConsiderationDurationForUma' after confirmation chip has
  // collapsed. This click may be considered influenced by the displaying of the
  // confirmation chip.
  LOCK_CLICK_SHORTLY_AFTER_CONFIRMATION_CHIP = 3,

  // Always keep at the end.
  kMaxValue = LOCK_CLICK_SHORTLY_AFTER_CONFIRMATION_CHIP,
};

constexpr auto kConfirmationConsiderationDurationForUma = base::Seconds(20);

// This enum backs up the
// 'Permissions.PageInfo.ChangedWithin1m.{PermissionType}' histograms enum. It
// is used for collecting page info permission change metrics following in the
// first minute after a PermissionAction has been taken. Note that
// PermissionActions  DISMISSED and IGNORED are not taken into account, as they
// don't have an effect on the content settings.
enum class PermissionChangeAction {
  // PermissionAction was one of {GRANTED, GRANTED_ONCE} and the content
  // setting is changed to CONTENT_SETTING_BLOCK.
  REVOKED = 0,

  // PermissionAction was DENIED and the content setting is changed to
  // CONTENT_SETTING_ALLOW.
  REALLOWED = 1,

  // PermissionAction was one of {GRANTED, GRANTED_ONCE} and the content setting
  // is changed to CONTENT_SETTING_DEFAULT.
  RESET_FROM_ALLOWED = 2,

  // PermissionAction was DENIED and the content setting is changed to
  // CONTENT_SETTING_DEFAULT.
  RESET_FROM_DENIED = 3,

  // For one time grantable permissions, the user can toggle a remember checkbox
  // in the secondary page info page which toggles grants between permanent
  // grant and one time grant.
  REMEMBER_CHECKBOX_TOGGLED = 4,

  // Always keep at the end.
  kMaxValue = REMEMBER_CHECKBOX_TOGGLED,
};

// LINT.IfChange(ElementAnchoredBubbleAction)
enum class ElementAnchoredBubbleAction {
  // Site level permission was granted.
  kGranted = 0,

  // Site level permission was granted once.
  kGrantedOnce = 1,

  // Site level permission was denied.
  kDenied = 2,

  // Acknowledging the prompt informing the user a permission is managed by
  // admin.
  kOk = 3,

  // The prompt was dismissed by the user clicking on the [X] button.
  kDismissedXButton = 4,

  // The prompt was dismissed by the user clicking outside of the prompt area.
  kDismissedScrim = 5,

  // User clicked "Open system settings" to manage OS level permission prompts.
  kSystemSettings = 6,

  // Always keep at the end.
  kMaxValue = kSystemSettings,
};
// LINT.ThenChange(//tools/metrics/histograms/enums.xml:ElementAnchoredBubbleAction)

// The reason the permission action `PermissionAction::IGNORED` was triggered.
enum class PermissionIgnoredReason {
  // Ignore was triggered due to closure of the browser window
  WINDOW_CLOSED = 0,

  // Ignore was triggered due to closure of the tab
  TAB_CLOSED = 1,

  // Ignore was triggered due to navigation
  NAVIGATION = 2,

  // Catches all other cases
  UNKNOWN = 3,

  // Always keep at the end
  NUM,
};

// This enum backs up the
// 'Permissions.PageInfo.Changed.{PermissionType}.Reallowed.Outcome' histograms
// enum. It is used for collecting permission usage rates after permission
// status was reallowed via PageInfo. It is applicable only if permission is
// allowed as all other states are no-op for an origin.
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class PermissionChangeInfo {
  kInfobarShownPageReloadPermissionUsed = 0,

  kInfobarShownPageReloadPermissionNotUsed = 1,

  kInfobarShownNoPageReloadPermissionUsed = 2,

  kInfobarShownNoPageReloadPermissionNotUsed = 3,

  kInfobarNotShownPageReloadPermissionUsed = 4,

  kInfobarNotShownPageReloadPermissionNotUsed = 5,

  kInfobarNotShownNoPageReloadPermissionUsed = 6,

  kInfobarNotShownNoPageReloadPermissionNotUsed = 7,

  // Always keep at the end.
  kMaxValue = kInfobarNotShownNoPageReloadPermissionNotUsed,
};

// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.components.permissions
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: DismissalType
enum class DismissalType {
  // Fallback if a more specific dismissal type is not available..
  kUnspecified = 0,

  // The user dismissed by touching the back button.
  kNavigateBack = 1,  //

  // The user dismissed by touching outside the scrim
  kTouchOutside = 2,

  // It's possible for the context to be null if a prompt is
  // dequeued after the user backgrounds the browser and cleanup has already
  // happened. In that case, the prompt gets quietly dismissed.
  kAutodismissNoContext = 3,

  // The user accepted the site-level prompt but denied the
  // app-level prompt (= OS prompt), in which case the permission request gets
  // quietly dismissed.
  kAutodismissOsDenied = 4,

  // It's possible that the modal dialog manager is null when showing a dialog,
  // for example if the tab has been navigated/closed or the layout might not be
  // inflated in some embedders (e.g WebEngine).
  kAutodismissNoDialogManager = 5,

  // Always keep this at the end.
  kMaxValue = kAutodismissNoDialogManager,
};

// Provides a convenient way of logging UMA for permission related operations.
class PermissionUmaUtil {
 public:
  using PredictionGrantLikelihood =
      PermissionPrediction_Likelihood_DiscretizedLikelihood;

  static const char kPermissionsPromptShown[];
  static const char kPermissionsPromptShownGesture[];
  static const char kPermissionsPromptShownNoGesture[];
  static const char kPermissionsPromptAccepted[];
  static const char kPermissionsPromptAcceptedGesture[];
  static const char kPermissionsPromptAcceptedNoGesture[];
  static const char kPermissionsPromptAcceptedOnce[];
  static const char kPermissionsPromptAcceptedOnceGesture[];
  static const char kPermissionsPromptAcceptedOnceNoGesture[];
  static const char kPermissionsPromptDenied[];
  static const char kPermissionsPromptDeniedGesture[];
  static const char kPermissionsPromptDeniedNoGesture[];
  static const char kPermissionsPromptDismissed[];

  static const char kPermissionsExperimentalUsagePrefix[];
  static const char kPermissionsActionPrefix[];

  PermissionUmaUtil() = delete;
  PermissionUmaUtil(const PermissionUmaUtil&) = delete;
  PermissionUmaUtil& operator=(const PermissionUmaUtil&) = delete;

  static void PermissionRequested(ContentSettingsType permission);

  static void RecordActivityIndicator(std::set<ContentSettingsType> permissions,
                                      bool blocked,
                                      bool blocked_system_level,
                                      bool clicked);

  static void RecordDismissalType(
      const std::vector<ContentSettingsType>& content_settings_types,
      PermissionPromptDisposition ui_disposition,
      DismissalType dismissalType);

  static void RecordPermissionRequestedFromFrame(
      ContentSettingsType content_settings_type,
      content::RenderFrameHost* rfh);

  static void PermissionRequestPreignored(blink::PermissionType permission);

  // Records the revocation UMA and UKM metrics for ContentSettingsTypes that
  // have user facing permission prompts. The passed in `permission` must be
  // such that PermissionUtil::IsPermission(permission) returns true.
  static void PermissionRevoked(ContentSettingsType permission,
                                PermissionSourceUI source_ui,
                                const GURL& revoked_origin,
                                content::BrowserContext* browser_context);

  static void RecordEmbargoPromptSuppression(
      PermissionEmbargoStatus embargo_status);

  static void RecordEmbargoPromptSuppressionFromSource(
      content::PermissionStatusSource source);

  static void RecordEmbargoStatus(PermissionEmbargoStatus embargo_status);

  static void RecordPermissionRecoverySuccessRate(
      ContentSettingsType permission,
      bool is_used,
      bool show_infobar,
      bool page_reload);

  // This gets recorded during the creation process of a prompt, but only for
  // prompts that aren't labeled as abusive or disruptive.
  static void RecordPermissionPromptAttempt(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      bool can_display_prompt);

  // UMA specifically for when permission prompts are shown. This should be
  // roughly equivalent to the metrics above, however it is
  // useful to have separate UMA to a few reasons:
  // - to account for, and get data on coalesced permission bubbles
  // - there are other types of permissions prompts (e.g. download limiting)
  //   which don't go through PermissionContext
  // - the above metrics don't always add up (e.g. sum of
  //   granted+denied+dismissed+ignored is not equal to requested), so it is
  //   unclear from those metrics alone how many prompts are seen by users.
  static void PermissionPromptShown(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests);

  static void PermissionPromptResolved(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      content::WebContents* web_contents,
      PermissionAction permission_action,
      base::TimeDelta time_to_action,
      PermissionPromptDisposition ui_disposition,
      std::optional<PermissionPromptDispositionReason> ui_reason,
      std::optional<std::vector<ElementAnchoredBubbleVariant>> variants,
      std::optional<PredictionGrantLikelihood> predicted_grant_likelihood,
      std::optional<PermissionRequestRelevance> permission_request_relevance,
      std::optional<bool> prediction_decision_held_back,
      std::optional<permissions::PermissionIgnoredReason> ignored_reason,
      bool did_show_prompt,
      bool did_click_manage,
      bool did_click_learn_more);

  static void RecordCrowdDenyDelayedPushNotification(base::TimeDelta delay);

  static void RecordCrowdDenyVersionAtAbuseCheckTime(
      const std::optional<base::Version>& version);

  static void RecordElementAnchoredBubbleDismiss(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      DismissedReason reason);

  static void RecordElementAnchoredBubbleOsMetrics(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      OsScreen screen,
      OsScreenAction action,
      base::TimeDelta time_to_action);

  static void RecordElementAnchoredBubbleVariantUMA(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      ElementAnchoredBubbleVariant variant);

  // Record UMAs related to the Android "Missing permissions" infobar.
  static void RecordMissingPermissionInfobarShouldShow(
      bool should_show,
      const std::vector<ContentSettingsType>& content_settings_types);
  static void RecordMissingPermissionInfobarAction(
      PermissionAction action,
      const std::vector<ContentSettingsType>& content_settings_types);

  static void RecordPermissionUsage(ContentSettingsType permission_type,
                                    content::BrowserContext* browser_context,
                                    content::WebContents* web_contents,
                                    const GURL& requesting_origin);

  static void RecordPermissionUsageNotificationShown(
      bool did_user_always_allow_notifications,
      bool is_allowlisted,
      int suspicious_score,
      content::BrowserContext* browser_context,
      const GURL& requesting_origin,
      uint64_t site_engagement_level);

  static void RecordTimeElapsedBetweenGrantAndUse(
      ContentSettingsType type,
      base::TimeDelta delta,
      content_settings::SettingSource source);

  static void RecordTimeElapsedBetweenGrantAndRevoke(ContentSettingsType type,
                                                     base::TimeDelta delta);

  static void RecordAutoDSEPermissionReverted(
      ContentSettingsType permission_type,
      ContentSetting backed_up_setting,
      ContentSetting effective_setting,
      ContentSetting end_state_setting);

  static void RecordDSEEffectiveSetting(ContentSettingsType permission_type,
                                        ContentSetting setting);

  static void RecordPermissionPredictionSource(
      PermissionPredictionSource prediction_type);

  static void RecordPermissionPredictionServiceHoldback(
      RequestType request_type,
      PredictionModelType model_type,
      bool is_heldback);

  static void RecordPageInfoDialogAccessType(
      PageInfoDialogAccessType access_type);

  static std::string GetOneTimePermissionEventHistogram(
      ContentSettingsType type);

  static void RecordOneTimePermissionEvent(ContentSettingsType type,
                                           OneTimePermissionEvent event);

  static void RecordPageInfoPermissionChangeWithin1m(
      ContentSettingsType type,
      PermissionAction previous_action,
      ContentSetting setting_after);

  static void RecordPageInfoPermissionChange(ContentSettingsType type,
                                             ContentSetting setting_before,
                                             ContentSetting setting_after,
                                             bool suppress_reload_page_bar);

  static std::string GetPermissionActionString(
      PermissionAction permission_action);

  static std::string GetPredictionModelString(PredictionModelType model_type);

  static std::string GetPromptDispositionString(
      PermissionPromptDisposition ui_disposition);

  static std::string GetPromptDispositionReasonString(
      PermissionPromptDispositionReason ui_disposition_reason);

  static std::string GetRequestTypeString(RequestType request_type);

  static bool IsPromptDispositionQuiet(
      PermissionPromptDisposition prompt_disposition);

  static bool IsPromptDispositionLoud(
      PermissionPromptDisposition prompt_disposition);

  static void RecordIgnoreReason(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      PermissionPromptDisposition prompt_disposition,
      PermissionIgnoredReason reason);

  // Record metrics related to usage of permissions delegation.
  static void RecordPermissionsUsageSourceAndPolicyConfiguration(
      ContentSettingsType content_settings_type,
      content::RenderFrameHost* render_frame_host);

  static void RecordCrossOriginFrameActionAndPolicyConfiguration(
      ContentSettingsType content_settings_type,
      PermissionAction action,
      content::RenderFrameHost* render_frame_host);

  static void RecordTopLevelPermissionsHeaderPolicyOnNavigation(
      content::RenderFrameHost* render_frame_host);

  // Logs a metric that captures how long since revocation, due to a site being
  // considered unused, the user regrants a revoked permission.
  static void RecordPermissionRegrantForUnusedSites(
      const GURL& origin,
      ContentSettingsType request_type,
      PermissionSourceUI source_ui,
      content::BrowserContext* browser_context,
      base::Time current_time);

  static std::optional<uint32_t> GetDaysSinceUnusedSitePermissionRevocation(
      const GURL& origin,
      ContentSettingsType content_settings_type,
      base::Time current_time,
      HostContentSettingsMap* hcsm);

  // Records UKM metrics for ContentSettingsTypes that have user facing
  // permission prompts triggered by the user clicking on the Embedded
  // Permission Element. The passed in `permission` must be such that
  // PermissionUtil::IsPermission(permission) returns true.
  static void RecordElementAnchoredPermissionPromptAction(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      const std::vector<base::WeakPtr<permissions::PermissionRequest>>&
          screen_requests,
      ElementAnchoredBubbleAction action,
      ElementAnchoredBubbleVariant variant,
      int screen_counter,
      const GURL& requesting_origin,
      content::WebContents* web_contents,
      content::BrowserContext* browser_context);

  // Records `TimeDelta` between two consecutive indicators of the same
  // `RequestTypeForUma`.
  static void RecordPermissionIndicatorElapsedTimeSinceLastUsage(
      RequestTypeForUma request_type,
      base::TimeDelta time_delta);

  static void RecordPermissionRequestRelevance(
    permissions::RequestType permission_request_type,
      PermissionRequestRelevance permission_request_relevance,
      std::string model_version);

  // Records if the browser was always active while the prompt was
  // displaying.
  static void RecordBrowserAlwaysActiveWhilePrompting(
      RequestTypeForUma request_type,
      bool embedded_permission_element_initiated,
      bool always_active);

  // Records if the browser was always active before user's interaction.
  static void RecordActionBrowserAlwaysActive(RequestTypeForUma request_type,
                                              std::string permission_action,
                                              bool always_active);

  // Records the execution time of prediction model inquiries.
  static void RecordPredictionModelInquireTime(
      base::TimeTicks model_inquire_start_time,
      PredictionModelType model_type);

  // Records if the browser was active at the time the prompt started displaying
  static void RecordPromptShownInActiveBrowser(
      RequestTypeForUma request_type,
      bool embedded_permission_element_initiated,
      bool active);

  // A scoped class that will check the current resolved content setting on
  // construction and report a revocation metric accordingly if the revocation
  // condition is met (from ALLOW to something else).
  class ScopedRevocationReporter {
   public:
    ScopedRevocationReporter(content::BrowserContext* browser_context,
                             const GURL& primary_url,
                             const GURL& secondary_url,
                             ContentSettingsType content_type,
                             PermissionSourceUI source_ui);

    ScopedRevocationReporter(content::BrowserContext* browser_context,
                             const ContentSettingsPattern& primary_pattern,
                             const ContentSettingsPattern& secondary_pattern,
                             ContentSettingsType content_type,
                             PermissionSourceUI source_ui);

    ~ScopedRevocationReporter();

    // Returns true if a ScopedRevocationReporter instance is in scope.
    static bool IsInstanceInScope();

   private:
    raw_ptr<content::BrowserContext> browser_context_;
    const GURL primary_url_;
    const GURL secondary_url_;
    ContentSettingsType content_type_;
    PermissionSourceUI source_ui_;
    bool is_initially_allowed_;
    base::Time last_modified_date_;
  };

 private:
  friend class PermissionUmaUtilTest;

  // Records UMA and UKM metrics for ContentSettingsTypes that have user
  // facing permission prompts. The passed in `permission` must be such that
  // PermissionUtil::IsPermission(permission) returns true.
  // web_contents may be null when for recording non-prompt actions.
  static void RecordPermissionAction(
      ContentSettingsType permission,
      PermissionAction action,
      PermissionSourceUI source_ui,
      PermissionRequestGestureType gesture_type,
      base::TimeDelta time_to_action,
      PermissionPromptDisposition ui_disposition,
      std::optional<PermissionPromptDispositionReason> ui_reason,
      std::optional<std::vector<ElementAnchoredBubbleVariant>> variants,
      const GURL& requesting_origin,
      content::WebContents* web_contents,
      content::BrowserContext* browser_context,
      content::RenderFrameHost* render_frame_host,
      std::optional<PredictionGrantLikelihood> predicted_grant_likelihood,
      std::optional<PermissionRequestRelevance> permission_request_relevance,
      std::optional<bool> prediction_decision_held_back);

  // Records |count| total prior actions for a prompt of type |permission|
  // for a single origin using |prefix| for the metric.
  static void RecordPermissionPromptPriorCount(ContentSettingsType permission,
                                               const std::string& prefix,
                                               int count);

  static void RecordPromptDecided(
      const std::vector<std::unique_ptr<PermissionRequest>>& requests,
      bool accepted,
      bool is_one_time);
};

}  // namespace permissions

#endif  // COMPONENTS_PERMISSIONS_PERMISSION_UMA_UTIL_H_