Chromium Chronicle #15:限制目標瀏覽權限

第 15 集:Joe Mason 在蒙特婁,PQ (2020 年 11 月)
先前劇集

Chrome 是一項擁有許多子系統的大型專案。我們通常會找出為某個元件撰寫的程式碼,在其他地方很實用,但可能有隱藏的限制。為了安全起見,請禁止外部人士存取危險功能。 舉例來說,自訂函式會根據特定效能需求而調整:

// Blazing fast for 2-char strings, O(n^3) otherwise.
std::string ConcatShortStringsFast(const std::string& a, const std::string& b);

您可以透過多種方式限制存取權,GN 瀏覽權限規則會根據目標,阻止元件外的程式碼。根據預設,所有目標都能顯示,但您可以修改:

# In components/restricted_component/BUILD.gn
visibility = [
  # Applies to all targets in this file.
  # Only the given targets can depend on them.
  "//components/restricted_component:*",
  "//components/authorized_other_component:a_single_target",
]
source_set("internal") {
  # This dangerous target should be locked down even more.
  visibility = [ "//components/restricted_component:privileged_target" ]
}

瀏覽權限宣告會以 gn check 進行驗證,此程序會在每個 GN 版本中執行。

另一種機制是 DEPS include_rules,它會限制標頭檔案的存取權。每個目錄都會繼承父項的 include_rules,並可在其專屬的 DEPS 檔案中修改這些規則。來自外部目錄的所有標頭檔案都必須獲得 include_rules 允許。

# In //components/authorized_other_component/DEPS
include_rules = [
  # Common directories like //base are inherited from
  # //components/DEPS or //DEPS. Also allow includes from
  # restricted_component, but not restricted_component/internal.
  "+components/restricted_component",
  "-components/restricted_component/internal",
  # But do allow a single header from internal, for testing.
  "+components/restricted_component/internal/test_support.h",
]

為確保這些依附元件正確無誤,「將目錄新增至 include_rules 的變更必須經該目錄的 OWNERS 核准」。不必獲得核准就能使用 include_rules 限制目錄!您可以新增 include_rule 來出價,確保所有變更元件的使用者記得不使用特定標題。

include_rules 會由預先提交項目檢查,因此在嘗試上傳變更之前,您不會看到任何錯誤。如要在不上傳的情況下測試 include_rules,請執行 buildtools/checkdeps/checkdeps.py <directory>

資源