File: chrome_content_rules_registry.cc

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 (442 lines) | stat: -rw-r--r-- 16,313 bytes parent folder | download | duplicates (5)
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
// Copyright 2012 The Chromium Authors
// 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/declarative_content/chrome_content_rules_registry.h"

#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/api/declarative/rules_registry_service.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/rules_registry_ids.h"
#include "extensions/common/api/declarative/declarative_constants.h"
#include "extensions/common/extension_id.h"

namespace extensions {

//
// EvaluationScope
//

// Used to coalesce multiple requests for evaluation into a zero or one actual
// evaluations (depending on the EvaluationDisposition).  This is required for
// correctness when multiple trackers respond to the same event. Otherwise,
// executing the request from the first tracker will be done before the tracked
// state has been updated for the other trackers.
class ChromeContentRulesRegistry::EvaluationScope {
 public:
  // Default disposition is PERFORM_EVALUATION.
  explicit EvaluationScope(ChromeContentRulesRegistry* registry);
  EvaluationScope(ChromeContentRulesRegistry* registry,
                  EvaluationDisposition disposition);

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

  ~EvaluationScope();

 private:
  const raw_ptr<ChromeContentRulesRegistry> registry_;
  const EvaluationDisposition previous_disposition_;
};

ChromeContentRulesRegistry::EvaluationScope::EvaluationScope(
    ChromeContentRulesRegistry* registry)
    : EvaluationScope(registry, DEFER_REQUESTS) {}

ChromeContentRulesRegistry::EvaluationScope::EvaluationScope(
    ChromeContentRulesRegistry* registry,
    EvaluationDisposition disposition)
    : registry_(registry),
      previous_disposition_(registry_->evaluation_disposition_) {
  DCHECK_NE(EVALUATE_REQUESTS, disposition);
  registry_->evaluation_disposition_ = disposition;
}

ChromeContentRulesRegistry::EvaluationScope::~EvaluationScope() {
  registry_->evaluation_disposition_ = previous_disposition_;
  if (registry_->evaluation_disposition_ == EVALUATE_REQUESTS) {
    for (content::WebContents* tab : registry_->evaluation_pending_)
      registry_->EvaluateConditionsForTab(tab);
    registry_->evaluation_pending_.clear();
  }
}

//
// ChromeContentRulesRegistry
//

ChromeContentRulesRegistry::ChromeContentRulesRegistry(
    content::BrowserContext* browser_context,
    RulesCacheDelegate* cache_delegate,
    PredicateEvaluatorsFactory evaluators_factory)
    : ContentRulesRegistry(browser_context,
                           declarative_content_constants::kOnPageChanged,
                           cache_delegate,
                           rules_registry_ids::kDefaultRulesRegistryID),
      evaluators_(std::move(evaluators_factory).Run(this)),
      evaluation_disposition_(EVALUATE_REQUESTS) {}

void ChromeContentRulesRegistry::NotifyPredicateStateUpdated(
    content::WebContents* contents) {
  switch (evaluation_disposition_) {
    case EVALUATE_REQUESTS:
      EvaluateConditionsForTab(contents);
      break;
    case DEFER_REQUESTS:
      evaluation_pending_.insert(contents);
      break;
    case IGNORE_REQUESTS:
      break;
  }
}

bool ChromeContentRulesRegistry::ShouldManagePredicatesForBrowserContext(
    content::BrowserContext* context) {
  return ManagingRulesForBrowserContext(context);
}

void ChromeContentRulesRegistry::MonitorWebContentsForRuleEvaluation(
    content::WebContents* contents) {
  // We rely on active_rules_ to have a key-value pair for |contents| to know
  // which WebContents we are working with.
  active_rules_[contents] =
      std::set<raw_ptr<const ContentRule, SetExperimental>>();

  EvaluationScope evaluation_scope(this);
  for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
       evaluators_)
    evaluator->TrackForWebContents(contents);
}

