File: ad_tracker.h

package info (click to toggle)
chromium 141.0.7390.107-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,254,812 kB
  • sloc: cpp: 35,264,957; ansic: 7,169,920; javascript: 4,250,185; python: 1,460,636; asm: 950,788; xml: 751,751; pascal: 187,972; sh: 89,459; perl: 88,691; objc: 79,953; sql: 53,924; cs: 44,622; fortran: 24,137; makefile: 22,319; tcl: 15,277; php: 14,018; yacc: 8,995; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (209 lines) | stat: -rw-r--r-- 8,219 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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_AD_TRACKER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_AD_TRACKER_H_

#include <stdint.h>

#include <optional>
#include <variant>

#include "base/feature_list.h"
#include "components/subresource_filter/core/common/scoped_rule.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/ad_script_identifier.h"
#include "third_party/blink/renderer/platform/heap/collection_support/heap_hash_map.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "v8/include/v8.h"

namespace blink {

class Document;
class ExecutionContext;
class LocalFrame;
enum class ResourceType : uint8_t;

namespace probe {
class AsyncTaskContext;
class CallFunction;
class ExecuteScript;
}  // namespace probe

// Tracker for tagging resources as ads based on the call stack scripts.
// The tracker is maintained per local root.
class CORE_EXPORT AdTracker : public GarbageCollected<AdTracker> {
 public:
  struct NoProvenance {};

  // Represents the reason why a script is classified as an ad. It can be one
  // of:
  // - NoProvenance: The script has neither an ancestor nor a rule match.
  // - subresource_filter::ScopedRule: The script is flagged by the subresource
  //   filter.
  // - script_id: The script itself is not flagged, but another ad
  //   script (the "ancestor") exists in its creation stack.
  using AdProvenance =
      std::variant<NoProvenance, subresource_filter::ScopedRule, int>;

  enum class StackType { kBottomOnly, kBottomAndTop };

  struct AdScriptAncestry {
    // A chain of `AdScriptIdentifier`s representing the ancestry of an ad
    // script. The chain is ordered from the script itself (lower level) up to
    // its root ancestor that was flagged by filterlist.
    Vector<AdScriptIdentifier> ancestry_chain;

    // The filterlist rule that caused the root (last) script in
    // `ancestry_chain` to be ad-tagged.
    subresource_filter::ScopedRule root_script_filterlist_rule;

    // A brief summary of the ancestry. Useful for intervention reports.
    String ToString() const;
  };

  // Finds an AdTracker for a given ExecutionContext.
  static AdTracker* FromExecutionContext(ExecutionContext*);

  static bool IsAdScriptExecutingInDocument(
      Document* document,
      StackType stack_type = StackType::kBottomAndTop);

  // Instrumenting methods.
  // Called when a script module or script gets executed from native code.
  void Will(const probe::ExecuteScript&);
  void Did(const probe::ExecuteScript&);

  // Called when a function gets called from native code.
  void Will(const probe::CallFunction&);
  void Did(const probe::CallFunction&);

  // Called when a subresource request is about to be sent or is redirected.
  // Returns true if any of the following are true:
  // - the resource is loaded in an ad iframe
  // - |known_ad| is true
  // - ad script is in the v8 stack and the resource was not requested by CSS.
  // Virtual for testing.
  virtual bool CalculateIfAdSubresource(
      ExecutionContext* execution_context,
      const KURL& request_url,
      ResourceType resource_type,
      const FetchInitiatorInfo& initiator_info,
      bool known_ad,
      const subresource_filter::ScopedRule& rule);

  // Called when an async task is created. Check at this point for ad script on
  // the stack and annotate the task if so.
  void DidCreateAsyncTask(probe::AsyncTaskContext* task_context);

  // Called when an async task is eventually run.
  void DidStartAsyncTask(probe::AsyncTaskContext* task_context);

  // Called when the task has finished running.
  void DidFinishAsyncTask(probe::AsyncTaskContext* task_context);

