| // 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 "extensions/browser/api/declarative/rules_registry.h" | |
| #include <algorithm> | |
| #include <memory> | |
| #include <set> | |
| #include <utility> | |
| #include "base/check.h" | |
| #include "base/functional/bind.h" | |
| #include "base/logging.h" | |
| #include "base/strings/stringprintf.h" | |
| #include "base/strings/utf_string_conversions.h" | |
| #include "base/time/time.h" | |
| #include "base/values.h" | |
| #include "content/public/browser/browser_task_traits.h" | |
| #include "content/public/browser/browser_thread.h" | |
| #include "extensions/browser/api/declarative/constants.h" | |
| #include "extensions/browser/api/declarative/declarative_utils.h" | |
| #include "extensions/browser/api/declarative/rules_cache_delegate.h" | |
| #include "extensions/browser/extension_error.h" | |
| #include "extensions/browser/extension_registry.h" | |
| #include "extensions/browser/extensions_browser_client.h" | |
| #include "extensions/browser/state_store.h" | |
| #include "extensions/common/api/declarative/declarative_manifest_data.h" | |
| #include "extensions/common/extension.h" | |
| #include "extensions/common/extension_id.h" | |
| #include "extensions/common/extensions_client.h" | |
| #include "extensions/common/manifest_constants.h" | |
| namespace extensions { | |
| namespace { | |
| constexpr char kSuccess[] = ""; | |
| base::ListValue RulesToValue( | |
| const std::vector<const api::events::Rule*>& rules) { | |
| base::ListValue value; | |
| for (const auto* rule : rules) | |
| value.Append(rule->ToValue()); | |
| return value; | |
| } | |
| std::vector<api::events::Rule> RulesFromValue( | |
| const std::optional<base::Value>& value) { | |
| std::vector<api::events::Rule> rules; | |
| if (!value || !value->is_list()) | |
| return rules; | |
| rules.reserve(value->GetList().size()); | |
| for (const base::Value& dict_value : value->GetList()) { | |
| if (!dict_value.is_dict()) | |
| continue; | |
| auto rule = api::events::Rule::FromValue(dict_value.GetDict()); | |
| if (rule) { | |
| rules.push_back(std::move(rule).value()); | |
| } | |
| } | |
| return rules; | |
| } | |
| std::string ToId(int identifier) { | |
| return base::StringPrintf("_%d_", identifier); | |
| } | |
| } // namespace | |
| // RulesRegistry | |
| RulesRegistry::RulesRegistry(content::BrowserContext* browser_context, | |
| const std::string& event_name, | |
| RulesCacheDelegate* cache_delegate, | |
| int id) | |
| : browser_context_(browser_context), | |
| event_name_(event_name), | |
| id_(id), | |
| ready_(/*signaled=*/!cache_delegate), // Immediately ready if no cache | |
| // delegate to wait for. | |
| last_generated_rule_identifier_id_(0) { | |
| if (cache_delegate) { | |
| cache_delegate_ = cache_delegate->GetWeakPtr(); | |
| cache_delegate->Init(this); | |
| } | |
| } | |
| std::string RulesRegistry::AddRulesNoFill( | |
| const ExtensionId& extension_id, | |
| std::vector<api::events::Rule> rules_in, | |
| RulesDictionary* destination, | |
| std::vector<const api::events::Rule*>* rules_out) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| // Verify that all rule IDs are valid UTF-8 and new (including within this | |
| // batch, since deserialized rules bypass `CheckAndFillInOptionalRules`). | |
| std::set<RuleId> new_rule_ids; | |
| for (const auto& rule : rules_in) { | |
| if (!declarative::IsValidRuleId(rule.id)) { | |
| return declarative::kInvalidRuleIdError; | |
| } | |
| const RuleId& rule_id = *(rule.id); | |
| // Every rule should have a priority assigned. | |
| DCHECK(rule.priority); | |
| RulesDictionaryKey key(extension_id, rule_id); | |
| auto [_, inserted] = new_rule_ids.insert(rule_id); | |
| if (rules_.contains(key) || manifest_rules_.contains(key) || !inserted) { | |
| return base::StringPrintf(declarative::kDuplicateRuleIdError, | |
| rule_id.c_str()); | |
| } | |
| } | |
| std::vector<const api::events::Rule*> rule_ptrs; | |
| rule_ptrs.reserve(rules_in.size()); | |
| for (auto& rule : rules_in) | |
| rule_ptrs.push_back(&rule); | |
| std::string error = AddRulesImpl(extension_id, rule_ptrs); | |
| if (!error.empty()) | |
| return error; | |
| // Commit all rules into |rules_| on success. | |
| rule_ptrs.clear(); | |
| for (auto& rule : rules_in) { | |
| const RuleId& rule_id = *(rule.id); | |
| RulesDictionaryKey key(extension_id, rule_id); | |
| auto insert_result = destination->emplace(key, std::move(rule)); | |
| // All rule IDs are new so insert had better not have failed. | |
| CHECK(insert_result.second); | |
| if (rules_out) | |
| rule_ptrs.push_back(&(insert_result.first->second)); | |
| } | |
| if (rules_out) | |
| *rules_out = rule_ptrs; | |
| MaybeProcessChangedRules(extension_id); | |
| return kSuccess; | |
| } | |
| std::string RulesRegistry::AddRules( | |
| const ExtensionId& extension_id, | |
| std::vector<api::events::Rule> rules_in, | |
| std::vector<const api::events::Rule*>* rules_out) { | |
| return AddRulesInternal(extension_id, std::move(rules_in), &rules_, | |
| rules_out); | |
| } | |
| std::string RulesRegistry::AddRulesInternal( | |
| const ExtensionId& extension_id, | |
| std::vector<api::events::Rule> rules_in, | |
| RulesDictionary* destination, | |
| std::vector<const api::events::Rule*>* rules_out) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| std::string error = CheckAndFillInOptionalRules(extension_id, &rules_in); | |
| if (!error.empty()) | |
| return error; | |
| FillInOptionalPriorities(&rules_in); | |
| // TODO(crbug.com/40605870): `used_rule_identifiers_` is not rolled back if | |
| // `AddRulesNoFill()` fails, and is not populated when stored rules are | |
| // replayed in `DeserializeAndAddRules()`. | |
| return AddRulesNoFill(extension_id, std::move(rules_in), destination, | |
| rules_out); | |
| } | |
| std::string RulesRegistry::RemoveRules( | |
| const ExtensionId& extension_id, | |
| const std::vector<std::string>& rule_identifiers) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| // Deduplicate the list of rule identifiers to prevent removing the same | |
| // rule multiple times and invalidating iterators. | |
| std::vector<std::string> deduplicated_rule_identifiers = rule_identifiers; | |
| std::sort(deduplicated_rule_identifiers.begin(), | |
| deduplicated_rule_identifiers.end()); | |
| deduplicated_rule_identifiers.erase( | |
| std::unique(deduplicated_rule_identifiers.begin(), | |
| deduplicated_rule_identifiers.end()), | |
| deduplicated_rule_identifiers.end()); | |
| // Check if any of the rules are non-removable. | |
| for (const RuleId& rule_id : deduplicated_rule_identifiers) { | |
| RulesDictionaryKey lookup_key(extension_id, rule_id); | |
| auto itr = manifest_rules_.find(lookup_key); | |
| if (itr != manifest_rules_.end()) | |
| return declarative::kErrorCannotRemoveManifestRules; | |
| } | |
| std::string error = | |
| RemoveRulesImpl(extension_id, deduplicated_rule_identifiers); | |
| if (!error.empty()) | |
| return error; | |
| for (auto i = deduplicated_rule_identifiers.cbegin(); | |
| i != deduplicated_rule_identifiers.cend(); ++i) { | |
| RulesDictionaryKey lookup_key(extension_id, *i); | |
| rules_.erase(lookup_key); | |
| } | |
| MaybeProcessChangedRules(extension_id); | |
| RemoveUsedRuleIdentifiers(extension_id, deduplicated_rule_identifiers); | |
| return kSuccess; | |
| } | |
| std::string RulesRegistry::RemoveAllRules(const ExtensionId& extension_id) { | |
| std::string result = | |
| RulesRegistry::RemoveAllRulesNoStoreUpdate(extension_id, false); | |
| MaybeProcessChangedRules(extension_id); // Now update the prefs and store. | |
| return result; | |
| } | |
| std::string RulesRegistry::RemoveAllRulesNoStoreUpdate( | |
| const ExtensionId& extension_id, | |
| bool remove_manifest_rules) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| std::string error = RemoveAllRulesImpl(extension_id); | |
| if (!error.empty()) | |
| return error; | |
| auto remove_rules = [&extension_id](RulesDictionary& dictionary) { | |
| for (auto it = dictionary.begin(); it != dictionary.end();) { | |
| if (it->first.first == extension_id) | |
| dictionary.erase(it++); | |
| else | |
| ++it; | |
| } | |
| }; | |
| remove_rules(rules_); | |
| if (remove_manifest_rules) | |
| remove_rules(manifest_rules_); | |
| RemoveAllUsedRuleIdentifiers(extension_id); | |
| return kSuccess; | |
| } | |
| void RulesRegistry::GetRules(const ExtensionId& extension_id, | |
| const std::vector<std::string>& rule_identifiers, | |
| std::vector<const api::events::Rule*>* out) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| for (const auto& i : rule_identifiers) { | |
| RulesDictionaryKey lookup_key(extension_id, i); | |
| auto entry = rules_.find(lookup_key); | |
| if (entry != rules_.end()) | |
| out->push_back(&entry->second); | |
| entry = manifest_rules_.find(lookup_key); | |
| if (entry != manifest_rules_.end()) | |
| out->push_back(&entry->second); | |
| } | |
| } | |
| void RulesRegistry::GetRules(const ExtensionId& extension_id, | |
| RulesDictionary* rules, | |
| std::vector<const api::events::Rule*>* out) { | |
| for (auto& i : *rules) { | |
| const RulesDictionaryKey& key = i.first; | |
| if (key.first == extension_id) | |
| out->push_back(&i.second); | |
| } | |
| } | |
| void RulesRegistry::GetAllRules(const ExtensionId& extension_id, | |
| std::vector<const api::events::Rule*>* out) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| GetRules(extension_id, &manifest_rules_, out); | |
| GetRules(extension_id, &rules_, out); | |
| } | |
| void RulesRegistry::OnShutdown() { | |
| browser_context_ = nullptr; | |
| } | |
| void RulesRegistry::OnRemoved() { | |
| OnShutdown(); | |
| if (!ready_.is_signaled()) { | |
| MarkReady(); | |
| } | |
| } | |
| void RulesRegistry::OnExtensionUnloaded(const Extension* extension) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| std::string error = RemoveAllRulesImpl(extension->id()); | |
| if (!error.empty()) | |
| ReportInternalError(extension->id(), error); | |
| } | |
| void RulesRegistry::OnExtensionUninstalled(const Extension* extension) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| std::string error = RemoveAllRulesNoStoreUpdate(extension->id(), true); | |
| if (!error.empty()) | |
| ReportInternalError(extension->id(), error); | |
| } | |
| void RulesRegistry::OnExtensionLoaded(const Extension* extension) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| std::vector<const api::events::Rule*> rules; | |
| GetAllRules(extension->id(), &rules); | |
| const DeclarativeManifestData* declarative_data = | |
| DeclarativeManifestData::Get(extension); | |
| if (declarative_data) { | |
| std::vector<api::events::Rule> manifest_rules = | |
| declarative_data->RulesForEvent(event_name_); | |
| if (manifest_rules.size()) { | |
| std::string error = | |
| AddRulesInternal(extension->id(), std::move(manifest_rules), | |
| &manifest_rules_, nullptr); | |
| if (!error.empty()) | |
| ReportInternalError(extension->id(), error); | |
| } | |
| } | |
| std::string error = AddRulesImpl(extension->id(), rules); | |
| if (!error.empty()) | |
| ReportInternalError(extension->id(), error); | |
| } | |
| size_t RulesRegistry::GetNumberOfUsedRuleIdentifiersForTesting() const { | |
| size_t entry_count = 0u; | |
| for (const auto& used_rule_identifier : used_rule_identifiers_) { | |
| // Each extension is counted as 1 just for being there. Otherwise we miss | |
| // keys with empty values. | |
| entry_count += 1u + used_rule_identifier.second.size(); | |
| } | |
| return entry_count; | |
| } | |
| void RulesRegistry::DeserializeAndAddRules(const ExtensionId& extension_id, | |
| std::optional<base::Value> rules) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| // Since this is called in response to asynchronously loading rules from | |
| // storage, the extension may have been unloaded by the time this is called. | |
| if (!ExtensionRegistry::Get(browser_context()) | |
| ->enabled_extensions() | |
| .Contains(extension_id)) { | |
| return; | |
| } | |
| std::string error = | |
| AddRulesNoFill(extension_id, RulesFromValue(rules), &rules_, nullptr); | |
| if (!error.empty()) | |
| ReportInternalError(extension_id, error); | |
| } | |
| void RulesRegistry::ReportInternalError(const ExtensionId& extension_id, | |
| const std::string& error) { | |
| auto error_instance = std::make_unique<InternalError>( | |
| extension_id, base::UTF8ToUTF16(error), logging::LOGGING_ERROR); | |
| ExtensionsBrowserClient::Get()->ReportError(browser_context_, | |
| std::move(error_instance)); | |
| } | |
| RulesRegistry::~RulesRegistry() { | |
| } | |
| void RulesRegistry::MarkReady() { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| ready_.Signal(); | |
| } | |
| void RulesRegistry::ProcessChangedRules(const ExtensionId& extension_id) { | |
| DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
| DCHECK(process_changed_rules_requested_.contains(extension_id)); | |
| process_changed_rules_requested_[extension_id] = NOT_SCHEDULED_FOR_PROCESSING; | |
| std::vector<const api::events::Rule*> new_rules; | |
| GetRules(extension_id, &rules_, &new_rules); | |
| if (cache_delegate_) { | |
| cache_delegate_->UpdateRules(extension_id, RulesToValue(new_rules)); | |
| } | |
| } | |
| void RulesRegistry::MaybeProcessChangedRules(const ExtensionId& extension_id) { | |
| // Read and initialize |process_changed_rules_requested_[extension_id]| if | |
| // necessary. (Note that the insertion below will not overwrite | |
| // |process_changed_rules_requested_[extension_id]| if that already exists. | |
| std::pair<ProcessStateMap::iterator, bool> insertion = | |
| process_changed_rules_requested_.insert(std::make_pair( | |
| extension_id, | |
| browser_context_ ? NOT_SCHEDULED_FOR_PROCESSING : NEVER_PROCESS)); | |
| if (insertion.first->second != NOT_SCHEDULED_FOR_PROCESSING) | |
| return; | |
| process_changed_rules_requested_[extension_id] = SCHEDULED_FOR_PROCESSING; | |
| ready_.Post(FROM_HERE, | |
| base::BindOnce(&RulesRegistry::ProcessChangedRules, | |
| weak_ptr_factory_.GetWeakPtr(), extension_id)); | |
| } | |
| bool RulesRegistry::IsUniqueId(const ExtensionId& extension_id, | |
| const std::string& rule_id) const { | |
| auto identifiers = used_rule_identifiers_.find(extension_id); | |
| if (identifiers == used_rule_identifiers_.end()) | |
| return true; | |
| return !identifiers->second.contains(rule_id); | |
| } | |
| std::string RulesRegistry::GenerateUniqueId(const ExtensionId& extension_id) { | |
| while (!IsUniqueId(extension_id, ToId(last_generated_rule_identifier_id_))) | |
| ++last_generated_rule_identifier_id_; | |
| return ToId(last_generated_rule_identifier_id_); | |
| } | |
| std::string RulesRegistry::CheckAndFillInOptionalRules( | |
| const ExtensionId& extension_id, | |
| std::vector<api::events::Rule>* rules) { | |
| // First verify that all explicit rule IDs are valid UTF-8 and unique (both | |
| // against already-used IDs and within this batch) before mutating | |
| // `used_rule_identifiers_`. | |
| std::set<RuleIdentifier> seen_ids; | |
| for (const auto& rule : *rules) { | |
| if (!rule.id) { | |
| continue; | |
| } | |
| if (!declarative::IsValidRuleId(rule.id)) { | |
| return declarative::kInvalidRuleIdError; | |
| } | |
| const std::string& id = *rule.id; | |
| auto [_, inserted] = seen_ids.insert(id); | |
| if (!IsUniqueId(extension_id, id) || !inserted) { | |
| return "Id " + id + " was used multiple times."; | |
| } | |
| } | |
| // Insert all rules with explicit identifiers first, so that generated | |
| // identifiers cannot collide with identifiers passed by the caller. | |
| for (const auto& id : seen_ids) { | |
| used_rule_identifiers_[extension_id].insert(id); | |
| } | |
| // Now we generate IDs in case they were not specified in the rules. | |
| for (auto& rule : *rules) { | |
| if (!rule.id) { | |
| rule.id = GenerateUniqueId(extension_id); | |
| used_rule_identifiers_[extension_id].insert(*(rule.id)); | |
| } | |
| } | |
| return std::string(); | |
| } | |
| void RulesRegistry::FillInOptionalPriorities( | |
| std::vector<api::events::Rule>* rules) { | |
| for (auto& rule : *rules) { | |
| if (!rule.priority) | |
| rule.priority = DEFAULT_PRIORITY; | |
| } | |
| } | |
| void RulesRegistry::RemoveUsedRuleIdentifiers( | |
| const ExtensionId& extension_id, | |
| const std::vector<std::string>& identifiers) { | |
| std::vector<std::string>::const_iterator i; | |
| for (i = identifiers.begin(); i != identifiers.end(); ++i) | |
| used_rule_identifiers_[extension_id].erase(*i); | |
| } | |
| void RulesRegistry::RemoveAllUsedRuleIdentifiers( | |
| const ExtensionId& extension_id) { | |
| used_rule_identifiers_.erase(extension_id); | |
| } | |
| } // namespace extensions |