void ChromeContentRulesRegistry::DidFinishNavigation(
    content::WebContents* contents,
    content::NavigationHandle* navigation_handle) {
  if (base::Contains(active_rules_, contents)) {
    EvaluationScope evaluation_scope(this);
    for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
         evaluators_)
      evaluator->OnWebContentsNavigation(contents, navigation_handle);
  }
}

void ChromeContentRulesRegistry::WebContentsDestroyed(
    content::WebContents* web_contents) {
  active_rules_.erase(web_contents);
}

void ChromeContentRulesRegistry::OnWatchedPageChanged(
    content::WebContents* contents,
    const std::vector<std::string>& css_selectors) {
  if (base::Contains(active_rules_, contents)) {
    EvaluationScope evaluation_scope(this);
    for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
         evaluators_) {
      evaluator->OnWatchedPageChanged(contents, css_selectors);
    }
  }
}

ChromeContentRulesRegistry::ContentRule::ContentRule(
    const Extension* extension,
    std::vector<std::unique_ptr<const ContentCondition>> conditions,
    std::vector<std::unique_ptr<const ContentAction>> actions,
    int priority)
    : extension(extension),
      conditions(std::move(conditions)),
      actions(std::move(actions)),
      priority(priority) {}

ChromeContentRulesRegistry::ContentRule::~ContentRule() = default;

std::unique_ptr<const ChromeContentRulesRegistry::ContentRule>
ChromeContentRulesRegistry::CreateRule(
    const Extension* extension,
    const std::map<std::string, ContentPredicateFactory*>& predicate_factories,
    const api::events::Rule& api_rule,
    std::string* error) {
  std::vector<std::unique_ptr<const ContentCondition>> conditions;
  for (const base::Value& value : api_rule.conditions) {
    conditions.push_back(
        CreateContentCondition(extension, predicate_factories, value, error));
    if (!error->empty())
      return nullptr;
  }

  std::vector<std::unique_ptr<const ContentAction>> actions;
  for (const base::Value& value : api_rule.actions) {
    // TODO(crbug.com/40832669): Migrate api_rule to use base::Value::Dict to
    // avoid conversion.
    if (!value.is_dict()) {
      return nullptr;
    }

    actions.push_back(ContentAction::Create(browser_context(), extension,
                                            value.GetDict(), error));
    if (!error->empty())
      return nullptr;
  }

  // Note: |api_rule| may contain tags, but these are ignored.

  return std::make_unique<ContentRule>(extension, std::move(conditions),
                                       std::move(actions), *api_rule.priority);
}

bool ChromeContentRulesRegistry::ManagingRulesForBrowserContext(
    content::BrowserContext* context) {
  // Manage both the normal context and incognito contexts associated with it.
  return Profile::FromBrowserContext(context)->GetOriginalProfile() ==
      Profile::FromBrowserContext(browser_context());
}

// static
bool ChromeContentRulesRegistry::EvaluateConditionForTab(
    const ContentCondition* condition,
    content::WebContents* tab) {
  for (const std::unique_ptr<const ContentPredicate>& predicate :
       condition->predicates) {
    if (predicate && !predicate->IsIgnored() &&
        !predicate->GetEvaluator()->EvaluatePredicate(predicate.get(), tab)) {
      return false;
    }
  }

  return true;
}

std::set<
    raw_ptr<const ChromeContentRulesRegistry::ContentRule, SetExperimental>>
ChromeContentRulesRegistry::GetMatchingRules(content::WebContents* tab) const {
  const bool is_incognito_tab = tab->GetBrowserContext()->IsOffTheRecord();
  std::set<raw_ptr<const ContentRule, SetExperimental>> matching_rules;
  for (const RulesMap::value_type& rule_id_rule_pair : content_rules_) {
    const ContentRule* rule = rule_id_rule_pair.second.get();
    if (is_incognito_tab &&
        !ShouldEvaluateExtensionRulesForIncognitoRenderer(rule->extension))
      continue;

    for (const std::unique_ptr<const ContentCondition>& condition :
         rule->conditions) {
      if (EvaluateConditionForTab(condition.get(), tab))
        matching_rules.insert(rule);
    }
  }
  return matching_rules;
}