  // Returns true if any script in the pseudo call stack has previously been
  // identified as an ad resource, if the current ExecutionContext is a known ad
  // execution context, or if the script at the top of isolate's
  // stack is ad script. Whether to look at just the bottom of the
  // stack or the top and bottom is indicated by `stack_type`. kBottomAndTop is
  // generally best as it catches more ads, but if you're calling very
  // frequently then consider just the bottom of the stack for performance sake.
  //
  // Output Parameters:
  // - `out_ad_script_ancestry`: if non-null and there is ad script in the
  //   stack, this will be populated with the ad script's ancestry and the
  //   triggering filterlist rule. See `AdScriptAncestry` for more details on
  //   the populated fields.
  virtual bool IsAdScriptInStack(
      StackType stack_type,
      AdScriptAncestry* out_ad_script_ancestry = nullptr);

  virtual void Trace(Visitor*) const;

  void Shutdown();
  explicit AdTracker(LocalFrame*);
  AdTracker(const AdTracker&) = delete;
  AdTracker& operator=(const AdTracker&) = delete;
  virtual ~AdTracker();

 private:
  friend class FrameFetchContextSubresourceFilterTest;
  friend class AdTrackerSimTest;
  friend class AdTrackerTest;

  struct AdScriptData {
    AdScriptIdentifier id;
    AdProvenance provenance;
  };

  ExecutionContext* GetCurrentExecutionContext(v8::Isolate*);

  // Similar to the public IsAdScriptInStack method but instead of returning an
  // ancestry chain, it returns only one script (the most immediate one).
  bool IsAdScriptInStackHelper(
      StackType stack_type,
      std::optional<AdScriptIdentifier>* out_ad_script);

  bool IsKnownAdScript(ExecutionContext*, const String& url);

  // Adds the given `url` and its associated `ad_provenance` to the set of known
  // ad scripts associated with the provided `execution_context`.
  void AppendToKnownAdScripts(ExecutionContext& execution_context,
                              const String& url,
                              AdProvenance ad_provenance);

  // Handles the discovery of a script ID for a known ad script. It creates and
  // links a new AdScriptIdentifier (with `script_id` and `v8_context`) to the
  // provenance of `script_name`. The new link is kept in `script_provenances_`.
  //
  // Prerequisites: `script_name` is a known ad script in `execution_context`.
  void OnScriptIdAvailableForKnownAdScript(
      ExecutionContext* execution_context,
      const v8::Local<v8::Context>& v8_context,
      const String& script_name,
      int script_id);

  // Retrieves the ancestry chain of a given ad script (inclusive) and and the
  // triggering filterlist rule. See `AdScriptAncestry` for more details on the
  // populated fields.
  AdScriptAncestry GetAncestry(const AdScriptIdentifier& ad_script);

  Member<LocalFrame> local_root_;

  // Indicates the bottom-most synchronous ad script on the stack or
  // `std::nullopt` if there isn't one.
  std::optional<int> bottom_most_ad_script_;

  // Indicates the bottom-most ad script on the async stack or `std::nullopt`
  // if there isn't one.
  std::optional<AdScriptIdentifier> bottom_most_async_ad_script_;

  // Maps the URL of a detected ad script to its AdProvenance.
  //
  // Script Identification:
  // - Scripts with a resource URL are identified by that URL.
  // - Inline scripts (without a URL) are assigned a unique synthetic URL
  //   generated by `GenerateFakeUrlFromScriptId()`.
  using KnownAdScriptsAndProvenance = HashMap<String, AdProvenance>;

  // Tracks ad scripts detected outside of ad-frame contexts.
  HeapHashMap<WeakMember<ExecutionContext>, KnownAdScriptsAndProvenance>
      context_known_ad_scripts_;

  // A map of all known ad script ids to their metadata.
  HashMap<int, AdScriptData> ad_script_data_;

  // The number of ad-related async tasks currently running in the stack.
  int running_ad_async_tasks_ = 0;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_AD_TRACKER_H_