std::string ChromeContentRulesRegistry::AddRulesImpl(
    const ExtensionId& extension_id,
    const std::vector<const api::events::Rule*>& api_rules) {
  EvaluationScope evaluation_scope(this);
  const Extension* extension = ExtensionRegistry::Get(browser_context())
      ->enabled_extensions().GetByID(extension_id);
  CHECK(extension);

  std::string error;
  RulesMap new_rules;
  std::map<ContentPredicateEvaluator*,
           std::map<const void*, std::vector<const ContentPredicate*>>>
      new_predicates;

  std::map<std::string, ContentPredicateFactory*> predicate_factories;
  for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
       evaluators_) {
    predicate_factories[evaluator->GetPredicateApiAttributeName()] =
        evaluator.get();
  }

  for (auto* api_rule : api_rules) {
    ExtensionIdRuleIdPair rule_id(extension_id, *api_rule->id);
    DCHECK(content_rules_.find(rule_id) == content_rules_.end());

    std::unique_ptr<const ContentRule> rule(
        CreateRule(extension, predicate_factories, *api_rule, &error));
    if (!error.empty()) {
      // Notify evaluators that none of the created predicates will be tracked
      // after all.
      for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
           evaluators_) {
        if (!new_predicates[evaluator.get()].empty()) {
          evaluator->TrackPredicates(
              std::map<const void*, std::vector<const ContentPredicate*>>());
        }
      }

      return error;
    }
    DCHECK(rule);

    // Group predicates by evaluator and rule, so we can later notify the
    // evaluators that they have new predicates to manage.
    for (const std::unique_ptr<const ContentCondition>& condition :
         rule->conditions) {
      for (const std::unique_ptr<const ContentPredicate>& predicate :
           condition->predicates) {
        if (predicate.get()) {
          new_predicates[predicate->GetEvaluator()][rule.get()].push_back(
              predicate.get());
        }
      }
    }

    new_rules[rule_id] = std::move(rule);
  }

  // Notify the evaluators about their new predicates.
  for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
       evaluators_)
    evaluator->TrackPredicates(new_predicates[evaluator.get()]);

  // Wohoo, everything worked fine.
  content_rules_.insert(std::make_move_iterator(new_rules.begin()),
                        std::make_move_iterator(new_rules.end()));

  // Request evaluation for all WebContents, under the assumption that a
  // non-empty condition has been added.
  for (const auto& web_contents_rules_pair : active_rules_) {
    NotifyPredicateStateUpdated(web_contents_rules_pair.first);
  }

  return std::string();
}

std::string ChromeContentRulesRegistry::RemoveRulesImpl(
    const ExtensionId& extension_id,
    const std::vector<std::string>& rule_identifiers) {
  // Ignore evaluation requests in this function because it reverts actions on
  // any active rules itself. Otherwise, we run the risk of reverting the same
  // rule multiple times.
  EvaluationScope evaluation_scope(this, IGNORE_REQUESTS);

  std::vector<RulesMap::iterator> rules_to_erase;
  std::vector<const void*> predicate_groups_to_stop_tracking;
  for (const std::string& id : rule_identifiers) {
    // Skip unknown rules.
    auto content_rules_entry =
        content_rules_.find(std::make_pair(extension_id, id));
    if (content_rules_entry == content_rules_.end())
      continue;

    const ContentRule* rule = content_rules_entry->second.get();

    // Remove the ContentRule from active_rules_.
    for (auto& tab_rules_pair : active_rules_) {
      if (base::Contains(tab_rules_pair.second, rule)) {
        ContentAction::ApplyInfo apply_info =
            {rule->extension, browser_context(), tab_rules_pair.first,
             rule->priority};
        for (const auto& action : rule->actions)
          action->Revert(apply_info);
        tab_rules_pair.second.erase(rule);
      }
    }

    rules_to_erase.push_back(content_rules_entry);
    predicate_groups_to_stop_tracking.push_back(rule);
  }

  // Notify the evaluators to stop tracking the predicates that will be removed.
  for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
       evaluators_)
    evaluator->StopTrackingPredicates(predicate_groups_to_stop_tracking);

  // Remove the rules.
  for (auto it : rules_to_erase)
    content_rules_.erase(it);

  return std::string();
}

std::string ChromeContentRulesRegistry::RemoveAllRulesImpl(
    const ExtensionId& extension_id) {
  // Search all identifiers of rules that belong to extension |extension_id|.
  std::vector<std::string> rule_identifiers;
  for (const RulesMap::value_type& id_rule_pair : content_rules_) {
    const ExtensionIdRuleIdPair& extension_id_rule_id_pair = id_rule_pair.first;
    if (extension_id_rule_id_pair.first == extension_id)
      rule_identifiers.push_back(extension_id_rule_id_pair.second);
  }

  return RemoveRulesImpl(extension_id, rule_identifiers);
}

void ChromeContentRulesRegistry::EvaluateConditionsForTab(
    content::WebContents* tab) {
  std::set<raw_ptr<const ContentRule, SetExperimental>> matching_rules =
      GetMatchingRules(tab);
  if (matching_rules.empty() && !base::Contains(active_rules_, tab))
    return;

  std::set<raw_ptr<const ContentRule, SetExperimental>>& prev_matching_rules =
      active_rules_[tab];
  for (const ContentRule* rule : matching_rules) {
    ContentAction::ApplyInfo apply_info =
        {rule->extension, browser_context(), tab, rule->priority};
    if (!base::Contains(prev_matching_rules, rule)) {
      for (const std::unique_ptr<const ContentAction>& action : rule->actions)
        action->Apply(apply_info);
    } else {
      for (const std::unique_ptr<const ContentAction>& action : rule->actions)
        action->Reapply(apply_info);
    }
  }
  for (const ContentRule* rule : prev_matching_rules) {
    if (!base::Contains(matching_rules, rule)) {
      ContentAction::ApplyInfo apply_info =
          {rule->extension, browser_context(), tab, rule->priority};
      for (const std::unique_ptr<const ContentAction>& action : rule->actions)
        action->Revert(apply_info);
    }
  }

  if (matching_rules.empty())
    active_rules_[tab].clear();
  else
    swap(matching_rules, prev_matching_rules);
}

bool
ChromeContentRulesRegistry::ShouldEvaluateExtensionRulesForIncognitoRenderer(
    const Extension* extension) const {
  if (!util::IsIncognitoEnabled(extension->id(), browser_context()))
    return false;

  // Split-mode incognito extensions register their rules with separate
  // RulesRegistries per Original/OffTheRecord browser contexts, whereas
  // spanning-mode extensions share the Original browser context.
  if (util::CanCrossIncognito(extension, browser_context())) {
    // The extension uses spanning mode incognito. No rules should have been
    // registered for the extension in the OffTheRecord registry so
    // execution for that registry should never reach this point.
    CHECK(!browser_context()->IsOffTheRecord());
  } else {
    // The extension uses split mode incognito. Both the Original and
    // OffTheRecord registries may have (separate) rules for this extension.
    // Since we're looking at an incognito renderer, so only the OffTheRecord
    // registry should process its rules.
    if (!browser_context()->IsOffTheRecord())
      return false;
  }

  return true;
}

size_t ChromeContentRulesRegistry::GetActiveRulesCountForTesting() {
  size_t count = 0;
  for (const auto& web_contents_rules_pair : active_rules_)
    count += web_contents_rules_pair.second.size();
  return count;
}

ChromeContentRulesRegistry::~ChromeContentRulesRegistry() = default;

}  // namespace extensions